forked from tipichris/bbcwx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
desklet.js
3343 lines (3003 loc) · 120 KB
/
desklet.js
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* bbcwx - a Cinnamon Desklet displaying the weather retrieved
* from one of several web services.
*
* Copyright 2014 - 2015 Chris Hastie. Forked from accudesk@logan; original
* code Copyright 2013 loganj.
*
* Includes the marknote library, Copyright 2011 jbulb.org.
* Icons Copyright 2010 Merlin the Red, 2010 VClouds, 2010
* d3stroy and 2004 digitalchet.
* See help.html for further credits and license information.
*
* This program 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 3 of the License, or
* (at your option) any later version.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
const Gio = imports.gi.Gio;
const St = imports.gi.St;
const Desklet = imports.ui.desklet;
const Lang = imports.lang;
const Mainloop = imports.mainloop;
const Clutter = imports.gi.Clutter;
const GLib = imports.gi.GLib;
const Tweener = imports.ui.tweener;
const Util = imports.misc.util;
const Main = imports.ui.main;
const Tooltips = imports.ui.tooltips;
const PopupMenu = imports.ui.popupMenu;
const Cinnamon = imports.gi.Cinnamon;
const Settings = imports.ui.settings;
const DeskletManager = imports.ui.deskletManager;
const Soup = imports.gi.Soup;
const UUID = "[email protected]";
const DESKLET_DIR = imports.ui.deskletManager.deskletMeta[UUID].path;
imports.searchPath.push(DESKLET_DIR);
const xml = imports.marknote;
const _httpSession = new Soup.SessionAsync();
Soup.Session.prototype.add_feature.call(_httpSession, new Soup.ProxyResolverDefault());
// Set up some constants for layout and styling
const BBCWX_TEXT_SIZE = 14;
const BBCWX_CC_TEXT_SIZE = 24;
const BBCWX_LABEL_TEXT_SIZE = 11;
const BBCWX_LINK_TEXT_SIZE = 10;
const BBCWX_REFRESH_ICON_SIZE=14;
const BBCWX_TABLE_ROW_SPACING=2;
const BBCWX_TABLE_COL_SPACING=5;
const BBCWX_TABLE_PADDING=5;
const BBCWX_CONTAINER_PADDING=12;
const BBCWX_ICON_HEIGHT = 40;
const BBCWX_CC_ICON_HEIGHT =170;
const BBCWX_BUTTON_PADDING=3;
const BBCWX_LABEL_PADDING=4;
const BBCWX_TEMP_PADDING=12;
const BBCWX_SEPARATOR_STYLE = 'bbcwx-separator';
const BBCWX_SERVICE_STATUS_ERROR = 0;
const BBCWX_SERVICE_STATUS_INIT = 1;
const BBCWX_SERVICE_STATUS_OK = 2;
const BBCWX_DEFAULT_ICONSET = 'colourful';
const BBCWX_DEFAULT_ICON_EXT = 'png';
const BBCWX_TRANSLATION_URL = 'https://github.com/tipichris/bbcwx/wiki/Translating';
const Gettext = imports.gettext;
Gettext.bindtextdomain(UUID, GLib.get_home_dir() + "/.local/share/locale");
// list of preferred languages, most preferred first
const LangList = GLib.get_language_names()
//const LangList = ['ar', 'zh_CN', 'es_ES', 'es', 'en'];
function _(str) {
if (!str.toString().length) return '';
return Gettext.dgettext(UUID, str)
}
function MyDesklet(metadata,desklet_id){
this._init(metadata,desklet_id);
}
MyDesklet.prototype = {
__proto__: Desklet.Desklet.prototype,
_init: function(metadata,desklet_id){
//############Variables###########
this.desklet_id = desklet_id;
//## Days of the week
this.daynames={Mon: _('Mon'),Tue: _('Tue'), Wed: _('Wed'), Thu: _('Thu'), Fri: _('Fri'), Sat: _('Sat'), Sun: _('Sun')};
this.fwicons=[];this.labels=[];this.max=[];this.min=[];this.windd=[];this.winds=[];this.tempn=[];this.eachday=[];this.wxtooltip=[];
this.cc=[];this.days=[];
this.metadata = metadata;
this.oldno=0; // test for a change in this.no
this.oldwebservice='';
this.oldshifttemp='';
this.redrawNeeded=false;
//################################
try {
Desklet.Desklet.prototype._init.call(this, metadata);
//#########################binding configuration file################
this.settings = new Settings.DeskletSettings(this, UUID, this.desklet_id);
// temperature unit change may require refetching forecast if service includes units in text summaries
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"tunits","tunits",this.onTempUnitChange,null);
// these require only a redisplay
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"wunits","wunits",this.onUnitChange,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"punits","punits",this.onUnitChange,null);
// these changes require only a change to the styling of the desklet:
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"overrideTheme","overrideTheme",this.updateStyle,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"transparency","transparency",this.updateStyle,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"textcolor","textcolor",this.updateStyle,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"bgcolor","bgcolor",this.updateStyle,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"cornerradius","cornerradius",this.updateStyle,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"zoom","zoom",this.updateStyle,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"border","border",this.updateStyle,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"bordercolor","bordercolor",this.updateStyle,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"borderwidth","borderwidth",this.updateStyle,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"iconstyle","iconstyle",this.updateStyle,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"citystyle","citystyle",this.updateStyle,null);
// this change requires us to fetch new data:
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"stationID","stationID",this.changeStation,null);
// this requires a change of API key and refetch data
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"apikey","apikey",this.changeApiKey,null);
// this change requires the main loop to be restarted, but no other updates
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"refreshtime","refreshtime",this.changeRefresh,null);
// these changes potentially need a redraw of the window, but not a refetch of data
// layout because the position of the current temperature may change
// userno because of change to number of days in table, and possibly position of current temperature
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"layout","layout",this.displayOptsChange,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"userno","userno",this.redraw,null);
// these need a redraw. displayOptsChange sets a flag to say a redraw is needed before calling redraw
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"display__cc__pressure","display__cc__pressure",this.displayOptsChange,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"display__cc__humidity","display__cc__humidity",this.displayOptsChange,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"display__cc__feelslike","display__cc__feelslike",this.displayOptsChange,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"display__cc__wind_speed","display__cc__wind_speed",this.displayOptsChange,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"display__cc__visibility","display__cc__visibility",this.displayOptsChange,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"display__forecast__wind_speed","display__forecast__wind_speed",this.displayOptsChange,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"display__forecast__wind_direction","display__forecast__wind_direction",this.displayOptsChange,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"display__forecast__maximum_temperature","display__forecast__maximum_temperature",this.displayOptsChange,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"display__forecast__minimum_temperature","display__forecast__minimum_temperature",this.displayOptsChange,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"display__forecast__pressure","display__forecast__pressure",this.displayOptsChange,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"display__forecast__humidity","display__forecast__humidity",this.displayOptsChange,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"display__meta__country","display__meta__country",this.updateStyle,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"display__cc__weather","display__cc__weather",this.displayOptsChange,null);
// a change to webservice requires data to be fetched and the window redrawn
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"webservice","webservice",this.initForecast,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"locsrc","locsrc",this.displayMeta,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"manuallocation","manuallocation",this.displayMeta,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"experimental_enabled","experimental_enabled",this.doExperimental,null);
this.settings.bindProperty(Settings.BindingDirection.ONE_WAY,"gravity","gravity",this.setGravity,null);
// refresh style on change of global desklet setting for decorations
global.settings.connect('changed::desklet-decorations', Lang.bind(this, this.updateStyle));
// set a header for those that don't override the theme
//## The desklet title
this.setHeader(_('Weather'));
this._geocache = new Object();
this._geocache.yahoo = new Object();
this._geocache.google = new Object();
this.helpFile = DESKLET_DIR + "/help.html";
//## Link to Help file in context menu
this._menu.addAction(_('Help'), Lang.bind(this, function() {
Util.spawnCommandLine("xdg-open " + this.helpFile);
}));
//## Link to information on translating in context menu
this._menu.addAction(_('Translate'), Lang.bind(this, function() {
Util.spawnCommandLine("xdg-open " + BBCWX_TRANSLATION_URL);
}));
this.initForecast();
}
catch (e) {
global.logError(e);
}
return true;
},
////////////////////////////////////////////////////////////////////////////
// Set everything up initially
initForecast: function() {
if (this.service) delete this.service;
// select the the driver we need for this service
switch(this.webservice) {
case 'bbc':
this.service = new wxDriverBBC(this.stationID);
break;
case 'yahoo':
this.service = new wxDriverYahoo(this.stationID);
break;
case 'owm':
this.service = new wxDriverOWM(this.stationID, this.apikey);
break;
case 'wunderground':
this.service = new wxDriverWU(this.stationID, this.apikey);
break;
case 'wwo':
this.service = new wxDriverWWO(this.stationID, this.apikey);
break;
case 'forecast':
this.service = new wxDriverForecastIo(this.stationID, this.apikey);
break;
case 'twc':
this.service = new wxDriverTWC(this.stationID);
break;
default:
this.service = new wxDriverBBC(this.stationID);
}
this._setDerivedValues();
this._createWindow();
this.setGravity();
this._update_style();
this._refreshweathers();
},
////////////////////////////////////////////////////////////////////////////
// Create the layout of our desklet. Certain settings changes require this
// to be called again (eg change service, as capabilities change, change number
// days of forecast to display
_createWindow: function(){
// in these circumstances we do not need to redraw the window from scratch as the elements haven't changed
if((this.no == this.oldno) && (this.oldwebservice == this.webservice) && (this.shifttemp == this.oldshifttemp) && !this.redrawNeeded) {
return;
}
this.oldno=this.no;
this.oldwebservice = this.webservice;
this.oldshifttemp = this.shifttemp;
this.redrawNeeded = false;
// get rid of the signal to banner and main icon before we recreate a window
try {
if (this.bannersig) this.banner.disconnect(this.bannersig);
if (this.cwiconsig && this.cwicon) this.cwicon.disconnect(this.cwiconsig);
this.bannersig = null;
this.cwiconsig = null;
} catch(e) { }
this.window=new St.BoxLayout({vertical: ((this.vertical==1) ? true : false)});
this.cwicon = null;
// container for link and refresh icon
this.buttons=new St.BoxLayout({vertical: false,x_align:2, y_align:2 });
// refresh icon
this.iconbutton=new St.Icon({ icon_name: 'view-refresh-symbolic',
icon_type: St.IconType.SYMBOLIC
});
this.but=new St.Button(); // container for refresh icon
// these will hold the data for the three day forecast
this.labels=[]; this.fwicons=[];this.max=[]; this.min=[]; this.windd=[]; this.winds=[];
this.fhumidity=[]; this.fpressure=[]; this.eachday=[];
// some labels need resetting incase we are redrawing after a change of service
this.humidity=null; this.pressure=null; this.windspeed=null; this.feelslike=null;
this._separatorArea = new St.DrawingArea({ style_class: BBCWX_SEPARATOR_STYLE });
let ccap = this.show.cc;
// current weather values
if(ccap.humidity) this.humidity=new St.Label();
if(ccap.pressure) this.pressure=new St.Label();
if(ccap.wind_speed) this.windspeed=new St.Label();
if(ccap.feelslike) this.feelslike=new St.Label();
if(ccap.visibility) this.visibility=new St.Label();
// container for current weather values
this.ctemp_values = new St.BoxLayout({vertical: true, y_align: 2});
// container for current weather labels
this.ctemp_captions = new St.BoxLayout({vertical: true, y_align: 2});
// container for current weather
this.ctemp = new St.BoxLayout({vertical: false, x_align: 2, y_align: 2});
// city and city container
this.cityname=new St.Label();
this.city=new St.BoxLayout({vertical:true});
// container for right (horizontal) or lower (vertical) part of window
this.container= new St.BoxLayout({vertical: true, x_align: 2});
// container for left (horizontal) or upper (vertical) part of window
this.cweather = new St.BoxLayout({vertical: true, x_align: 2});
// current weather icon container
if (ccap.weather) this.cwicon = new St.Button();
// current weather text
if (ccap.weather) this.weathertext=new St.Label();
// current temp on wide layouts
if (this.shifttemp) {
this.ctemp_bigtemp = new St.BoxLayout({vertical: false, x_align: 3, y_align: 2});
this.currenttemp=new St.Label();
this.ctemp_bigtemp.add_actor(this.currenttemp);
this.ctemp.add_actor(this.ctemp_bigtemp);
}
this.city.add_actor(this.cityname);
//## Next five strings are labels for current conditions
if(ccap.humidity) this.ctemp_captions.add_actor(new St.Label({text: _('Humidity:')}));
if(ccap.pressure) this.ctemp_captions.add_actor(new St.Label({text: _('Pressure:')}));
if(ccap.wind_speed) this.ctemp_captions.add_actor(new St.Label({text: _('Wind:')}));
if(ccap.feelslike) this.ctemp_captions.add_actor(new St.Label({text: _('Feels like:')}));
if(ccap.visibility) this.ctemp_captions.add_actor(new St.Label({text: _('Visibility:')}));
if(this.humidity) this.ctemp_values.add_actor(this.humidity);
if(this.pressure) this.ctemp_values.add_actor(this.pressure);
if(this.windspeed) this.ctemp_values.add_actor(this.windspeed);
if(this.feelslike) this.ctemp_values.add_actor(this.feelslike);
if(this.visibility) this.ctemp_values.add_actor(this.visibility);
this.ctemp.add_actor(this.ctemp_captions);
this.ctemp.add_actor(this.ctemp_values);
// build table to hold three day forecast
this.fwtable =new St.Table();
//## Maximum temperature
this.maxlabel = new St.Label({text: _('Max:')});
//## Minimum temperature
this.minlabel = new St.Label({text: _('Min:')});
//## Wind speed (English translation is "Wind:")
this.windlabel = new St.Label({text: _('Wind speed:')});
//## Wind direction
this.winddlabel = new St.Label({text: _('Dir:')});
//## Atmospheric pressure
this.fpressurelabel = new St.Label({text: _('Pressure:')});
this.fhumiditylabel = new St.Label({text: _('Humidity:')});
let fcap = this.show.forecast;
let row = 2;
if(fcap.maximum_temperature) {this.fwtable.add(this.maxlabel,{row:row,col:0}); row++}
if(fcap.minimum_temperature) {this.fwtable.add(this.minlabel,{row:row,col:0}); row++}
if(fcap.wind_speed) {this.fwtable.add(this.windlabel,{row:row,col:0}); row++}
if(fcap.wind_direction) {this.fwtable.add(this.winddlabel,{row:row,col:0}); row++}
if(fcap.pressure) {this.fwtable.add(this.fpressurelabel,{row:row,col:0}); row++}
if(fcap.humidity) {this.fwtable.add(this.fhumiditylabel,{row:row,col:0}); row++}
for(let f=0;f<this.no;f++) {
this.labels[f]=new St.Button({label: ''});
this.fwicons[f]=new St.Button();
if(fcap.maximum_temperature) this.max[f]=new St.Label();
if(fcap.minimum_temperature) this.min[f]=new St.Label();
if(fcap.wind_speed) this.winds[f]=new St.Label();
if(fcap.wind_direction) this.windd[f]=new St.Label();
if(fcap.pressure) this.fpressure[f]=new St.Label();
if(fcap.humidity) this.fhumidity[f]=new St.Label();
this.wxtooltip[f] = new Tooltips.Tooltip(this.fwicons[f]);
this.fwtable.add(this.labels[f],{row:0,col:f+1});
this.fwtable.add(this.fwicons[f],{row:1,col:f+1});
row = 2;
if(this.max[f]) {this.fwtable.add(this.max[f],{row:row,col:f+1}); row++}
if(this.min[f]) {this.fwtable.add(this.min[f],{row:row,col:f+1}); row++}
if(this.winds[f]) {this.fwtable.add(this.winds[f],{row:row,col:f+1}); row++}
if(this.windd[f]) {this.fwtable.add(this.windd[f],{row:row,col:f+1}); row++}
if(this.fpressure[f]) {this.fwtable.add(this.fpressure[f],{row:row,col:f+1}); row++}
if(this.fhumidity[f]) {this.fwtable.add(this.fhumidity[f],{row:row,col:f+1}); row++}
}
this.but.set_child(this.iconbutton);
this.but.connect('clicked', Lang.bind(this, this.updateForecast));
// seems we have to use a button for bannerpre to get the vertical alignment :(
//## Credit the data supplier. A link to the data supplier appears to the right of this string
this.bannerpre=new St.Button({label: _('Data from ')});
this.banner=new St.Button({
reactive: true,
track_hover: true,
style_class: 'bbcwx-link'});
this.bannertooltip = new Tooltips.Tooltip(this.banner);
if (this.cwicon) this.cwicontooltip = new Tooltips.Tooltip(this.cwicon);
//## Tooltip for refresh button
this.refreshtooltip = new Tooltips.Tooltip(this.but, _('Refresh'));
this.buttons.add_actor(this.bannerpre);
this.buttons.add_actor(this.banner);
this.buttons.add_actor(this.but);
this.container.add_actor(this.ctemp);
this.container.add_actor(this._separatorArea);
this.container.add_actor(this.fwtable);
this.cweather.add_actor(this.city);
if (this.cwicon) this.cweather.add_actor(this.cwicon);
if (this.weathertext) this.cweather.add_actor(this.weathertext);
this.container.add_actor(this.buttons);
this.window.add_actor(this.cweather);
this.window.add_actor(this.container);
this.setContent(this.window);
},
////////////////////////////////////////////////////////////////////////////
// Set some internal values derived from user choices
_setDerivedValues: function() {
this.vertical = this.layout;
this.currenttempadding = BBCWX_TEMP_PADDING;
this.currenttempsize = BBCWX_CC_TEXT_SIZE;
// set the number of days of forecast to display; maximum of the number
// selected by the user and the maximum supported by the driver
if (this.userno > this.service.maxDays) {
this.no = this.service.maxDays;
} else {
this.no = this.userno;
}
// set the refresh period; minimum of the number
// selected by the user and the minimum supported by the driver
this.refreshSec = this.refreshtime * 60;
if (this.refreshSec < this.service.minTTL) {
this.refreshSec = this.service.minTTL;
}
// if more than four days we'll shift the position of the current temperature,
// but only in horizontal layout
// false: concatenate with weather text; true: shift to alongside current conditions;
this.shifttemp = false;
if (this.no > 4 && this.vertical == 0) {
this.shifttemp = true;
}
// set this.iconprops
this._initIcons();
// clone this.service.capabilities, then && it with display preferences
this.show = JSON.parse(JSON.stringify(this.service.capabilities));
let displayopts =['display__cc__pressure', 'display__cc__wind_speed',
'display__cc__humidity', 'display__cc__feelslike', 'display__cc__visibility',
'display__forecast__wind_speed', 'display__forecast__wind_direction',
'display__forecast__maximum_temperature', 'display__forecast__minimum_temperature',
'display__forecast__humidity', 'display__forecast__pressure',
'display__meta__country'
];
let ccShowCount=0;
for (let i=0; i<displayopts.length; i++) {
let parts=displayopts[i].split('__');
this.show[parts[1]][parts[2]] = this.show[parts[1]][parts[2]] && this[displayopts[i]];
if (parts[1] == 'cc' && this.show[parts[1]][parts[2]]) ccShowCount++;
}
// don't shift the current temp display position if
// no current conditions to display
if (ccShowCount < 1) this.shifttemp = false;
// if not showing current weather text and icon, force
// to vertical and shift current temperature
this.show.cc.weather = this.display__cc__weather;
if (!this.display__cc__weather) {
this.shifttemp = true
this.currenttempsize = this.currenttempsize*1.7;
this.vertical = 1;
// don't right pad the temperature if there's nothing to its right
if (ccShowCount < 1) this.currenttempadding = 0;
}
},
////////////////////////////////////////////////////////////////////////////
// Set internal values for icons
_initIcons: function() {
this.iconprops = this._getIconMeta(this.iconstyle);
this.defaulticonprops = this._getIconMeta(BBCWX_DEFAULT_ICONSET);
//global.log('_initIcons set values ' + this.iconprops.aspect + ' ; ' + this.iconprops.ext + ' ; ' + this.iconprops.adjust + ' using ' + this.iconstyle);
},
////////////////////////////////////////////////////////////////////////////
// Fetch the icon set meta data
_getIconMeta: function(iconset) {
let iconprops = new Object();
let deficonprops = {
aspect: 1,
adjust: 1,
ext: 'png',
map : {}
}
let file = Gio.file_new_for_path(DESKLET_DIR + '/icons/' + iconset + '/iconmeta.json');
try {
let raw_file = Cinnamon.get_file_contents_utf8_sync(file.get_path());
iconprops = JSON.parse(raw_file);
} catch(e) {
global.logError("Failed to parse iconmeta.json for iconset " + this.iconstyle);
}
// set anything missing to default values
for (prop in deficonprops) {
if (typeof iconprops[prop] === 'undefined') {
iconprops[prop] = deficonprops[prop];
}
}
return iconprops;
},
////////////////////////////////////////////////////////////////////////////
// Called when some change requires the styling of the desklet to be updated
updateStyle: function() {
// set values for this.iconprops
this._setDerivedValues();
// update style
this._update_style();
// also need to run these to update icon style and size
this.displayForecast();
this.displayCurrent();
this.displayMeta();
},
////////////////////////////////////////////////////////////////////////////
// Called when units are changed
onUnitChange: function() {
this.displayForecast();
this.displayCurrent();
},
////////////////////////////////////////////////////////////////////////////
// Called when temperature units are updated. If service text summaries include
// units we must refetch forecast, otherwise just refresh display
onTempUnitChange: function() {
this.onUnitChange();
if(this.service.unitsInSummaries) {
this.updateForecast();
}
},
////////////////////////////////////////////////////////////////////////////
// Does the bulk of the work of updating style
_update_style: function() {
//global.log("bbcwx (instance " + this.desklet_id + "): entering _update_style");
this.window.vertical = (this.vertical==1) ? true : false;
if (this.cwicon) {
this.cwicon.height=BBCWX_CC_ICON_HEIGHT*this.zoom;
this.cwicon.width=BBCWX_CC_ICON_HEIGHT*this.iconprops.aspect*this.zoom;
}
if (this.weathertext) this.weathertext.style= 'text-align : center; font-size:'+BBCWX_CC_TEXT_SIZE*this.zoom+'px';
if (this.currenttemp) this.currenttemp.style= 'text-align : center; font-size:'+this.currenttempsize*this.zoom+'px';
if (this.ctemp_bigtemp) this.ctemp_bigtemp.style = 'text-align : left; padding-right: ' + this.currenttempadding *this.zoom + 'px'
this.fwtable.style="spacing-rows: "+BBCWX_TABLE_ROW_SPACING*this.zoom+"px;spacing-columns: "+BBCWX_TABLE_COL_SPACING*this.zoom+"px;padding: "+BBCWX_TABLE_PADDING*this.zoom+"px;";
this.cityname.style="text-align: center;font-size: "+BBCWX_TEXT_SIZE*this.zoom+"px; font-weight: " + ((this.citystyle) ? 'bold' : 'normal') + ";" ;
this.ctemp_captions.style = 'text-align : right;font-size: '+BBCWX_TEXT_SIZE*this.zoom+"px; padding-right: " +BBCWX_LABEL_PADDING*this.zoom+"px";
this.ctemp_values.style = 'text-align : left; font-size: '+BBCWX_TEXT_SIZE*this.zoom+"px";
if(this.overrideTheme) {
// hide header and use a style with no border
this._header.hide();
this.window.set_style_class_name('desklet');
if (this.border) {
let borderradius = (this.borderwidth > this.cornerradius) ? this.borderwidth : this.cornerradius;
this.window.style="border: " + this.borderwidth + "px solid "+this.bordercolor+"; border-radius: " + borderradius + "px; background-color: "+(this.bgcolor.replace(")",","+this.transparency+")")).replace('rgb','rgba')+"; color: "+this.textcolor;
}
else {
this.window.style="border-radius: " + this.cornerradius + "px; background-color: "+(this.bgcolor.replace(")",","+this.transparency+")")).replace('rgb','rgba')+"; color: "+this.textcolor;
}
this.banner.style='font-size: '+BBCWX_LINK_TEXT_SIZE*this.zoom+"px; color: " + this.textcolor;
this.bannerpre.style='font-size: '+BBCWX_LINK_TEXT_SIZE*this.zoom+"px; color: " + this.textcolor;
this.banner.set_style_class_name('bbcwx-link');
} else {
this.window.set_style('');
// set style_class and _header visibility according to
// global desklet settings for theme
let dec = global.settings.get_int('desklet-decorations');
switch(dec){
case 0:
this._header.hide();
this.window.set_style_class_name('desklet');
break;
case 1:
this._header.hide();
this.window.set_style_class_name('desklet-with-borders');
break;
case 2:
this._header.show();
this.window.set_style_class_name('desklet-with-borders-and-header');
break;
}
this.banner.style='font-size: '+BBCWX_LINK_TEXT_SIZE*this.zoom+"px;";
this.bannerpre.style='font-size: '+BBCWX_LINK_TEXT_SIZE*this.zoom+"px;";
}
this._separatorArea.height=5*this.zoom;
for(let f=0;f<this.no;f++) {
this.labels[f].style='text-align : center;font-size: '+BBCWX_TEXT_SIZE*this.zoom+"px";
this.fwicons[f].height=BBCWX_ICON_HEIGHT*this.zoom;this.fwicons[f].width= BBCWX_ICON_HEIGHT*this.iconprops.aspect*this.zoom;
if(this.max[f]) this.max[f].style= 'text-align : center; font-size: '+BBCWX_TEXT_SIZE*this.zoom+"px";
if(this.min[f]) this.min[f].style= 'text-align : center; font-size: '+BBCWX_TEXT_SIZE*this.zoom+"px";
if(this.winds[f]) this.winds[f].style= 'text-align : center; font-size: '+BBCWX_TEXT_SIZE*this.zoom+"px";
if(this.windd[f]) this.windd[f].style= 'text-align : center; font-size: '+BBCWX_TEXT_SIZE*this.zoom+"px";
if(this.fpressure[f]) this.fpressure[f].style= 'text-align : center; font-size: '+BBCWX_TEXT_SIZE*this.zoom+"px";
if(this.fhumidity[f]) this.fhumidity[f].style= 'text-align : center; font-size: '+BBCWX_TEXT_SIZE*this.zoom+"px";
}
this.buttons.style="padding-top:"+BBCWX_BUTTON_PADDING*this.zoom+"px;padding-bottom:"+BBCWX_BUTTON_PADDING*this.zoom+"px";
this.iconbutton.icon_size=BBCWX_REFRESH_ICON_SIZE*this.zoom;
let forecastlabels = ['maxlabel', 'minlabel', 'windlabel', 'winddlabel', 'fpressurelabel', 'fhumiditylabel'];
for (let i = 0; i<forecastlabels.length; i++) {
if (this[forecastlabels[i]]) this[forecastlabels[i]].style = 'text-align : right;font-size: '+BBCWX_LABEL_TEXT_SIZE*this.zoom+"px";
}
this.cweather.style='padding: ' + BBCWX_CONTAINER_PADDING*this.zoom+'px';
if (this.vertical==1) {
// loose the top padding on container in vertical mode (too much space)
this.container.style='padding: 0 ' + BBCWX_CONTAINER_PADDING*this.zoom+'px ' + BBCWX_CONTAINER_PADDING*this.zoom+'px ' + BBCWX_CONTAINER_PADDING*this.zoom+'px ' ;
} else {
this.container.style='padding: ' + BBCWX_CONTAINER_PADDING*this.zoom+'px';
}
},
////////////////////////////////////////////////////////////////////////////
// Update the forecast, without changing layout or styling
updateForecast: function() {
this._refreshweathers();
},
////////////////////////////////////////////////////////////////////////////
// Change the location we are displaying weather for
changeStation: function() {
this.service.setStation(this.stationID);
this._refreshweathers();
},
////////////////////////////////////////////////////////////////////////////
// Change the API key and reget weather data
changeApiKey: function() {
this.service.setApiKey(this.apikey);
this._refreshweathers();
},
////////////////////////////////////////////////////////////////////////////
// Change the refresh period and restart the loop
changeRefresh: function() {
this._setDerivedValues();
this._doLoop();
},
////////////////////////////////////////////////////////////////////////////
// Called when there is a change to user config for parameters to display
displayOptsChange: function() {
this.redrawNeeded = true;
this.redraw();
},
////////////////////////////////////////////////////////////////////////////
// redraw the window, but without refetching data from the service provider
redraw: function() {
this._setDerivedValues();
this._createWindow();
this._update_style();
this.displayCurrent();
this.displayForecast();
this.displayMeta();
},
////////////////////////////////////////////////////////////////////////////
// update the data from the service and start the timeout to the next update
// refreshData will call the display* functions
_refreshweathers: function() {
let now=new Date().toLocaleFormat('%H:%M:%S');
global.log("bbcwx (instance " + this.desklet_id + "): refreshing forecast at " + now);
// pass this to refreshData as it needs to call display* functions once the data
// is updated
this.service.refreshData(this);
this._doLoop();
},
////////////////////////////////////////////////////////////////////////////
// Begin / restart the main loop, waiting for refreshSec before updating again
_doLoop: function() {
if(typeof this._timeoutId !== 'undefined') {
Mainloop.source_remove(this._timeoutId);
}
this._timeoutId=Mainloop.timeout_add_seconds(Math.round(this.refreshSec * (0.9 + Math.random()*0.2)),Lang.bind(this, this.updateForecast));
},
////////////////////////////////////////////////////////////////////////////
// Update the display of the forecast data
displayForecast: function() {
//global.log("bbcwx (instance " + this.desklet_id + "): entering displayForecast");
for(let f=0;f<this.no;f++)
{
let day = this.service.data.days[f];
this.labels[f].label=((this.daynames[day.day]) ? this.daynames[day.day] : '');
let fwiconimage = this._getIconImage(day.icon, BBCWX_ICON_HEIGHT*this.zoom);
//fwiconimage.set_size(BBCWX_ICON_HEIGHT*this.iconprops.aspect*this.zoom, BBCWX_ICON_HEIGHT*this.zoom);
this.fwicons[f].set_child(fwiconimage);
//## Message if we fail to get weather data
this.wxtooltip[f].set_text(((day.weathertext) ? _(day.weathertext) : _('No data available')));
if(this.max[f]) this.max[f].text=this._formatTemperature(day.maximum_temperature, true);
if(this.min[f]) this.min[f].text=this._formatTemperature(day.minimum_temperature, true);
if(this.winds[f]) this.winds[f].text=this._formatWindspeed(day.wind_speed, true);
if(this.windd[f]) this.windd[f].text= ((day.wind_direction) ? day.wind_direction : '');
if(this.fpressure[f]) this.fpressure[f].text=this._formatPressure(day.pressure, '', true);
if(this.fhumidity[f]) this.fhumidity[f].text=this._formatHumidity(day.humidity, true);
}
},
////////////////////////////////////////////////////////////////////////////
// Update the display of the current observations
displayCurrent: function(){
let cc = this.service.data.cc;
if (this.cwicon) {
let cwimage=this._getIconImage(this.service.data.cc.icon, BBCWX_CC_ICON_HEIGHT*this.zoom);
//cwimage.set_size(BBCWX_CC_ICON_HEIGHT*this.iconprops.aspect*this.zoom, BBCWX_CC_ICON_HEIGHT*this.zoom);
this.cwicon.set_child(cwimage);
}
if (this.shifttemp) {
if (this.weathertext) this.weathertext.text = ((cc.weathertext) ? cc.weathertext : '');
this.currenttemp.text = this._formatTemperature(cc.temperature, true) ;
} else {
if (this.weathertext) this.weathertext.text = ((cc.weathertext) ? cc.weathertext : '') + ((cc.temperature && cc.weathertext) ? ', ' : '' )+ this._formatTemperature(cc.temperature, true) ;
}
if (this.humidity) this.humidity.text= this._formatHumidity(cc.humidity);
if (this.pressure) this.pressure.text=this._formatPressure(cc.pressure, cc.pressure_direction, true);
if (this.windspeed) this.windspeed.text=((cc.wind_direction) ? cc.wind_direction : '') + ((cc.wind_direction && cc.wind_speed) ? ', ' : '' ) + this._formatWindspeed(cc.wind_speed, true);
if (this.feelslike) this.feelslike.text=this._formatTemperature(cc.feelslike, true);
if (this.visibility) this.visibility.text=this._formatVisibility(cc.visibility, true);
if (this.service.data.status.cc != BBCWX_SERVICE_STATUS_OK && this.weathertext) {
this.weathertext.text = (this.service.data.status.lasterror) ? _('Error: %s').format(this.service.data.status.lasterror) : _('No data') ;
}
},
////////////////////////////////////////////////////////////////////////////
// Update the display of the meta data, eg city name, link tooltip. Handles
// managing reverse geocode lookups from Yahoo or Google if needed
displayMeta: function() {
let locsrc = this.locsrc;
if (this.manuallocation.toString().length) locsrc = 'manual'
this.displaycity = '';
this.tooltiplocation = '';
if (locsrc == 'manual') {
this.displaycity=this.manuallocation;
this.tooltiplocation = this.manuallocation
} else {
// if city name from service is empty, use wgs84, or stationID
if (!this.service.data.city.toString().length) {
if (this.service.capabilities.meta.wgs84 && this.service.data.status.meta == BBCWX_SERVICE_STATUS_OK) {
// If city name is empty and source is 'service', we'll look it up with Yahoo!
if (locsrc == 'service') locsrc = 'yahoo';
this.displaycity=this.service.data.wgs84.lat + ',' + this.service.data.wgs84.lon;
this.tooltiplocation = this.service.data.wgs84.lat + ',' + this.service.data.wgs84.lon;
} else {
this.displaycity = this.stationID;
this.tooltiplocation = this.stationID;
}
} else {
// initially set the displayed location to that from the data service,
// if available. Google / Yahoo lookups we'll do asyncronously later
this.displaycity=this.service.data.city;
this.tooltiplocation = this.service.data.city;
if (this.show.meta.country) {
this.displaycity += ', ' + this.service.data.country;
}
}
}
// initial update (Google/Yahoo to follow)
this._updateLocationDisplay();
if (this.service.linkIcon) {
this.banner.label = '';
let bannericonimage = this._getIconImage(this.service.linkIcon.file, this.service.linkIcon.height*this.zoom, this.service.linkIcon.width*this.zoom, false);
//bannericonimage.set_size(this.service.linkIcon.width*this.zoom, this.service.linkIcon.height*this.zoom);
this.banner.set_child(bannericonimage);
} else {
this.banner.label = this.service.linkText;
}
try {
if (this.bannersig) this.banner.disconnect(this.bannersig);
if (this.cwiconsig && this.cwicon) this.cwicon.disconnect(this.cwiconsig);
this.bannersig = null;
this.cwiconsig = null;
} catch(e) { global.logWarning("Failed to disconnect signal from link banner") }
this.bannersig = this.banner.connect('clicked', Lang.bind(this, function() {
Util.spawnCommandLine("xdg-open " + this.service.linkURL );
}));
if (this.cwicon) {
this.cwiconsig = this.cwicon.connect('clicked', Lang.bind(this, function() {
Util.spawnCommandLine("xdg-open " + this.service.linkURL );
}));
}
if (this.service.data.status.meta != BBCWX_SERVICE_STATUS_OK) {
this.cityname.text = (this.service.data.status.lasterror) ? _('Error: %s').format(this.service.data.status.lasterror) : _('No data') ;
}
// do async lookup of location with yahoo or google
else if (this.service.capabilities.meta.wgs84 && (locsrc == 'yahoo' || locsrc == 'google')) {
let latlon = this.service.data.wgs84.lat + ',' + this.service.data.wgs84.lon;
// check the cache
if (typeof this._geocache[locsrc][latlon] === 'object') {
// debugging
//global.log ("bbcwx: geocache hit for " + latlon + ", " + locsrc + ": " + this._geocache[locsrc][latlon].city);
this.displaycity = this._geocache[locsrc][latlon].city;
this.tooltiplocation = this.displaycity
if (this.show.meta.country) {
this.displaycity += ', ' + this._geocache[locsrc][latlon].country;
}
this._updateLocationDisplay();
// no cache - lookup
} else {
// debugging
//global.log ("bbcwx: Looking up city for " + latlon + " at " + locsrc);
let b = this._getGeo(locsrc, function(geo, locsrc) {
if (geo) {
this._load_geo(geo, locsrc);
this._updateLocationDisplay();
}
});
}
}
},
////////////////////////////////////////////////////////////////////////////
// Update the display of city name and link tooltip
_updateLocationDisplay: function() {
this.cityname.text=this.displaycity;
//## %s is replaced by place name
let linktooltip = _('Click for the full forecast for %s').format(this.tooltiplocation)
this.bannertooltip.set_text(linktooltip);
if (this.cwicontooltip) this.cwicontooltip.set_text(linktooltip);
},
////////////////////////////////////////////////////////////////////////////
// Do async reverse geocode lookups at Yahoo! or Google
// -> locsrc: which service to use: either 'yahoo' or 'google'
// -> callback: callback function to process returned results
_getGeo: function( locsrc, callback) {
// just use the most preferred language and hope Yahoo! / Google supports it
let locale = LangList[0];
let url = '';
if (locsrc == 'yahoo') {
url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text%3D%22' + this.service.data.wgs84.lat + '%2C' + this.service.data.wgs84.lon +'%22%20and%20gflags%3D%22R%22%20and%20locale%3D%22' + locale + '%22&format=json&callback=';
} else if (locsrc == 'google') {
url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + this.service.data.wgs84.lat + '%2C' + this.service.data.wgs84.lon + '&language=' + locale;
} else {
// set some error flag?
return;
}
//debugging
//global.log('bbcwx: geo, calling ' + url);
var here = this;
let message = Soup.Message.new('GET', url);
_httpSession.queue_message(message, function (session, message) {
if( message.status_code == 200) {
try {callback.call(here,message.response_body.data.toString(),locsrc);} catch(e) {global.logError(e)}
} else {
global.logWarning("Error retrieving address " + url + ". Status: " + message.status_code + ": " + message.reason_phrase);
//here.data.status.lasterror = message.status_code;
callback.call(here,false,locsrc);
}
});
},
///////////////////////////////////////////////////////////////////////////
// Call back function to process returned object from reverse geocode lookups
// Wraper around _load_geo_yahoo and _load_geo_google
// -> data: returned data
// -> locsrc: the service it came from, 'yahoo' or 'google'
_load_geo: function(data, locsrc) {
switch(locsrc) {
case 'google':
this._load_geo_google(data);
break;
case 'yahoo':
this._load_geo_yahoo(data);
break;
default:
this._load_geo_yahoo(data);
}
},
///////////////////////////////////////////////////////////////////////////
// Call back function to process returned object from reverse geocode lookups
// from Yahoo!
_load_geo_yahoo: function (data) {
if (!data) {
//this.data.status.meta = BBCWX_SERVICE_STATUS_ERROR;
return;
}
let json = JSON.parse(data);
let latlon = this.service.data.wgs84.lat + ',' + this.service.data.wgs84.lon;
this._geocache.yahoo[latlon] = new Object();
try {
let geo = json.query.results.Result;
this.displaycity = geo.city;
this.tooltiplocation = this.displaycity;
if (this.show.meta.country) {
this.displaycity += ', ' + geo.country;
}
this._geocache.yahoo[latlon].city = geo.city;
this._geocache.yahoo[latlon].country = geo.country;
} catch(e) {
global.logError(e);
delete this._geocache.yahoo[latlon]
//this.data.status.meta = BBCWX_SERVICE_STATUS_ERROR;
}
},
///////////////////////////////////////////////////////////////////////////
// Call back function to process returned object from reverse geocode lookups
// from Google
_load_geo_google: function (data) {
if (!data) {
//this.data.status.meta = BBCWX_SERVICE_STATUS_ERROR;
return;
}
let city = '';
let country = '';
let geo = new Object();
let addrtypes = [ 'xlocality', 'xstreetaddr', 'xpostal_code', 'administrative_area_level_3', 'administrative_area_level_2', 'administrative_area_level_1', 'xcountry'];
for (let a=0; a<addrtypes.length; a++) {
geo[addrtypes[a]] = new Object();
}
let json = JSON.parse(data);
let latlon = this.service.data.wgs84.lat + ',' + this.service.data.wgs84.lon;
this._geocache.google[latlon] = new Object();
try {
let results = json.results;
for (let i=0; i<results.length; i++) {
for (let t=0; t<results[i].types.length; t++) {
if (results[i].types[t] == 'administrative_area_level_3') {
geo.administrative_area_level_3 = results[i];
}
if (results[i].types[t] == 'administrative_area_level_2') {
geo.administrative_area_level_2 = results[i];
}
if (results[i].types[t] == 'administrative_area_level_1') {
geo.administrative_area_level_1 = results[i];
}
if (results[i].types[t] == 'country') {
geo.xcountry = results[i];
}
if (results[i].types[t] == 'locality') {
geo.xlocality = results[i];
}
if (results[i].types[t] == 'street_address') {
geo.xstreetaddr = results[i];
}
if (results[i].types[t] == 'postal_code' && results[i].types.join().indexOf("postal_code_prefix") == -1) {
geo.xpostal_code = results[i];
}
}
}
for (let a=0; a<addrtypes.length; a++) {
if (typeof geo[addrtypes[a]].address_components !== "undefined" && (!city || !country)) {
let components = geo[addrtypes[a]].address_components;
for (let i=0; i<components.length; i++) {
for (let t=0; t<components[i].types.length; t++) {
if (components[i].types[t] == 'locality' && !city) {
city = components[i].long_name;
}
if (components[i].types[t] == 'country' && !country) {
country = components[i].long_name;
}
}
if (!city) {
for (let t=0; t<components[i].types.length; t++) {
if (components[i].types[t] == addrtypes[a] && !city) {
city = components[i].long_name;