-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathgis-weather.py
1977 lines (1797 loc) · 85.7 KB
/
gis-weather.py
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
#!/usr/bin/env python3
#
# gis_weather.py
v = '0.8.4.22'
# Copyright (C) 2013-2022 Alexander Koltsov <[email protected]>
#
# 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/>.
print('Gis Weather '+v)
import sys
if sys.platform.startswith("win"):
WIN = True
else:
WIN = False
from utils import instance
if not WIN:
try:
instance.set_procname(b'gis-weather')
multInstances = True
except:
multInstances = False
else:
multInstances = False
from utils import localization
localization.set()
if not multInstances:
print(_('Running multiple instances is not supported'))
import argparse
parser = argparse.ArgumentParser(description='Customizable weather widget')
parser.add_argument('-i', '--instances', nargs=1, metavar='N', default=['0'],
help=_('number of instances'))
parser.add_argument('-v', '--version', action='version', version='Gis Weather '+v)
parser.add_argument('-t', '--test', help="testing mode",
action="store_true")
args = parser.parse_args()
if args.test:
print(_('testing mode turned on'))
INSTANCE_NO = instance.count()
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('PangoCairo', '1.0')
from gi.repository import Gtk, GObject, Pango, PangoCairo, Gdk, GdkPixbuf, GLib
try:
gi.require_version('AppIndicator3', '0.1')
from gi.repository import AppIndicator3
HAS_INDICATOR=True
except:
HAS_INDICATOR=False
print('Not found gir1.2-appindicator3-0.1 (libappindicator3)')
try:
gi.require_version('Rsvg', '2.0')
from gi.repository import Rsvg
HAS_RSVG=True
except:
HAS_RSVG=False
print('Not found gir1.2-rsvg-2.0 (librsvg)')
from dialogs import about_dialog, city_id_dialog, update_dialog, settings_dialog, help_dialog
from services import data
from utils import gw_menu, presets, date_convert, diff_versions, weather_vars
from utils.opener import urlopen
from utils.opener import urlretrieve
import cairo
import re
import os
import time
import math
import json
import subprocess
import shlex
import gzip
import shutil
import webbrowser
try:
import distro
DISTRO = True
except:
import platform
DISTRO = False
CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.config', 'gis-weather')
CONFIG_PATH_FILE = os.path.join(CONFIG_PATH, instance.get_config_file())
def make_dirs(path):
if not os.path.exists(path):
os.makedirs(path)
make_dirs(CONFIG_PATH)
make_dirs(os.path.join(CONFIG_PATH, 'color_schemes'))
make_dirs(os.path.join(CONFIG_PATH, 'icons'))
make_dirs(os.path.join(CONFIG_PATH, 'backgrounds'))
make_dirs(os.path.join(CONFIG_PATH, 'presets'))
presets.save_to_file(CONFIG_PATH)
# Default values
gw_config_default = {
'angel': 0, # angle of clockwise rotation in degrees
'city_id': 0, # location code
'appid': '', # api key
'upd_time': 60, # Update by (in minutes)
'n': 7, # Display days
'x_pos': 60, # left position
'y_pos': 60, # top position
't_feel': False, # temperature as feel
'font': 'Sans', # font
'color_text': (0, 0, 0, 1), #RGBa # color text
'color_text_week': (0.5, 0, 0, 1), # color weekend
'weekend': 'Sa, Su',
'color_bg': (0.8, 0.8, 0.8, 1), # color background
'color_shadow': (1, 1, 1, 0.7), # color shadow
'draw_shadow': True, # draw shadow
'opacity': 1, # opacity window
'show_time_receive': False, # time of receipt of weather
'show_block_wind_direct': True, # block wind direct
'block_wind_direct_left': -170, # position
'wind_direct_small': False, # small block wind direct
'show_block_add_info': True, # block with additional information
'block_add_info_left': 70, # position
'show_block_tomorrow': True, # block with the weather for tomorrow
'block_tomorrow_left': 180, # position
'show_block_today': True, # block with the weather for today
'block_today_left': -310, # position
'r': 0, # border radius
'show_splash_screen': 2, # splash creen 0 - no, 1 - only backdround, 2 - yes
'max_try_show': 30, # hide splash, 0 - show always
'sticky': True, # on all desktops
'show_bg_png': True, # picture in background
'bg_custom': 'Light50', # this picture
'margin': 20, # inside padding
'high_wind': 10, # wind greater or equal to this value is highlighted (-1 do not allocate)
'color_high_wind': (0, 0, 0.6, 1), # color
'icons_name': 'default', # name folder with icon
'icons_menu_name': 'default', # name folder with icon for menu
'fix_BadDrawable': False, # if BadDrawable error
'color_scheme_number': 0,
'check_for_updates': 2, # 0 - no, 1 - only when startup, 2 - always
'fix_position': False,
'app_lang': 'auto',
'weather_lang': 'en',
'delay_start_time': 0,
'block_now_left': 0,
't_scale': 0, # 0 - °C, 1 - °F, 2 - K
'service': 'Gismeteo',
'max_days': 12,
'show_chance_of_rain': False,
'wind_units': 0,
'press_units': 0,
'show_indicator': 0, # 0 - widget only, 1 - indicator only, 2 - widget + indicator
'indicator_is_appindicator': 'None',
'indicator_icons_name': 'default',
'indicator_font': 'Sans',
'indicator_font_size': 9,
'indicator_color_text': (0, 0, 0, 1),
'indicator_color_shadow': (1, 1, 1, 0.7),
'indicator_draw_shadow': True,
'indicator_top': 0,
'indicator_width': 30,
'indicator_disable_plus': False,
'app_indicator_fix_size': False,
'app_indicator_size': 22,
'scale': 1,
'instances_count': 1,
'date_separator': 'default',
'show_indicator_text': True,
'swap_d_and_m': False,
'save_cur_temp': False,
'save_cur_temp_add_scale': False,
'save_cur_temp_to_pipe': True,
'save_cur_icon': False,
'save_cur_data_path': '',
'save_weather': False,
'save_weather_fmt': '',
'save_weather_path': '',
'save_widget': False,
'save_widget_path': '',
'save_widget_scale': False,
'type_hint':0,
'always_on_top': False,
'tooltip_show': True,
'tooltip_fmt': '',
# customizable options
'preset_number': 0,
'bg_left': 0,
'bg_top': 0,
'bg_width': -1,
'bg_height': -1,
'block_icons_left': 0,
'block_icons_top': 0,
'day_left': 0,
'day_top': 0,
'height_adjustment': 0,
'height_fix': 0,
'width_fix': 0,
'splash_icon_top': 0,
'splash_version_top': 0,
'block_wind_direct_small_left': 0,
'block_today_top': 0,
'block_tomorrow_top': 0,
'block_wind_direct_small_top': 0,
'splash_block_top': 0,
'desc_style': 0, # 0 - Normal, 1 - Italic
'block_sunrise':{'x':30, 'y':100, 'font_size': 9, 'align': 'left', 'show': True},
'block_moonrise':{'x':30, 'y':100, 'font_size': 9, 'align': 'right', 'show': True},
'time_of_day_gradient': False,
# day icon customization
'day_icon_attr': {'x': 30, 'y': 16, 'size': 36, 'show': True},
'day_date_fmt': '{day}, {date}',
'day_date_attr': {'x': 0, 'y': -2, 'font_weight': ' Bold', 'font_size': 9, 'align': 'left', 'show': True},
't_now_fmt': '{t_now}',
't_fmt': '{t_day}\n{t_night}',
't_attr': {'x': 0, 'y': 15, 'font_weight': ' Normal', 'font_size': 10, 'align': 'left', 'show': True},
'wind_fmt': '{wind_direct}, {wind_speed}',
'wind_attr': {'x': 0, 'y': 50, 'font_weight': ' Normal', 'font_size': 8, 'align': 'left', 'show': True},
'text_attr': {'x': 0, 'y': 55, 'font_size': 7, 'align': 'left', 'show': True},
# now icon customization
'city_name_attr': {'x':0, 'y':0, 'font_weight':' Bold', 'font_size':14, 'align':'center', 'show':True},
'text_now_attr': {'x':0, 'y':0, 'font_weight':' Normal', 'font_size':10, 'align':'center', 'show':True},
't_now_attr': {'x':0, 'y':30, 'font_weight':' Normal', 'font_size':18, 'align':'right', 'show':True},
'icon_now_attr': {'x':0, 'y':30, 'size':80, 'show':True},
'custom_text1_attr': {'text':_('Now'), 'x':0, 'y':0, 'font_weight':' Bold', 'font_size':9, 'align':'left', 'show':False},
'block_h_offset': 12,
'city_name_custom': '',
'pipe1': {'text': '{t_now}', 'path': os.path.join(CONFIG_PATH, 'pipe1'), 'active': False},
'pipe2': {'text': '{t_now}', 'path': os.path.join(CONFIG_PATH, 'pipe2'), 'active': False},
'pipe3': {'text': '{t_now}', 'path': os.path.join(CONFIG_PATH, 'pipe3'), 'active': False},
'text_file1': {'text': '{t_now}', 'path': os.path.join(CONFIG_PATH, 'text_file1'), 'active': False},
'text_file2': {'text': '{t_now}', 'path': os.path.join(CONFIG_PATH, 'text_file2'), 'active': False},
'text_file3': {'text': '{t_now}', 'path': os.path.join(CONFIG_PATH, 'text_file3'), 'active': False},
'weather_menu': False,
'weather_menu_n': 3
}
window_type_hint_list = (
'',
Gdk.WindowTypeHint.DOCK,
Gdk.WindowTypeHint.NORMAL,
Gdk.WindowTypeHint.DIALOG,
Gdk.WindowTypeHint.MENU,
Gdk.WindowTypeHint.TOOLBAR,
Gdk.WindowTypeHint.SPLASHSCREEN,
Gdk.WindowTypeHint.UTILITY,
Gdk.WindowTypeHint.DESKTOP,
Gdk.WindowTypeHint.DROPDOWN_MENU,
Gdk.WindowTypeHint.POPUP_MENU,
Gdk.WindowTypeHint.TOOLTIP,
Gdk.WindowTypeHint.NOTIFICATION,
Gdk.WindowTypeHint.COMBO,
Gdk.WindowTypeHint.DND
)
gw_config = {}
for i in gw_config_default.keys():
gw_config[i] = gw_config_default[i]
color_scheme = [
{ 'color_text': (0, 0, 0, 1), #RGBa # text color
'color_text_week': (0.5, 0, 0, 1), # color weekend
'color_shadow': (1, 1, 1, 0.7), # color shadow
'color_high_wind': (0, 0, 0.6, 1) # color high wind
},
{ 'color_text': (0.9, 0.9, 0.9, 1), # text color
'color_text_week': (1, 0.5, 0.5, 1), # color weekend
'color_shadow': (0, 0, 0, 0.7), # color shadow
'color_high_wind': (0.5, 0.5, 1, 1) # color high wind
},
{ 'color_text': (0.2, 0.2, 0.2, 1), # text color
'color_text_week': (0.5, 0, 0, 1), # color weekend
'color_shadow': (0, 0, 0, 0), # color shadow
'color_high_wind': (0, 0, 0, 1) # color high wind
}
]
def Save_Color_Scheme(number = 0):
json.dump(color_scheme[number], open(os.path.join(CONFIG_PATH, 'color_schemes', 'color_sheme_%s.json' %number), "w", encoding='utf-8'), sort_keys=True, indent=4, separators=(', ', ': '), ensure_ascii=False)
for i in range(len(color_scheme)):
if not os.path.exists(os.path.join(CONFIG_PATH, 'color_schemes', 'color_sheme_%s.json' %i)):
Save_Color_Scheme(i)
def Create_Variables():
for i in gw_config.keys():
globals()[i] = gw_config[i]
print (_('Configuration folder')+':\n '+CONFIG_PATH_FILE)
def Save_Config():
for i in gw_config.keys():
try:
gw_config[i] = globals()[i]
except:
pass
json.dump(gw_config, open(CONFIG_PATH_FILE, "w", encoding='utf-8'), sort_keys=True, indent=4, separators=(', ', ': '), ensure_ascii=False)
def Load_Config():
try:
gw_config_loaded=json.load(open(CONFIG_PATH_FILE))
for i in gw_config_loaded.keys():
gw_config[i] = gw_config_loaded[i] # new values
except:
print ('\033[1;31m[!]\033[0m '+_('Error loading config file'))
Create_Variables()
# first start, config missed
if not os.path.exists(CONFIG_PATH_FILE):
if INSTANCE_NO == 0:
Create_Variables()
Save_Config()
else:
if INSTANCE_NO == 1:
if os.path.exists(os.path.join(CONFIG_PATH, 'gw_config.json')):
shutil.copy(os.path.join(CONFIG_PATH, 'gw_config.json'), CONFIG_PATH_FILE)
else:
Create_Variables()
Save_Config()
else:
shutil.copy(os.path.join(CONFIG_PATH, 'gw_config%s.json'%str(INSTANCE_NO-1)), CONFIG_PATH_FILE)
g_load = json.load(open(CONFIG_PATH_FILE))
g_load['x_pos'] = g_load['x_pos'] - 20
g_load['y_pos'] = g_load['y_pos'] + 20
json.dump(g_load, open(CONFIG_PATH_FILE, "w", encoding='utf-8'), sort_keys=True, indent=4, separators=(', ', ': '), ensure_ascii=False)
# load config
Load_Config()
def Load_Color_Scheme(number = 0):
try:
scheme_loaded=json.load(open(os.path.join(CONFIG_PATH, 'color_schemes', 'color_sheme_%s.json' %number)))
for i in scheme_loaded.keys():
gw_config[i] = scheme_loaded[i]
gw_config['color_scheme_number'] = number
except:
print ('\033[1;31m[!]\033[0m '+_('Error loading color scheme')+' # '+str(number))
Create_Variables()
def Load_Preset(number = 0):
try:
preset_default=presets.list[0]
for i in preset_default.keys():
gw_config[i] = preset_default[i]
preset_loaded=json.load(open(os.path.join(CONFIG_PATH, 'presets', 'preset_%s.json' %number)))
for i in preset_loaded.keys():
gw_config[i] = preset_loaded[i]
gw_config['preset_number'] = number
except:
print ('\033[1;31m[!]\033[0m '+_('Error loading preset')+' # '+str(number))
Create_Variables()
# ------------------------------------------------------------------------------
# path to gis-weather.py
APP_PATH = os.path.abspath(os.path.dirname(sys.argv[0]))
if APP_PATH == '' or APP_PATH.startswith('.'):
print (_('Enter full path to script'))
print (_('Exit'))
exit()
THEMES_PATH = os.path.join(APP_PATH, 'themes')
ICONS_PATH = os.path.join(THEMES_PATH, 'icons')
BGS_PATH = os.path.join(THEMES_PATH, 'backgrounds')
ICONS_USER_PATH = os.path.join(CONFIG_PATH, 'icons')
BGS_USER_PATH = os.path.join(CONFIG_PATH, 'backgrounds')
make_dirs(os.path.join(ICONS_USER_PATH, 'default', 'weather'))
if indicator_is_appindicator == 'None':
if HAS_INDICATOR:
indicator_is_appindicator = 1
else:
indicator_is_appindicator = 0
Save_Config()
# additional variables
height = None
width = None
# cr = None
h_block = 95
w_block = 80
block_margin = 20
keep_above = False
keep_below = False
err_connect = False
first_start = True
try_no = 0
splash = True
err = False
on_redraw = False
timer_bool = True
get_weather_bool = True
not_composited = False
if check_for_updates == 0:
check_for_updates_local = False
else:
check_for_updates_local = True
icons_list = []
backgrounds_list = []
show_time_receive_local = False
time_receive = None
ind = None
pix_path = None
lock_update = False
t_scale_dict = {
0: "°C",
1: "°F",
2: "K"
}
desc_list = (
" Normal",
" Italic"
)
Pango_dict ={
'center': Pango.Alignment.CENTER,
'left': Pango.Alignment.LEFT,
'right': Pango.Alignment.RIGHT
}
if upd_time < 60:
upd_time = 60
# weather variables
weather = weather_vars.weather
# create variables
for i in weather.keys():
globals()[i] = weather[i]
if int(args.instances[0]) != 0:
instances_count = int(args.instances[0])
else:
instances_count = 0
if INSTANCE_NO < instances_count:
subprocess.Popen(['python3', os.path.join(APP_PATH, 'gis-weather.py'), '-i '+str(instances_count)])
def get_weather():
global service, weather_lang
if service not in data.services_list:
service = data.services_list[0]
weather_lang = data.get(service)[-1][0]
Save_Config()
if city_id == 0 or (not appid and data.get(service)['need_appid']):
if app.show_edit_dialog():
Save_Config()
if city_id == 0:
return False
else:
return data.get_weather(service)
def check_updates():
global lock_update
if lock_update:
return False
package = 'gz'
if os.path.exists(os.path.join(APP_PATH, 'package')):
f = open(os.path.join(APP_PATH, 'package'),"r")
package = f.readline().strip()
if package not in ('gz', 'deb', 'exe', 'rpm', 'aur', 'ppa'):
print ('package = '+package)
return False
if package in ('aur', 'ppa'):
global check_for_updates
check_for_updates = 0
Save_Config()
return False
print ('\033[34m>\033[0m '+_('Check for new version')+' '+'(%s)' % package)
try:
source = urlopen('http://sourceforge.net/projects/gis-weather/files/gis-weather/')
source = source.decode(encoding='UTF-8')
except:
print ('\033[1;31m[!]\033[0m '+_('Unable to check for updates'))
print ('-'*40)
return False
new_ver1 = re.findall('<a href="/projects/gis-weather/files/gis-weather/(.+)/"', source)
new_ver = new_ver1[0].split('.')
try:
temp = urlopen('http://sourceforge.net/projects/gis-weather/files/gis-weather/%s/'%new_ver1[0])
temp = temp.decode(encoding='UTF-8')
except:
print ('\033[1;31m[!]\033[0m '+_('Unable to check for updates'))
print ('-'*40)
return False
lock_update = True
temp_links = re.findall('sourceforge.net/projects/gis-weather/files/gis-weather/%s/(.+)/download'%new_ver1[0], temp)
update_link = ''
for i in range(len(temp_links)):
if temp_links[i].split('.')[-1] == package:
update_link = 'http://sourceforge.net/projects/gis-weather/files/gis-weather/%s/%s/download'%(new_ver1[0], temp_links[i])
file_name = temp_links[i]
if update_link == '':
new_ver = ['0', '0', '0', '0']
new_v = None
if diff_versions.diff(v.split('.'), new_ver):
new_v = new_ver1[0]
if new_v:
print ('\033[34m>>>\033[0m '+_('New version available')+' '+str(new_v))
print ('\033[34m>>>\033[0m '+str(update_link))
print ('-'*40)
global check_for_updates_local
check_for_updates_local = False
update_dialog.create(v, new_v, CONFIG_PATH, APP_PATH, update_link, file_name, package)
else:
print ('\033[34m>\033[0m '+_('You are using the latest version'))
print ('-'*40)
if check_for_updates == 1 and check_for_updates_local:
check_for_updates_local = False
lock_update = False
def screenshot():
w = Gdk.get_default_root_window()
if WIN:
import ctypes
user32 = ctypes.windll.user32
left, top, width, height = 0, 0, user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
else:
left, top, width, height = w.get_geometry()
pb = Gdk.pixbuf_get_from_window(w,left,top,width,height)
if (pb != None):
try:
pb.savev(os.path.join(CONFIG_PATH, "main_screenshot.png"),"png", (), ())
print (_("Screenshot saved to")+' '+os.path.join(CONFIG_PATH, "main_screenshot.png"))
except:
print (">> Pixbuf.savev Error")
else:
print (_("Unable to get the screenshot"))
def crop_image(left, top, width, height):
surface = cairo.ImageSurface.create_from_png(os.path.join(CONFIG_PATH, "main_screenshot.png"))
pb = Gdk.pixbuf_get_from_surface(surface, left, top, int(width*scale), int(height*scale))
try:
pb.savev(os.path.join(CONFIG_PATH, "screenshot.png"),"png", (), ())
except:
print (">> Pixbuf.savev Error")
def extract_svgz(icon, path):
inF = gzip.open(icon, 'rb')
outF = open(path, 'wb')
outF.write(inF.read())
inF.close()
outF.close()
def get_pixbuf(icon):
if icon[-4:] == 'svgz':
inF = gzip.open(icon, 'r')
loader = GdkPixbuf.PixbufLoader()
loader.write(inF.read())
loader.close()
inF.close()
pixbuf = loader.get_pixbuf()
else:
pixbuf = GdkPixbuf.Pixbuf.new_from_file(icon)
return pixbuf
class Indicator:
if indicator_is_appindicator and HAS_INDICATOR: # AppIndicator3
def __init__(self):
self.indicator = AppIndicator3.Indicator.new("gis-weather", "weather-clear", AppIndicator3.IndicatorCategory.APPLICATION_STATUS)
if show_indicator:
self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
self.hiden = False
else:
self.indicator.set_status(AppIndicator3.IndicatorStatus.PASSIVE)
self.hiden = True
def set_label(self, text):
self.indicator.set_label(text, '')
def set_icon(self, icon):
if app_indicator_fix_size:
self.set_icon_fixed(icon, app_indicator_size)
else:
if icon[-4:] == 'svgz':
extract_svgz(icon,os.path.join(CONFIG_PATH, 'tmp_cur_icon.svg'))
self.indicator.set_icon(os.path.join(CONFIG_PATH, 'tmp_cur_icon.svg'))
else:
self.indicator.set_icon(icon)
def set_icon_fixed(self, icon, size=None):
pixbuf = get_pixbuf(icon)
if size:
pixbuf = pixbuf.scale_simple(size,size,GdkPixbuf.InterpType.BILINEAR)
try:
pixbuf.savev(os.path.join(CONFIG_PATH, "tmp_cur_icon.png"),"png", (), ())
self.indicator.set_icon(os.path.join(CONFIG_PATH, "tmp_cur_icon.png"))
except:
print (">> Pixbuf.savev Error")
def set_menu(self, menu):
self.indicator.set_menu(menu)
self.indicator.connect("scroll-event", self.scroll)
def scroll(self, ind, steps, direction):
if direction == Gdk.ScrollDirection.UP:
app.menu_response(None, 'show_hide_widget', 'show')
elif direction == Gdk.ScrollDirection.DOWN:
app.menu_response(None, 'show_hide_widget', 'hide')
def hide(self):
if not self.hiden:
self.indicator.set_status(AppIndicator3.IndicatorStatus.PASSIVE)
self.hiden = True
def show(self):
if self.hiden:
self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
self.indicator.set_menu(app.menu)
self.hiden = False
def set_tooltip_markup(self, markup):
pass
else: # Gtk.StatusIcon
def __init__(self):
self.indicator = Gtk.StatusIcon()
self.indicator_label = Gtk.StatusIcon()
self.indicator.set_from_file(os.path.join(APP_PATH, "icon.png"))
if show_indicator:
self.indicator.set_visible(True)
self.indicator_label.set_visible(True)
self.hiden = False
else:
self.indicator.set_visible(False)
self.indicator_label.set_visible(False)
self.hiden = True
def set_label(self, text):
if show_indicator_text:
self.indicator_label.set_visible(True)
self.draw_text_to_png(self.indicator.get_size(), text)
self.indicator_label.set_from_file(os.path.join(CONFIG_PATH, "text.svg"))
else:
self.indicator_label.set_visible(False)
def set_icon(self, icon):
if icon[-4:] == 'svgz':
extract_svgz(icon,os.path.join(CONFIG_PATH, 'tmp_cur_icon.svg'))
self.indicator.set_from_file(os.path.join(CONFIG_PATH, 'tmp_cur_icon.svg'))
else:
self.indicator.set_from_file(icon)
def set_menu(self, menu):
self.indicator.connect("popup-menu", self.popup_menu)
self.indicator_label.connect("popup-menu", self.popup_menu)
def scroll(self, button, event):
if event.direction == Gdk.ScrollDirection.UP:
app.menu_response(None, 'show_hide_widget', 'show')
elif event.direction == Gdk.ScrollDirection.DOWN:
app.menu_response(None, 'show_hide_widget', 'hide')
def popup_menu(self, icon, widget, time):
app.create_menu(for_indicator=True, weather_menu=weather_menu)
app.menu.popup(None, None, None, None, widget, time)
def hide(self):
if not self.hiden:
self.indicator.set_visible(False)
self.indicator_label.set_visible(False)
self.hiden = True
def show(self):
if self.hiden:
self.indicator.set_visible(True)
self.indicator_label.set_visible(True)
self.hiden = False
def draw_text_to_png(self, HEIGHT, text):
WIDTH = indicator_width
# surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
# self.cr = cairo.Context(surface)
# if indicator_draw_shadow:
# self.cr.set_source_rgba(indicator_color_shadow[0], indicator_color_shadow[1], indicator_color_shadow[2], indicator_color_shadow[3])
# self.draw_indicator_text(text, 1, indicator_top+HEIGHT//8+1, indicator_font, indicator_font_size, WIDTH)
# self.cr.set_source_rgba(indicator_color_text[0], indicator_color_text[1], indicator_color_text[2], indicator_color_text[3])
# self.draw_indicator_text(text, 0, indicator_top+HEIGHT//8, indicator_font, indicator_font_size, WIDTH)
# surface.write_to_png(os.path.join(CONFIG_PATH, "text.png"))
surface = cairo.SVGSurface(os.path.join(CONFIG_PATH, "text.svg"), WIDTH, HEIGHT)
cr = cairo.Context(surface)
cr.select_font_face(indicator_font, cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
cr.set_font_size(indicator_font_size)
if indicator_draw_shadow:
cr.set_source_rgba(indicator_color_shadow[0], indicator_color_shadow[1], indicator_color_shadow[2], indicator_color_shadow[3])
cr.move_to(1, indicator_top+HEIGHT//8*7+1)
cr.show_text(text)
cr.set_source_rgba(indicator_color_text[0], indicator_color_text[1], indicator_color_text[2], indicator_color_text[3])
cr.move_to(0, indicator_top+HEIGHT//8*7)
cr.show_text(text)
cr.show_page()
# def draw_indicator_text(self, text, x, y, font, size, width=200, alignment=Pango.Alignment.LEFT):
# self.cr.save()
# self.cr.translate(x, y)
# font_desc = Pango.FontDescription(font)
# font_desc.set_size(size * Pango.SCALE)
# self.p_layout = PangoCairo.create_layout(self.cr)
# self.p_layout.set_font_description(font_desc)
# self.p_layout.set_width(width * Pango.SCALE)
# self.p_layout.set_alignment(alignment)
# self.p_layout.set_markup(text)
# PangoCairo.show_layout(self.cr, self.p_layout)
# self.cr.restore()
def set_tooltip_markup(self, markup):
self.indicator.set_tooltip_markup(markup)
class MyDrawArea(Gtk.DrawingArea):
p_layout = None
p_fdesc = None
cr = None
fmt = None
def __init__(self):
self.timer = GLib.timeout_add(1000, self.redraw)
GObject.GObject.__init__(self)
self.set_app_paintable(True)
self.connect('draw', self.expose)
def splash_screen(self, cr, state = 0):
if show_splash_screen == 0:
return
global try_no
if max_try_show != 0 and try_no >= max_try_show:
return
self.draw_bg(cr, bg_left, bg_top, bg_width, bg_height)
if show_splash_screen != 1:
self.draw_scaled_image(cr, width/2 - 64, splash_icon_top+splash_block_top+height/2 - 128, os.path.join(APP_PATH, 'icon.png'), 128, 128)
self.draw_text(cr, 'Gis Weather v ' + v, 0, splash_version_top+splash_block_top+height/2 - 8, font+' Normal', 14, width, Pango.Alignment.CENTER)
if state == 0:
self.draw_text(cr, _('Getting weather...'), 0, splash_version_top+splash_block_top+height/2 + 20, font+' Normal', 10, width, Pango.Alignment.CENTER)
else:
try_no += 1
self.draw_text(cr, _('Error getting weather')+' '+ str(try_no), 0, splash_version_top+splash_block_top+height/2 + 20, font+' Normal', 10, width, Pango.Alignment.CENTER)
if city_id == 0:
self.draw_text(cr, _('Location not set'), 0, splash_version_top+splash_block_top+height/2 + 40, font+' Normal', 10, width, Pango.Alignment.CENTER)
def redraw(self, timer1 = True, get_weather1 = True, load_config = False):
global first_start, on_redraw, timer_bool, get_weather_bool
if load_config:
Load_Config()
app.set_window_properties()
timer_bool = timer1
get_weather_bool = get_weather1
on_redraw = True
if first_start:
first_start = False
if show_indicator == 0:
ind.hide()
else:
ind.show()
if show_indicator == 1:
app.window_main.hide()
else:
app.window_main.show()
if show_indicator == 1:
self.expose_indicator()
self.queue_draw()
while Gtk.events_pending():
Gtk.main_iteration_do(True)
if check_for_updates_local and get_weather1:
check_updates()
if indicator_is_appindicator:
app.create_menu(for_indicator=True, weather_menu=weather_menu)
ind.set_menu(app.menu)
def expose_indicator(self):
global err, on_redraw, get_weather_bool, weather, err_connect
if get_weather_bool:
weather1 = get_weather()
if weather1:
time_receive = time.strftime('%H:%M', time.localtime())
err_connect = False
splash = False
weather = weather1
for i in weather.keys():
globals()[i] = weather[i]
else:
err_connect = True
get_weather_bool = False
if not timer_bool:
print ('-'*40)
if err_connect:
if on_redraw:
on_redraw = False
if timer_bool:
self.timer = GLib.timeout_add(10000, self.redraw)
else:
if on_redraw:
on_redraw = False
if timer_bool:
self.timer = GLib.timeout_add(upd_time*60*1000, self.redraw)
print ('\033[34m>\033[0m '+_('Next update in')+' '+str(upd_time)+' '+_('min'))
print ('-'*40)
self.Draw_Weather(self.cr)
def clear_draw_area(self, widget):
self.cr = Gdk.cairo_create(self.get_window())
self.cr.save()
if fix_BadDrawable:
self.cr.set_source_rgba(0.5, 0.5, 0.5, 0.01)
else:
self.cr.set_source_rgba(1, 1, 1, 0)
self.cr.set_operator(cairo.OPERATOR_SOURCE)
self.cr.paint()
self.cr.restore()
self.cr.scale(scale, scale)
# self.cr.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
def expose(self, widget, event):
global err, on_redraw, get_weather_bool, weather, err_connect, splash, time_receive, date
self.clear_draw_area(widget)
if first_start:
self.splash_screen(self.cr)
return
if get_weather_bool:
weather1 = get_weather()
if weather1:
time_receive = time.strftime('%H:%M', time.localtime())
err_connect = False
splash = False
weather = weather1
for i in weather.keys():
globals()[i] = weather[i]
date = date_convert.main(date, date_separator, swap_d_and_m)
else:
if timer_bool:
print ('\033[1;31m[!]\033[0m '+_('Next try in 10 seconds'))
err_connect = True
get_weather_bool = False
if not timer_bool:
print ('-'*40)
if err_connect:
if on_redraw:
on_redraw = False
if timer_bool:
self.timer = GLib.timeout_add(10000, self.redraw)
print ('-'*40)
if splash:
self.splash_screen(self.cr, 1)
else:
self.Draw_Weather(self.cr)
self.draw_scaled_image(self.cr, margin + 10, margin + 10, os.path.join(THEMES_PATH, 'error.png'),24,24)
self.draw_text(self.cr, _('Connection error'), margin + 35, margin + 14, font+' Normal', 10, color = color_text_week)
err = True
else:
if err == True:
err = False
self.clear_draw_area(widget)
if on_redraw:
on_redraw = False
if timer_bool:
self.timer = GLib.timeout_add(upd_time*60*1000, self.redraw)
print ('\033[34m>\033[0m '+_('Next update in')+' '+str(upd_time)+' '+_('min'))
print ('-'*40)
self.Draw_Weather(self.cr)
if save_widget:
path_to_save = None
if os.path.exists(os.path.dirname(save_widget_path)):
path_to_save = save_widget_path
self.save_widget_screenshot(path_to_save)
def Draw_Weather(self, cr):
if save_cur_icon:
path_to_save = CONFIG_PATH
if os.path.exists(save_cur_data_path):
path_to_save = save_cur_data_path
self.draw_scaled_icon(cr, 0, 0, weather['icon_now'][0],1,1, indicator_icons_name)
pixbuf = get_pixbuf(pix_path)
pixbuf.savev(os.path.join(path_to_save, "cur_icon.png"),"png", (), ())
t_index = t_scale*2
if t_feel:
t_index += 1
self.fmt = {
'city_name': city_name[0] if not city_name_custom else city_name_custom,
't_now': t_now[0].split(';')[t_scale*2],
't_now_feel': t_now[0].split(';')[t_scale*2+1],
'condition_now': text_now[0],
'wind_direct_now': wind_direct_now[0] if wind_direct_now else '',
'wind_speed_now': wind_speed_now[0].split(';')[wind_units].split()[0],
'wind_units_now': wind_speed_now[0].split(';')[wind_units].split()[-1],
'sunrise': sunrise,
'sunset': sunset,
'pressure_now': press_now[0].split(';')[press_units].split()[0] if press_now else '',
'pressure_units_now': _(press_now[0].split(';')[press_units].split()[-1]) if press_now else '',
'humidity_now': hum_now[0]+' %' if hum_now else '',
'icon_now': weather['icon_now'][0].split(';')[-1],
'Temperature': _('Temperature')+':',
'Feels_like': _('feels like')+':',
'Wind': _('Wind')+':',
'Pressure': _('Pressure')+':',
'Humidity': _('Humidity')+':',
'Sunrise': _('Sunrise')+':',
'Sunset': _('Sunset')+':'}
if save_cur_temp:
t_now_post = ''
if save_cur_temp_add_scale:
t_now_post = t_scale_dict[t_scale][-1]
path_to_save = CONFIG_PATH
if os.path.exists(save_cur_data_path):
path_to_save = save_cur_data_path
if save_cur_temp_to_pipe:
if os.path.isfile(os.path.join(path_to_save, 'cur_temp')):
os.remove(os.path.join(path_to_save, 'cur_temp'))
os.mkfifo(os.path.join(path_to_save, 'cur_temp'))
if not os.path.exists(os.path.join(path_to_save, 'cur_temp')):
os.mkfifo(os.path.join(path_to_save, 'cur_temp'))
elif not os.path.isfile(os.path.join(path_to_save, 'cur_temp')) and os.path.exists(os.path.join(path_to_save, 'cur_temp')):
os.remove(os.path.join(path_to_save, 'cur_temp'))
process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=1, universal_newlines=True)
process.stdin.write('echo "'+t_now[0].split(';')[t_index]+t_now_post+'" > '+os.path.join(path_to_save, 'cur_temp')+' && exit 0\n')
try:
process.wait(60)
except:
process.kill()
print(os.path.join(path_to_save, 'cur_temp')+' saved (%s)'%t_now[0].split(';')[t_index]+t_now_post)
if save_weather:
path_to_save = CONFIG_PATH
if os.path.exists(save_weather_path):
path_to_save = save_weather_path
if save_weather_fmt != '':
weather_text = save_weather_fmt
else:
weather_text = '<tt><big><b><u>{city_name:^30}</u></b></big>\n \n '+\
'<b>{condition_now}</b>\n \n '+\
'{Temperature:<15}<big>{t_now}C</big>\n '+\
'{Feels_like:<15}<big>{t_now_feel}C</big>\n '+\
'{Wind:<15}<big>{wind_direct_now} {wind_speed_now}</big> {wind_units_now}\n '+\
'{Pressure:<15}<big>{pressure_now}</big> {pressure_units_now} \n '+\
'{Humidity:<15}<big>{humidity_now}</big>\n \n '+\
'{Sunrise:<15}{sunrise}\n '+\
'{Sunset:<15}{sunset}\n</tt>'
cur_weather_file = open(os.path.join(path_to_save, 'cur_weather'), 'w')
cur_weather_file.write(weather_text.format_map(self.fmt))
cur_weather_file.close()
print(os.path.join(path_to_save, 'cur_weather')+' saved')
for i in ('pipe1', 'pipe2', 'pipe3'):
if globals()[i]['active']:
if not os.path.exists(globals()[i]['path']):
os.mkfifo(globals()[i]['path'])
print('write to {i} ({path})'.format(i=i, path=globals()[i]['path']))
process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=1, universal_newlines=True)
process.stdin.write('echo "'+globals()[i]['text'].format_map(self.fmt)+'" > '+globals()[i]['path']+' && exit 0\n')
try:
process.wait(60)
except:
process.kill()
for i in ('text_file1', 'text_file2', 'text_file3'):
if globals()[i]['active']:
text_file = open(globals()[i]['path'], 'w')
text_file.write(globals()[i]['text'].format_map(self.fmt))
text_file.close()
print('{i} ({path}) saved'.format(i=i, path=globals()[i]['path']))
if show_indicator:
self.draw_scaled_icon(cr, 0, 0, weather['icon_now'][0],1,1, indicator_icons_name)