-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
ubuntu-mate-welcome
executable file
·4203 lines (3636 loc) · 194 KB
/
ubuntu-mate-welcome
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/python3
# -*- coding:utf-8 -*-
#
# Copyright 2012-2013 "Korora Project" <dev@kororaproject.org>
# Copyright 2013 "Manjaro Linux" <support@manjaro.org>
# Copyright 2014 Antergos
# Copyright 2015-2022 Martin Wimpress <code@flexion.org>
# Copyright 2015-2020 Luke Horwell <luke@ubuntu-mate.org>
#
# Ubuntu MATE Welcome 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.
#
# Ubuntu MATE Welcome 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 Ubuntu MATE Welcome. If not, see <http://www.gnu.org/licenses/>.
#
""" Welcome screen for Ubuntu MATE """
import gi
gi.require_version("Gdk", "3.0")
gi.require_version("Gtk", "3.0")
gi.require_version("Notify", "0.7")
gi.require_version("WebKit2", "4.0")
import apt
#import distro
import colorsys
import errno
import gettext
import inspect
import json
import locale
import os
import random
import signal
import socket
import subprocess
import sys
import time
import webbrowser
import re
import math
import urllib.error
import urllib.parse
import urllib.request
from aptdaemon.client import AptClient
from aptdaemon.gtk3widgets import AptErrorDialog, AptConfirmDialog, \
AptProgressDialog
import aptdaemon.errors
from aptdaemon.enums import *
from gi.repository import GLib, Gio, GObject, Gdk, Gtk, Notify, WebKit2
from threading import Thread
from shutil import which
from subprocess import DEVNULL, PIPE
# FIXME! Temporary workaround to make sure the snap works even if proctitle is not installed on the host.
try:
import setproctitle
proctitle_available = True
except ImportError:
proctitle_available = False
__VERSION__ = '22.04.0'
UBUNTU_MATE_COLOURS = ['Aqua', 'Blue', 'Brown', 'Orange', 'Pink', 'Purple', 'Red', 'Teal', 'Yellow']
UBUNTU_MATE_WALLPAPERS = [
'[]-Jazz.jpg',
'[]-Wall-Logo-Text.png',
'[]-Wall-Logo.png',
'[]-Wall.png',
'Ubuntu-MATE-Splash.jpg'
]
##################################
# Miscellaneous
##################################
def get_string(schema, path, key):
if path:
settings = Gio.Settings.new_with_path(schema, path)
else:
settings = Gio.Settings.new(schema)
return settings.get_string(key)
def goodbye(a=None, b=None):
# NOTE: _a_ and _b_ are passed via the close window 'delete-event'.
''' Closing the program '''
# Refuse to quit if operations are in progress.
if dynamicapps.operations_busy:
dbg.stdout('Welcome', 'Refusing to quit with software changes in progress!', 0, 1)
title = string.boutique
text_busy = _('Software changes are in progress. Please allow them to complete before closing Welcome.')
ok_label = _("OK")
if which('zenity'):
dialog_app = which('zenity')
elif which('yad'):
dialog_app = which('yad')
else:
dialog_app = None
if dialog_app is not None:
messagebox = subprocess.Popen([dialog_app,
'--error',
'--title=' + title,
"--text=" + text_busy,
"--ok-label=" + ok_label,
'--width=400',
'--window-icon=error',
'--timeout=9'])
return 1
else:
dbg.stdout('Welcome', 'Application Closed', 0, 0)
Gtk.main_quit()
# Be quite forceful, particularly those child screenshot windows.
exit()
def whereami():
""" Determine data source """
current_folder = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe())) )
if( os.path.exists( os.path.join(current_folder, 'data/' ) ) ):
dbg.stdout('Welcome', 'Using relative path for data source. Non-production testing.', 1, 0)
data_path = os.path.join(current_folder, 'data/')
elif( os.path.exists('/usr/share/ubuntu-mate-welcome/') ):
dbg.stdout('Welcome', 'Using /usr/share/ubuntu-mate-welcome/ path.', 1, 0)
data_path = '/usr/share/ubuntu-mate-welcome/'
elif( os.path.exists(os.environ.get('SNAP') + '/usr/share/ubuntu-mate-welcome/') ):
dbg.stdout('Welcome', 'Using ' + os.environ.get('SNAP') + '/usr/share/ubuntu-mate-welcome/ path.', 1, 0)
data_path = os.environ.get('SNAP') + '/usr/share/ubuntu-mate-welcome/'
else:
dbg.stdout('Welcome', 'Unable to source the ubuntu-mate-welcome data directory.', 0, 1)
sys.exit(1)
return data_path
def notify_send(title, description, icon_path):
"""
Send system notification to the user.
"""
try:
Notify.init(_("Software Boutique"))
notification=Notify.Notification.new(title, description, icon_path)
notification.show()
except Exception as e:
dbg.stdout("Notify", "Exception while sending notification: " + str(e), 0, 1)
def run_external_command(command, with_shell=False):
# Runs external commands and cleans up the output.
if with_shell:
raw = str(subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).communicate()[0])
else:
raw = str(subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0])
output = raw.replace("b'","").replace('b"',"").replace("\\n'","").replace("\\n","\n")
return output
##################################
# Apt and Installation Operations
##################################
class SimpleApt(object):
def __init__(self, packages, action, program_id=None):
self._timeout = 100
self.packages = packages
self.action = action
self.source_to_update = None
self.update_cache = False
self.loop = GLib.MainLoop()
self.client = AptClient()
self.program_id = program_id
def on_error(self, error):
dynamicapps.operations_busy = False
if isinstance(error, aptdaemon.errors.NotAuthorizedError):
# Silently ignore auth failures
return
elif not isinstance(error, aptdaemon.errors.TransactionFailed):
# Catch internal errors of the client
error = aptdaemon.errors.TransactionFailed(ERROR_UNKNOWN,
str(error))
error_dialog = AptErrorDialog(error)
error_dialog.run()
error_dialog.hide()
def on_finished_fix_incomplete_install(self, transaction, status):
dynamicapps.operations_busy = False
self.loop.quit()
if status == 'exit-success':
notify_send( _("Successfully performed fix."), _("Any previously incomplete installations have been finished."), data_path + 'img/notify/fix-success.svg' )
return True
else:
notify_send( _("Failed to perform fix."), _("Errors occurred while finishing an incomplete installation."), data_path + 'img/notify/fix-error.svg' )
return False
def on_finished_fix_broken_depends(self, transaction, status):
dynamicapps.operations_busy = False
self.loop.quit()
if status == 'exit-success':
notify_send( _("Successfully performed fix."), _("Packages with broken dependencies have been resolved."), data_path + 'img/notify/fix-success.svg')
return True
else:
notify_send( _("Failed to perform fix."), _("Packages may still have broken dependencies."), data_path + 'img/notify/fix-error.svg')
return False
def on_finished_update(self, transaction, status):
dynamicapps.operations_busy = False
# Show notification if user forces cache update.
if self.action == 'update':
self.loop.quit()
if status == 'exit-success':
notify_send(_("Successfully updated cache."), _("Software is now ready to install."), data_path + 'img/notify/fix-success.svg')
return True
else:
notify_send( _("Failed to update cache."), _("There may be a problem with your repository configuration."), data_path + 'img/notify/fix-error.svg')
return False
elif self.action == 'install':
if status != 'exit-success':
self.do_notify(status)
self.loop.quit()
return False
GLib.timeout_add(self._timeout,self.do_install)
return True
elif self.action == 'upgrade':
if status != 'exit-success':
self.do_notify(status)
self.loop.quit()
return False
GLib.timeout_add(self._timeout,self.do_upgrade)
return True
def on_finished_install(self, transaction, status):
dynamicapps.operations_busy = False
self.loop.quit()
if status != 'exit-success':
return False
else:
self.do_notify(status)
def on_finished_remove(self, transaction, status):
dynamicapps.operations_busy = False
self.loop.quit()
if status != 'exit-success':
return False
else:
self.do_notify(status)
def on_finished_upgrade(self, transaction, status):
dynamicapps.operations_busy = False
self.loop.quit()
if status != 'exit-success':
return False
else:
self.do_notify(status)
def do_notify(self, status):
# Notifications for individual applications.
if self.program_id:
name = dynamicapps.get_attribute_for_app(self.program_id, 'name')
img = dynamicapps.get_attribute_for_app(self.program_id, 'img')
img_path = os.path.join(data_path, 'img', 'applications', img + '.png')
if not os.path.exists(img_path):
img_path = 'package'
dbg.stdout('Apps', 'Changed status for "' + self.program_id + '": ' + status, 0, 3)
# Show a different notification for Welcome Updates
if self.program_id == 'ubuntu-mate-welcome' and status == 'exit-success':
notify_send( _("Welcome will stay up-to-date."), \
_("Welcome and the Software Boutique are set to receive the latest updates."), \
os.path.join(data_path, 'img', 'welcome', 'ubuntu-mate-icon.svg'))
return
# Show a different notification for "Upgrade Installed Packages" fix
if self.program_id == 'ubuntu-standard' and status == 'exit-success':
notify_send( _("Everything is up-to-date"), \
_("All packages have been upgraded to the latest versions."), \
os.path.join(data_path, 'img', 'welcome', 'ubuntu-mate-icon.svg'))
return
if self.action == 'install':
title_success = name + ' ' + _('Installed')
descr_success = _("The application is now ready to use.")
title_cancel = name + ' ' + _("was not installed.")
descr_cancel = _("The operation was cancelled.")
title_error = name + ' ' + _("failed to install")
descr_error = _("There was a problem installing this application.")
elif self.action == 'remove':
title_success = name + ' ' + _('Removed')
descr_success = _("The application has been uninstalled.")
title_cancel = name + ' ' + _("was not removed.")
descr_cancel = _("The operation was cancelled.")
title_error = name + ' ' + _("failed to remove")
descr_error = _("A problem is preventing this application from being removed.")
elif self.action == 'upgrade':
title_success = name + ' ' + _('Upgraded')
descr_success = _("This application is set to use the latest version.")
title_cancel = name + ' ' + _("was not upgraded.")
descr_cancel = _("The application will continue to use the stable version.")
title_error = name + ' ' + _("failed to upgrade")
descr_error = _("A problem is preventing this application from being upgraded.")
# Do not show notifications when updating the cache
if self.action != 'update':
if status == 'exit-success':
notify_send(title_success, descr_success, img_path)
elif status == 'exit-cancelled':
notify_send(title_cancel, descr_cancel, img_path)
else:
notify_send(title_error, descr_error, img_path)
def do_fix_incomplete_install(self):
dynamicapps.operations_busy = True
# Corresponds to: dpkg --configure -a
apt_fix_incomplete = self.client.fix_incomplete_install()
apt_fix_incomplete.connect("finished",self.on_finished_fix_incomplete_install)
fix_incomplete_dialog = AptProgressDialog(apt_fix_incomplete)
fix_incomplete_dialog.run(close_on_finished=True, show_error=True,
reply_handler=lambda: True,
error_handler=self.on_error,
)
return False
dynamicapps.operations_busy = False
def do_fix_broken_depends(self):
dynamicapps.operations_busy = True
# Corresponds to: apt-get --fix-broken install
apt_fix_broken = self.client.fix_broken_depends()
apt_fix_broken.connect("finished",self.on_finished_fix_broken_depends)
fix_broken_dialog = AptProgressDialog(apt_fix_broken)
fix_broken_dialog.run(close_on_finished=True, show_error=True,
reply_handler=lambda: True,
error_handler=self.on_error,
)
return False
dynamicapps.operations_busy = False
def do_update(self):
if self.source_to_update:
apt_update = self.client.update_cache(self.source_to_update)
else:
apt_update = self.client.update_cache()
try:
apt_update.connect("finished",self.on_finished_update)
except AttributeError:
return
if pref.get('hide-apt-progress', False):
apt_update.run()
else:
update_dialog = AptProgressDialog(apt_update)
update_dialog.run(close_on_finished=True, show_error=True,
reply_handler=lambda: True,
error_handler=self.on_error,
)
return False
def do_install(self):
apt_install = self.client.install_packages(self.packages)
apt_install.connect("finished", self.on_finished_install)
if pref.get('hide-apt-progress', False):
apt_install.run()
else:
install_dialog = AptProgressDialog(apt_install)
install_dialog.run(close_on_finished=True, show_error=True,
reply_handler=lambda: True,
error_handler=self.on_error,
)
return False
def do_remove(self):
apt_remove = self.client.remove_packages(self.packages)
apt_remove.connect("finished", self.on_finished_remove)
if pref.get('hide-apt-progress', False):
apt_remove.run()
else:
remove_dialog = AptProgressDialog(apt_remove)
remove_dialog.run(close_on_finished=True, show_error=True,
reply_handler=lambda: True,
error_handler=self.on_error,
)
return False
def do_upgrade(self):
apt_upgrade = self.client.upgrade_system(True)
apt_upgrade.connect("finished", self.on_finished_upgrade)
upgrade_dialog = AptProgressDialog(apt_upgrade)
upgrade_dialog.run(close_on_finished=True, show_error=True,
reply_handler=lambda: True,
error_handler=self.on_error,
)
return False
def install_packages(self):
dynamicapps.operations_busy = True
if self.update_cache:
GLib.timeout_add(self._timeout,self.do_update)
else:
GLib.timeout_add(self._timeout,self.do_install)
self.loop.run()
dynamicapps.operations_busy = False
def remove_packages(self):
dynamicapps.operations_busy = True
GLib.timeout_add(self._timeout,self.do_remove)
self.loop.run()
dynamicapps.operations_busy = False
def upgrade_packages(self):
dynamicapps.operations_busy = True
if self.update_cache:
GLib.timeout_add(self._timeout,self.do_update)
else:
GLib.timeout_add(self._timeout,self.do_upgrade)
self.loop.run()
dynamicapps.operations_busy = False
def fix_incomplete_install(self):
dynamicapps.operations_busy = True
GLib.timeout_add(self._timeout,self.do_fix_incomplete_install)
self.loop.run()
dynamicapps.operations_busy = False
def fix_broken_depends(self):
dynamicapps.operations_busy = True
GLib.timeout_add(self._timeout,self.do_fix_broken_depends)
self.loop.run()
dynamicapps.operations_busy = False
def update_repos():
transaction = SimpleApt('', 'update')
transaction.update_cache = True
transaction.do_update()
def fix_incomplete_install():
transaction = SimpleApt('', 'fix-incomplete-install')
transaction.fix_incomplete_install()
def fix_broken_depends():
transaction = SimpleApt('', 'fix-broken-depends')
transaction.fix_broken_depends()
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def get_aacs_db():
home_dir = GLib.get_home_dir()
key_url = 'http://www.labdv.com/aacs/KEYDB.cfg'
key_db = os.path.join(home_dir, '.config', 'aacs', 'KEYDB.cfg')
mkdir_p(os.path.join(home_dir, '.config', 'aacs'))
dbg.stdout('AACS', 'Getting ' + key_url + ' and saving as ' + key_db, 0, 0)
# Download the file from `key_url` and save it locally under `file_name`:
try:
with urllib.request.urlopen(key_url) as response, open(key_db, 'wb') as out_file:
data = response.read() # a `bytes` object
out_file.write(data)
Notify.init(_('Blu-ray AACS database install succeeded'))
aacs_notify=Notify.Notification.new(_('Successfully installed the Blu-ray AACS database.'), _('Installation of the Blu-ray AACS database was successful.'), 'dialog-information')
aacs_notify.show()
except:
Notify.init(_('Blu-ray AACS database install failed'))
aacs_notify=Notify.Notification.new(_('Failed to install the Blu-ray AACS database.'), _('Installation of the Blu-ray AACS database failed.'), 'dialog-error')
aacs_notify.show()
class PreInstallation(object):
"""
See the JSON Structure in the `DynamicApps` class on
how to specify pre-configuration actions in `applications.json`
"""
def __init__(self):
# Always ensure we have the correct variables, not any overrides.
self.os_version = subprocess.run(['lsb_release','-rs'], stdout=subprocess.PIPE).stdout.decode('utf-8').strip('\n')
self.codename = subprocess.run(['lsb_release','-cs'], stdout=subprocess.PIPE).stdout.decode('utf-8').strip('\n')
dbg.stdout('Pre-Install', "System is running Ubuntu " + self.os_version + " (" + self.codename + ")", 1, 0)
def process_packages(self, program_id, action, preconfigure_only=False):
simulating = arg.simulate_software_changes
# Get category for this program, which can be used to retrieve data later.
category = dynamicapps.get_attribute_for_app(program_id, 'category')
fullname = dynamicapps.get_attribute_for_app(program_id, 'img')
img = dynamicapps.get_attribute_for_app(program_id, 'img')
try:
preconfig = dynamicapps.index[category][program_id]['pre-install']
except:
dbg.stdout('Pre-Install', 'Missing pre-configuration data for "' + program_id + '". Refusing to continue.', 0, 1)
return
try:
if action == 'install':
packages = dynamicapps.index[category][program_id]['install-packages']
dbg.stdout('Apps', 'Packages to be installed:\n ' + packages, 0, 0)
elif action == 'remove':
packages = dynamicapps.index[category][program_id]['remove-packages']
dbg.stdout('Apps', 'Packages to be removed:\n ' + packages, 0, 0)
elif action == 'upgrade':
packages = dynamicapps.index[category][program_id]['upgrade-packages']
dbg.stdout('Apps', 'Packages to be upgraded:\n ' + packages, 0, 0)
else:
dbg.stdout('Apps', 'Invalid action was requested.', 0, 1)
return
except:
dbg.stdout('Apps', 'No packages retrieved for requested action.', 0, 1)
return
# Validate that we have packages to work with.
if len(packages):
packages = packages.split(',')
else:
dbg.stdout('Apps', 'No package(s) supplied for "' + program_id + '".', 0, 1)
return
transaction = SimpleApt(packages, action, program_id)
# Function to run privileged commands.
def run_task(function):
if os.environ.get('SNAP'):
subprocess.call(['pkexec', os.environ.get('SNAP') + '/usr/lib/ubuntu-mate/ubuntu-mate-welcome-repository-installer', os.path.abspath(os.path.join(data_path, 'js/applications.json')), function, category, program_id, target])
else:
subprocess.call(['pkexec', '/usr/lib/ubuntu-mate/ubuntu-mate-welcome-repository-installer', os.path.abspath(os.path.join(data_path, 'js/applications.json')), function, category, program_id, target])
# Determine if any pre-configuration is specific to a codename.
try:
preinstall = dynamicapps.index[category][program_id]['pre-install']
codenames = list(preinstall.keys())
except:
dbg.stdout('Pre-Install', 'No data specified for "' + program_id + '". This application entry is invalid.', 0, 1)
return
dbg.stdout('Pre-Install', 'Available configurations: ' + str(codenames), 1, 0)
target = None
for codename in codenames:
for name in codename.split(","):
if name == self.codename:
target = codename
break
if not target:
target = 'all'
dbg.stdout('Pre-Install', 'Using "all" pre-configuration.', 1, 0)
else:
dbg.stdout('Pre-Install', 'Using configuration for: "' + target + '".', 1, 0)
methods = preinstall[target]['method'].split('+')
if not methods:
dbg.stdout('Pre-Install', 'No pre-install method was specified. The index is invalid.', 0, 1)
else:
dbg.stdout('Pre-Install', 'Configuration changes: ' + str(methods), 0, 0)
# Perform any pre-configuration, if necessary.
if action == 'install' or action == 'upgrade':
# Enable i386 repository (19.10 and later) if app requires 32-bit libs/packages.
try:
requires_i386 = dynamicapps.get_attribute_for_app(program_id, 'enable_i386')
if requires_i386 == True:
run_task('enable_i386')
except KeyError:
pass
# Add repository
for method in methods:
if method == 'skip':
dbg.stdout('Pre-Install', 'Using the Ubuntu repository.', 0, 0)
continue
elif method == 'partner-repo':
dbg.stdout('Pre-Install', 'Enabling the Ubuntu partner repository.', 0, 3)
if not simulating:
run_task('enable_partner_repository')
transaction.update_cache = True
queue.must_update_cache = True
elif method == 'multiverse-repo':
dbg.stdout('Pre-Install', 'Enabling the Ubuntu multiverse repository.', 0, 3)
if not simulating:
run_task('enable_multiverse_repository')
transaction.update_cache = True
queue.must_update_cache = True
elif method == 'ppa':
try:
ppa = preinstall[target]['enable-ppa']
except:
dbg.stdout('Pre-Install', 'Missing "enable-ppa" attribute. Cannot add PPA as requested.', 0, 1)
return
dbg.stdout('Pre-Install', 'Adding PPA: "' + ppa + '" and updating cache.', 0, 3)
if not simulating:
run_task('enable_ppa')
transaction.update_cache = True
queue.must_update_cache = True
try:
source_file = preinstall[target]['source-file'].replace('OSVERSION',self.os_version).replace('CODENAME',self.codename)
dbg.stdout('Pre-Install', 'Updating Apt Source: "' + source_file + '.list"', 0, 3)
if not simulating:
transaction.source_to_update = source_file + '.list'
except:
dbg.stdout('Pre-Install', 'Updating entire Apt cache. (No individual source file specified)', 1, 3)
elif method == 'manual':
# Do we get the apt key from a URL?
try:
apt_key_url = preinstall[target]['apt-key-url'].replace('OSVERSION',self.os_version).replace('CODENAME',self.codename)
dbg.stdout('Pre-Install', 'Getting Apt key from URL: "' + apt_key_url + '"', 0, 3)
if not simulating:
run_task('add_apt_key_from_url')
queue.must_update_cache = True
except:
dbg.stdout('Pre-Install', 'No apt key to retrieve from a URL.', 1, 0)
# Do we get the apt key from the server?
try:
apt_key_server = preinstall[target]['apt-key-server'][0]
apt_key_key = preinstall[target]['apt-key-server'][1]
dbg.stdout('Pre-Install', 'Getting key "' + apt_key_key + '" from keyserver: "' + apt_key_server + '"', 0, 3)
if not simulating:
run_task('add_apt_key_from_keyserver')
queue.must_update_cache = True
except:
dbg.stdout('Pre-Install', 'No apt key to retrieve from a key server.', 1, 0)
# Do we need to add an apt source file?
try:
source = preinstall[target]['apt-sources']
source_file = preinstall[target]['source-file'].replace('OSVERSION',self.os_version).replace('CODENAME',self.codename)
dbg.stdout('Pre-Install', 'Writing source file: ' + source_file + '.list', 0, 3)
dbg.stdout('Pre-Install', ' -------- Start of file ------', 1, 4)
for line in source:
dbg.stdout('Pre-Install', ' ' + line.replace('OSVERSION',self.os_version).replace('CODENAME',self.codename), 0, 0)
dbg.stdout('Pre-Install', ' -------- End of file ------', 1, 4)
try:
dbg.stdout('Pre-Install', 'Updating Apt Source: ' + source_file + '.list', 0, 3)
if not simulating:
run_task('add_apt_sources')
transaction.source_to_update = source_file + '.list'
transaction.update_cache = True
queue.must_update_cache = True
except:
dbg.stdout('Pre-Install', 'Failed to add apt sources!', 0, 1)
except:
dbg.stdout('Pre-Install', 'No source data or source file to write.', 0, 1)
elif action == 'remove':
try:
# The function uses wild cards, so we don't need to worry about being explict.
listname = preinstall[target]['source-file'].replace('CODENAME','').replace('OSVERSION','')
if simulating:
dbg.stdout('Simulation', 'Deleting Apt Source: ' + listname, 0, 3)
else:
run_task('del_apt_sources')
queue.must_update_cache = True
except:
dbg.stdout('Pre-Install', 'No apt source specified, so none will be removed.', 1, 0)
# Pre-configuration complete. Now perform the operations.
# Do not do this if:
# * Simulation flag is active.
# * Part of the bulk queue - which handles packages differently.
if not preconfigure_only:
if simulating:
dbg.stdout('Pre-Install', 'Simulation flag active. No changes will be performed.', 0, 2)
return
else:
if transaction.action == 'install':
transaction.install_packages()
elif transaction.action == 'remove':
transaction.remove_packages()
elif transaction.action == 'upgrade':
transaction.upgrade_packages()
##################################
# Translations Framework & Strings
##################################
class Translations(object):
def __init__(self, data_path):
# Pages that do not want to be translated.
self.excluded_pages = ['message.html']
# Determine which locale to use
if arg.locale:
self.locale = arg.locale
else:
try:
self.locale = str(locale.getlocale()[0])
except Exception:
dbg.stdout("i18n", "Could not get system locale information! Falling back to 'en_US'.")
self.locale = "en_US"
# Determine if localized pages exist, or fallback to original pages.
def get_pages_path():
if os.path.exists(os.path.join(data_path, 'i18n', self.locale)):
self.localized = True
self.relative_i18n = True
dbg.stdout('i18n', 'Locale Set: ' + self.locale + ' (using relative path)', 1, 0)
return os.path.join(data_path, 'i18n', self.locale)
elif (os.path.exists(os.path.join('/usr/share/ubuntu-mate-welcome/i18n/', self.locale))):
self.localized = True
self.relative_i18n = False
dbg.stdout('i18n', 'Locale Set: ' + self.locale + ' (using /usr/share/ path)', 1, 0)
return os.path.join('/usr/share/ubuntu-mate-welcome/i18n/', self.locale)
else:
self.localized = False
self.relative_i18n = False
dbg.stdout('i18n', 'Locale Not Available: ' + self.locale + ' (using en_US instead)', 1, 1)
return data_path
self.pages_dir = get_pages_path()
# Should this locale not exist, try a generic one. (e.g. "en_GB" → "en")
if self.pages_dir == data_path:
self.localized = False
self.locale = self.locale.split('_')[0]
self.pages_dir = get_pages_path()
else:
self.localized = True
# Validate all the i18n pages so we have the same structure as the original.
page_was_lost = False
if not self.pages_dir == data_path:
for page in os.listdir(data_path):
if page[-5:] == '.html':
if os.path.exists(os.path.join(self.pages_dir, page)):
dbg.stdout('i18n', 'Page Verified: ' + page, 2, 2)
else:
if page not in self.excluded_pages:
page_was_lost = True
dbg.stdout('i18n', 'Page Missing: ' + page, 2, 1)
if page_was_lost:
dbg.stdout('i18n', 'One or more translation pages are missing! Falling back to "en_US".', 0, 1)
self.pages_dir = data_path
self.localized = False
else:
dbg.stdout('i18n', 'All translated i18n pages found.', 1, 2)
# Sets the path for resources (img/css/js)
if self.localized:
# E.g. data/i18n/en_GB/*.html → data/
self.res_dir = '../../'
else:
# E.g. data/*.html → data/
self.res_dir = ''
# Initalise i18n for Python translations.
if self.relative_i18n:
i18n_path = os.path.realpath(os.path.dirname(__file__) + '/locale/')
if os.environ.get('SNAP'):
i18n_path = os.path.realpath(os.path.dirname(__file__) + '/../share/locale/')
if not self.relative_i18n:
i18n_path = '/usr/share/locale/'
global t, _
dbg.stdout('i18n', 'Using locale for gettext: ' + self.locale, 1, 0)
dbg.stdout('i18n', 'Using path for gettext: ' + i18n_path, 1, 0)
try:
t = gettext.translation('ubuntu-mate-welcome', localedir=i18n_path, languages=[self.locale], fallback=True)
_ = t.gettext
dbg.stdout('i18n', 'Translation found for gettext.', 1, 2)
except:
dbg.stdout('i18n', 'No translation exists for gettext. Using default.', 1, 2)
t = gettext.translation('ubuntu-mate-welcome', localedir='/usr/share/locale/', fallback=True)
_ = t.gettext
class Strings(object):
""" Not all strings are stored here, but those common throughout the program. """
def __init__(self):
## To avoid needing to call i18n each time,
## variables are intentional to be strings.
# General
self.close = str(_("Close"))
self.cancel = str(_("Cancel"))
# Desktop launchers (not used by application - just translation scripts)
self.welcome = str(_("Welcome"))
self.welcome_comment = _("Start here with helpful resources and utilities")
self.boutique = str(_("Software Boutique"))
self.boutique_comment = _("Discover software from a curated collection that complements Ubuntu MATE")
# Boutique Footer
self.subscribed = str(_("Set to retrieve the latest software listings."))
self.subscribe_link = str(_("Retrieve the latest software listings."))
self.subscribing = str(_("Please wait while the application is being updated..."))
self.version = str(_("Version:"))
# Application Listings
self.upgraded = str(_("This application is set to receive the latest updates."))
self.alternate_to = str(_('Alternative to:'))
self.hide = str(_("Hide"))
self.show = str(_("Details"))
self.install = str(_("Install"))
self.reinstall = str(_("Reinstall"))
self.remove = str(_("Remove"))
self.upgrade = str(_("Upgrade"))
self.launch = str(_("Launch"))
self.license = str(_("License"))
self.platform = str(_("Platform"))
self.category = str(_("Category"))
self.website = str(_("Website"))
self.screenshot = str(_("Screenshot"))
self.source = str(_("Source"))
self.repo_main = str(_("Ubuntu Repository"))
self.repo_universe = str(_("Ubuntu Community Maintained Repository"))
self.repo_restricted = str(_("Ubuntu Proprietary Drivers Repository"))
self.repo_multiverse = str(_("Ubuntu Non-Free Repository"))
self.repo_partner = str(_("Canonical Partner Repository"))
self.unknown = str(_('Unknown'))
self.undo = str(_("Undo Changes"))
# Repository Listings
self.repo_unknown = str(_("External Repository"))
self.head_software = str(_("Software"))
self.head_source = str(_("Source"))
self.third_party_warning = str(_("This software isn't supported by Ubuntu, and requires trusting third party repositories to install."))
# Applying Changes
self.install_text = str(_("Installing..."))
self.remove_text = str(_("Removing..."))
self.upgrade_text = str(_("Upgrading..."))
# Categories
self.accessories = str(_("Accessories"))
self.education = str(_("Education"))
self.games = str(_("Games"))
self.graphics = str(_("Graphics"))
self.internet = str(_("Internet"))
self.office = str(_("Office"))
self.programming = str(_("Programming"))
self.media = str(_("Sound & Video"))
self.systools = str(_("System Tools"))
self.univaccess = str(_("Universal Access"))
self.servers = str(_("Server One-Click Installation"))
self.misc = str(_("Miscellaneous"))
# Boutique Features
self.search = str(_("Search"))
self.search_begin = str(_("Please enter a keyword to begin."))
self.search_short = str(_("Please enter at least 3 characters."))
# Boutique News
self.added = str(_("Added"))
self.fixed = str(_("Fixed"))
self.removed = str(_("Removed"))
# Boutique Queue
self.queue_install = str(_("Queued for installation."))
self.queue_remove = str(_("Queued for removal."))
self.queue_prepare_remove = str(_("Preparing to remove:"))
self.queue_prepare_install = str(_("Preparing to install:"))
self.queue_removing = str(_("Removing:"))
self.queue_installing = str(_("Installing:"))
self.updating_cache = str(_("Updating cache..."))
self.verifying_changes = str(_("Verifying software changes..."))
self.install_success = str(_("Successfully Installed"))
self.install_fail = str(_("Failed to Install"))
self.remove_success = str(_("Successfully Removed"))
self.remove_fail = str(_("Failed to Remove"))
self.status_install = str(_("To be installed"))
self.status_remove = str(_("To be removed"))
##################################
# WebKit + Python Communications
##################################
class AppView(WebKit2.WebView):
def __init__(self):
# WebKit2 Initalisation
webkit = WebKit2
webkit.WebView.__init__(self)
# Set WebKit background to the same as GTK
self.set_background_color(Gdk.RGBA(0, 0, 0, 0))
# Connect signals to application
self.connect('load-changed', self._load_changed_cb)
self.connect('notify::title', self._title_changed_cb)
self.connect('context-menu', self._context_menu_cb)
# Enable keyboard navigation
self.get_settings().set_enable_spatial_navigation(True)
self.get_settings().set_enable_caret_browsing(True)
# Show console messages in stdout if we're debugging.
if dbg.verbose_level == 2:
self.get_settings().set_enable_write_console_messages_to_stdout(True)
# Set up zoom to match rest of system font
self.set_zoom_level(systemstate.zoom_level)
dbg.stdout('Welcome', 'Setting zoom level to: ' + str(systemstate.zoom_level), 1, 0)
# Perform a smooth transition for footer icons.
self.do_smooth_footer = False
def refresh_gtk_colors(self):
"""
Updates the CSS on the page to use the colours from GTK.
"""
window = Gtk.Window()
style_context = window.get_style_context()
def _rgba_to_hex(color):
"""
Return hexadecimal string for :class:`Gdk.RGBA` `color`.
"""
return "#{0:02x}{1:02x}{2:02x}".format(
int(color.red * 255),
int(color.green * 255),
int(color.blue * 255))
def hex_to_rgb(hex_string):
hex_string = hex_string.lstrip("#")
return list(int(hex_string[i:i+2], 16) for i in (0, 2 ,4))
def _get_color(style_context, preferred_color, fallback_color):
color = _rgba_to_hex(style_context.lookup_color(preferred_color)[1])
if color == "#000000":
color = _rgba_to_hex(style_context.lookup_color(fallback_color)[1])
return color
def _get_hex_variant(string, offset):
"""
Converts hex input #RRGGBB to RGB and HLS to increase lightness independently
"""
string = string.lstrip("#")
rgb = list(int(string[i:i+2], 16) for i in (0, 2 ,4))
# colorsys module converts to HLS to brighten/darken
hls = colorsys.rgb_to_hls(rgb[0], rgb[1], rgb[2])
newbright = hls[1] + offset
newbright = min([255, max([0, newbright])])
hls = (hls[0], newbright, hls[2])
# Re-convert to rgb and hex
newrgb = colorsys.hls_to_rgb(hls[0], hls[1], hls[2])
def _validate(value):
value = int(value)
if value > 255:
return 255
elif value < 0:
return 0
return value
newrgb = [_validate(newrgb[0]), _validate(newrgb[1]), _validate(newrgb[2])]
newhex = '#%02x%02x%02x' % (newrgb[0], newrgb[1], newrgb[2])
return newhex
bg_color = _get_color(style_context, "base_color", "theme_bg_color")
text_color = _get_color(style_context, "fg_color", "theme_fg_color")
section_bg_color = _get_color(style_context, "dark_bg_color", "theme_bg_color")
section_text_color = _get_color(style_context, "dark_fg_color", "theme_fg_color")
selected_bg_color = _get_color(style_context, "selected_bg_color", "theme_selected_bg_color")
selected_text_color = _get_color(style_context, "selected_fg_color", "theme_selected_fg_color")
button_bg_color = _get_color(style_context, "button_bg_color", "theme_bg_color")
button_text_color = _get_color(style_context, "text_color", "theme_fg_color")
css = []
css.append("--bg: " + bg_color)
css.append("--bg-alt: " + _get_hex_variant(bg_color, -10))
css.append("--text: " + text_color)
css.append("--section_bg: " + section_bg_color)
css.append("--section_text: " + section_text_color)
css.append("--selected_bg: " + selected_bg_color)
css.append("--selected_text: " + selected_text_color)
css.append("--button_bg: linear-gradient(to bottom, {0}, {1})".format(
_get_hex_variant(button_bg_color, 8),
_get_hex_variant(button_bg_color, -8)))
css.append("--selected_button_bg: linear-gradient(to bottom, {0}, {1})".format(
_get_hex_variant(selected_bg_color, 8),
_get_hex_variant(selected_bg_color, -8)))
css.append("--button_text: " + button_text_color)
app.update_page("body", "append", "<style>:root {" + ";".join(css) + "}</style>")