This repository has been archived by the owner on Jun 30, 2019. It is now read-only.
forked from UbuntuBudgie/budgie-welcome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbudgie-welcome
executable file
·2021 lines (1643 loc) · 78.8 KB
/
budgie-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 2016 Ubuntu Mate
# Copyright 2016-2019 Ubuntu Budgie Developers
#
# budgie-welcome is free software: you can redistribute it and/or modify
# it under the temms 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 Budgie 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 Budgie welcome. If not, see <http://www.gnu.org/licenses/>.
#
""" Welcome App for Ubuntu Budgie and budgie-remix """
import gi
gi.require_version('WebKit2', '4.0')
import inspect
import os
import signal
import subprocess
import sys
import urllib.request
import urllib.error
import webbrowser
import socket
import json
import shutil
import locale
import gettext
import getpass
try:
import distro
except:
import platform
from gi.repository import WebKit2, Gtk, Gio, Gdk, GLib
from threading import Thread
from queue import Queue, Empty
from notify2 import Notification, init as NotifyInit
import apt
import re
# global variable - path inc the suffix / of where the app is being executed
start_location = "./" # path defined on app startup
win = None
class AppView(WebKit2.WebView):
def __init__(self):
WebKit2.WebView.__init__(self)
self.connect('load-changed', self._load_changed_cb)
self.connect('notify::title', self._title_changed_cb)
self.connect('context-menu', self._context_menu_cb)
self.l_uri = None
self.status_btn = None
self.back_btn = None
self.page_title = None
# self.set_zoom_level(0.90)
self.back_signal_handler = None
def _back_action(self, data):
app.run_javascript("smoothPageFade('index.html')")
def _index_action(self, data):
app.run_javascript("backAction()")
def _push_config(self):
# TODO: push notification should be connected to angularjs and use a
# broadcast event any suitable controllers will be able to listen and
# respond accordingly, for now we just use jQuery to manually toggle
current_page = app.current_page[:-5]
# Dynamically toggle header controls button
if current_page != "index":
if not self.back_btn.is_sensitive():
if current_page != "gettingstarted":
self.back_signal_handler = self.back_btn.connect("clicked", self._back_action)
else:
self.back_signal_handler = self.back_btn.connect("clicked", self._index_action)
self.back_btn.set_sensitive(True)
else:
if self.back_signal_handler:
self.back_btn.disconnect(self.back_signal_handler)
self.back_signal_handler = None
self.back_btn.set_sensitive(False)
if systemstate.session_type == 'live':
app.update_page('.live-session-only', 'show')
else:
app.update_page('.normal-session-only', 'show')
if not pm.queue.empty() or pm.active: # There is atleast one task
self.status_btn.show()
else:
self.status_btn.hide()
if systemstate.is_online:
app.run_javascript("$('.offline').hide()")
else:
app.run_javascript("$('.offline').show()")
### Getting Started Page ###
if current_page == 'gettingstarted':
if systemstate.first_run != True:
app.update_page('.first-run', 'hide')
if systemstate.codename in ['xenial']:
app.update_page('.1710', 'hide')
else:
app.update_page('.1710', 'show')
if systemstate.codename in ['xenial', 'bionic', 'cosmic']:
app.update_page('.1904', 'hide')
else:
app.update_page('.1904', 'show')
# Display information tailored to graphics vendor (Getting Started / Drivers)
app.run_javascript('var graphicsVendor = "' + systemstate.graphics_vendor + '";')
app.run_javascript('var graphicsGrep = "' + systemstate.graphics_grep + '";')
app.update_page('#boot-mode', 'html', systemstate.boot_mode)
graphics_vendor = systemstate.graphics_vendor
if graphics_vendor == 'NVIDIA':
app.update_page('.graphics-nvidia', 'fadeIn')
elif graphics_vendor == 'AMD':
app.update_page('.graphics-amd', 'fadeIn')
elif graphics_vendor == 'Intel':
app.update_page('.graphics-intel', 'fadeIn')
elif graphics_vendor == 'VirtualBox':
app.update_page('.graphics-vbox', 'fadeIn')
else:
app.update_page('.graphics-unknown', 'fadeIn')
if systemstate.arch == 'i386':
app.update_page('.64bitonly', 'hide')
### Index Page ###
if current_page == 'index':
if systemstate.autostart:
app.update_page('#autostart', 'html', '')
else:
app.update_page('#autostart', 'html', '')
app.run_javascript(
'$("#wordmark").attr("src","' + translations.res_dir + 'img/welcome/' + systemstate.distro_wordmark + '");')
if current_page == 'default':
systemstate.first_run = False
if self.back_signal_handler:
self.back_btn.disconnect(self.back_signal_handler)
self.back_signal_handler = self.back_btn.connect("clicked", self._back_action)
panel_backup = localdir + '/panel-backup.conf'
style_backup = localdir + '/style-backup.json'
if os.path.isfile(panel_backup):
app.update_page('#panel-restore', 'fadeIn')
else:
app.update_page('#panel-restore', 'hide')
if os.path.isfile(style_backup):
app.update_page('#style-undo', 'fadeIn')
else:
app.update_page('#style-undo', 'hide')
# themes are distro specific so need to hide/show as appropriate
theme = app._data_path + "/config/themes.json"
with open(theme) as file:
config = json.load(file)
if systemstate.codename in config:
for theme in config[systemstate.codename]:
app.update_page("." + theme, 'show')
if current_page in ['introduction', 'features', 'community', 'recommendations', 'gettingstarted']:
if systemstate.official:
app.update_page('.official-only', 'show')
else:
app.update_page('.unofficial-only', 'show')
if current_page in ['introduction', 'features']:
if systemstate.codename in ['bionic']:
app.update_page('.1804-only', 'show')
app.update_page('.after1810', 'hide')
else:
app.update_page('.1804-only', 'hide')
app.update_page('.after1810', 'show')
if current_page == 'recommendations':
if systemstate.codename in ['xenial']:
app.update_page('.before1804', 'show')
else:
app.update_page('.before1804', 'hide')
if current_page in [ 'recommendations', 'default', 'introduction']:
if systemstate.codename in ['xenial', 'bionic', 'cosmic']:
app.update_page('.before1904', 'show')
app.update_page('.after1904', 'hide')
else:
app.update_page('.before1904', 'hide')
app.update_page('.after1904', 'show')
if current_page == 'budgie-applets':
# applets are distro specific so need to hide/show as appropriate
package = app._data_path + "/config/packages.json"
with open(package) as file:
config = json.load(file)
for applet in config['budgie-applets']:
if systemstate.codename in config['budgie-applets'][applet]['repos']:
app.update_page("." + applet, 'show')
else:
app.update_page("." + applet, 'hide')
if systemstate.bde_version == 'NA':
app.update_page(".showhide", 'show')
else:
app.update_page(".showhide", 'hide')
### All pages with install/removal ###
if current_page in ['gettingstarted', 'default', 'recommendations', 'budgie-applets']:
app.update_page('[id$=install]', 'hide')
app.update_page('[id$=remove]', 'hide')
def checkInstallationStatus():
for code in pdata.getShortCodes(current_page):
# some package names are codename specific
# so the buttons on page needs the string
# without the codename
code = code.split("#")[0]
installed = pm.hasInstalled(current_page, code)
if installed:
app.update_page('#' + code + '-remove', 'show')
else:
app.update_page('#' + code + '-install', 'show')
if systemstate.speed:
size = pdata.get_size(current_page, code)
if size:
seconds = size / systemstate.speed
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
time = "%d:%02d:%02d" % (h, m, s)
timespan = "<div id='%s-time'>(%dMB ~ %d Hour(s) %d Minute(s))</div>" % (code, size, h, m)
app.update_page("#%s-time" % code, 'remove')
app.update_page('#' + code + '-install', 'after', timespan)
# Sort recommendations and budgie-applets
if current_page == 'recommendations':
app.run_javascript("sortList()")
# Checking on cache will take sometime. So run it on a
# separate thread.
thread = Thread(target=checkInstallationStatus)
thread.start()
app.run_javascript("$('span[name=\"distro-name\"]').html('{}')".format(systemstate.distroname))
# Apply intermediate actions, if any are present
if current_page in systemstate.intermediate_actions:
for action in systemstate.intermediate_actions[current_page]:
app.update_page(action[0], action[1], action[2], action[3])
def _load_changed_cb(self, view, frame):
uri = str(self.get_uri())
app.current_page = uri.rsplit('/', 1)[1]
self._push_config()
def _title_changed_cb(self, view, frame):
title = self.get_title()
# An empty command get executed while toggling startup
# option. Actual reason for this command execution needs
# to be investigated.
if title == '':
return
self._do_command(title)
# Clear title after executing a command. Otherwise, if the same
# command is executed with another event, it won't be identified
# as there is no effective title change. Consider links in applets
# page. Multiple links refers to budgie-extras repository.
self.run_javascript("document.title = ''")
def _context_menu_cb(self, webview, menu, event, htr, user_data=None):
# Disable context menu.
return True
def _do_command(self, uri):
if uri == 'control':
subprocess.Popen(['gnome-control-center'])
elif uri == 'update':
subprocess.Popen(['update-manager'])
elif uri == 'drivers':
subprocess.Popen(['software-properties-gtk', '--open-tab=4'])
elif uri == 'language':
subprocess.Popen(['gnome-control-center', 'region'])
elif uri == 'users':
subprocess.Popen(['gnome-control-center', 'user-accounts'])
elif uri == 'backup':
subprocess.Popen(['deja-dup-preferences'])
elif uri == 'firewall':
subprocess.Popen(['gufw'])
elif uri == 'budgie-desktop-settings':
subprocess.Popen(['budgie-desktop-settings'])
elif uri.startswith("title?"):
title = uri[6:]
self.page_title.set_label(title)
elif uri.startswith('layout?'):
layout = uri[7:]
self._apply_layout(layout)
elif uri.startswith('install?'):
code = uri[8:]
# Special case for steam, check for gnome-software
if code == 'steam' and not pm.hasInstalled(None, 'gnome-software'):
message = _("Steam is a third party package that requires user approval of EULA"
"(End User License Agreement). So we rely on GNOME Software for installing"
" steam and it is not available in your system. Please install GNOME Software"
" and try this option again")
popup = PopupMessage(message, PopupMessage.ERROR, None)
popup.showMessage()
return
if not self.checkPermissions(app.current_page[:-5], code):
return
self.managePackage(PMEntry.INSTALL, app.current_page[:-5], code)
# for skippy-xd we also need to define a keyboard shortcut
if code == 'skippy-xd':
app.define_keyboard_shortcut('skippy-xd', 'skippy-xd-toggle', '<Primary>grave')
elif uri.startswith('remove?'):
code = uri[7:]
self.managePackage(PMEntry.REMOVE, app.current_page[:-5], code)
elif uri.startswith('script?'):
code = uri[7:]
script = pdata.getScript(app.current_page[:-5], code)
root = pdata.getRootRequirement(app.current_page[:-5], code)
def run_script(script, root):
if root:
process = subprocess.Popen(
['pkexec', start_location + 'budgie-welcome-privileged-actions', "SCRIPT", filename, root])
else:
process = subprocess.Popen(['sh', script])
p = process.wait()
self._push_config()
script = app._data_path + "/scripts/" + script
run_script(script, root)
elif uri.startswith('install-os'):
if uri == 'install-os':
subprocess.Popen(['sudo', 'sh', '-c', "ubiquity gtk_ui"])
app.close()
return
elif uri.startswith('panel'):
def panelOperation():
actions = [
['.panel-apply', 'addClass', 'disabled', None],
['#panel-status', 'fadeIn', None, None]
]
for action in actions:
app.update_page(action[0], action[1], action[2], action[3])
systemstate.addIntermediateActions(app.current_page, actions)
operation = uri[6:]
p = subprocess.Popen([app._data_path + "/scripts/panel-" + operation], shell=True)
retval = p.wait()
systemstate.removeIntermediateActions(app.current_page, actions)
app.update_page('.panel-apply', 'removeClass', 'disabled')
app.update_page('#panel-status', 'fadeOut')
# There is some problem with showing notification in this module
if retval == 0:
pass
# Notifier(Notifier.INFO, "Panel " + operation + " completed successfully").show()
else:
dbg.stdout("Failed to perform panel operation", 0, 0)
# Notifier(Notifier.ERROR, "Panel " + operation + " failed").show()
self._push_config()
Thread(target=panelOperation).start()
elif uri == 'software-center':
try:
subprocess.Popen(['gnome-software'])
except Exception as e:
message = _("Seems that GNOME Software is not installed. If this problem persists "
"even after installing GNOME Software, please contact us with following "
"error message")
popup = PopupMessage(message, PopupMessage.ERROR, str(e))
popup.showMessage()
elif uri.startswith("theme?"):
code = uri[6:]
panelstyle = os.path.expanduser('~') + "/.config/gtk-3.0/gtk.css"
theme = app._data_path + "/config/" + code + "-style.json"
def applyStyle():
with open(theme) as file:
whole_config = json.load(file)
attrib = None
if systemstate.codename in whole_config:
config = whole_config[systemstate.codename]
else:
config = whole_config["default"]
for item in config:
if "panel-attrib" in item:
attrib = item["panel-attrib"]
continue
schema = item["SCHEMA"]
values = item["VALUES"]
gsettings = Gio.Settings.new(schema)
for key, value in values.items():
if type(value) == bool:
gsettings.set_boolean(key, value)
else:
gsettings.set_string(key, value)
if attrib:
self._set_panel_key('enable-shadow', attrib['enable-shadow'])
self._set_panel_key('size', attrib['size'])
self._set_panel_key('transparency', attrib['transparency'])
else:
# sane defaults
self._set_panel_key('enable-shadow', True)
self._set_panel_key('size', 37)
self._set_panel_key('transparency', None)
subprocess.Popen(['budgie-panel', '--replace', '&'])
self._push_config()
Thread(target=applyStyle).start()
elif uri == 'close':
app.close()
elif uri == 'toggle-startup':
# toggle autostart
systemstate.autostart_toggle()
self._push_config()
self.l_uri = None
# WebKit2.WebView.reload(self)
elif uri == "checkInternetConnection":
systemstate.check_internet_connection()
self._push_config()
elif uri.startswith("link?"):
webbrowser.open_new_tab(uri[5:])
elif uri == 'init-system-info':
systemstate.get_system_info(self)
elif uri == 'status':
message = _("Following tasks are in progress")
popup = PopupMessage(message, PopupMessage.STATUS, pm.getTaskList())
popup.showMessage()
elif uri == 'about':
message = "<div class=\"text-md-center\">"
message += "<strong>" + _("Budgie Welcome") + "</strong><br>"
message += "Version {}".format(
systemstate.app_version
)
message += "<br><br> " + _("Budgie Desktop") + " {}".format(
systemstate.budgie_version
)
message += "<br><br>({} {} {})".format(
systemstate.distroname,
systemstate.os_version,
systemstate.codename
)
message += "</div>"
popup = PopupMessage(message, PopupMessage.INFO)
popup.showMessage()
else:
print('Unknown command: {}'.format(uri))
def _apply_layout(self, layout):
def running_process(process):
"check if process is running. < process > is the name of the process."
proc = subprocess.Popen(
["if pgrep " + process + " >/dev/null 2>&1; then echo 'True'; else echo 'False'; fi"],
stdout=subprocess.PIPE, shell=True)
(Process_Existance, err) = proc.communicate()
return str(Process_Existance, 'utf-8') == 'True\n'
dtop = os.path.expanduser('~') + '/.config/autostart/plank.desktop'
global start_location
if layout == 'classicbudgie':
if running_process('plank'):
subprocess.Popen(['killall', 'plank'])
subprocess.Popen(['rm', dtop])
p = subprocess.Popen(['pkexec',
start_location + 'budgie-welcome-privileged-actions',
'panelini', 'classic'])
retval = p.wait()
return
if layout == 'ubuntubudgie':
if not running_process('plank'):
subprocess.Popen(['nohup', 'plank', '&'])
subprocess.Popen(['cp', '/usr/share/budgie-desktop/plank.desktop', dtop])
p = subprocess.Popen(['pkexec',
start_location + 'budgie-welcome-privileged-actions',
'panelini', 'ub'])
retval = p.wait()
return
def _set_panel_key(self, key, value):
# panel keys are relocatable - so need to loop through all panels
# and set the key to the value given
gsettings = Gio.Settings.new('com.solus-project.budgie-panel')
panels = gsettings.get_strv('panels')
for panel in panels:
gsettings = Gio.Settings.new_with_path('com.solus-project.budgie-panel.panel',
'/com/solus-project/budgie-panel/panels/{' + panel + '}/')
if type(value) == bool:
gsettings.set_boolean(key, value)
elif type(value) == int:
gsettings.set_int(key, value)
else:
gsettings.set_string(key, value)
def checkPermissions(self, fname, code):
# we check if third-party stuff is going to be installed. If it is
# we need to display a PopUp message describing what is being installed and
# getting a positive yes from the user in that they have understood the risks
installed = pm.hasInstalled(fname, code)
if installed:
return False
repos = pdata.getRepos(fname, code)
message = _("The following third-party repositories need to be added to complete the installation:")
message += "\n"
if repos:
if 'all' in repos:
checkrepos = repos['all']
else:
checkrepos = repos[systemstate.codename]
todo = False
for val in checkrepos:
if val[:3] == 'ppa':
ppa = val[4:].split('/')
filename = ppa[0] + "-ubuntu-" + ppa[1] + "-" + \
systemstate.codename + ".list"
filename = '/etc/apt/sources.list.d/' + filename
p = subprocess.Popen(['grep', '^deb\ http', filename])
retval = p.wait()
if retval != 0:
message += "\n" + val
todo = True
elif val[:3] == 'deb':
message += "\n" + val
todo = True
if todo:
message += "\n\n"
message += _(
"Third-Party repositories are not supported by Ubuntu. You should only continue if you trust the maintainers of the proposed repositories.")
message += "\n\n"
message += _("Continue with the installation?")
messagedialog = Gtk.MessageDialog(None,
Gtk.DialogFlags.MODAL,
Gtk.MessageType.WARNING,
Gtk.ButtonsType.OK_CANCEL,
_("Third-Party Repositories"))
messagedialog.format_secondary_text(message)
ret = messagedialog.run()
messagedialog.destroy()
if ret == Gtk.ResponseType.OK:
return True
return False
return True
def managePackage(self, operation, fname, code):
actions = [
['#' + code + ('-install' if operation == PMEntry.INSTALL else '-remove'), 'addClass', 'disabled', None],
['#' + code + '-status', 'fadeIn', None, None]
]
for action in actions:
app.update_page(action[0], action[1], action[2], action[3])
systemstate.addIntermediateActions(fname, actions)
pmentry = PMEntry(operation, fname, code, actions)
pm_queue.put(pmentry)
self.status_btn.show()
class Debug(object):
def __init__(self):
self.verbose_level = 0
def stdout(self, item, info, verbosity=0, colour=0):
# Only colourise output if running in a real terminal.
if sys.stdout.isatty():
end = '\033[0m'
if colour == 1: # Failure (Red)
start = '\033[91m'
elif colour == 2: # Success (Green)
start = '\033[92m'
elif colour == 3: # Action (Yellow)
start = '\033[93m'
elif colour == 4: # Debug (Blue)
start = '\033[96m'
else: # Normal/Misc (White)
start = '\033[0m'
# Ignore colours when redirected or piped.
else:
start = ''
end = ''
# Output the message depending how detailed it is.
if verbosity <= self.verbose_level:
print(start + '[' + item + '] ' + info, end)
class PopupMessage(object):
ERROR = 0
CONFIRMATION = 1
STATUS = 2
INFO = 3
def __init__(self, message, type, details=None, actions=dict(OK='removeSlowly(\'#popup-message-window\')')):
'''
message => Message to user
type => Type of message(error, confirmation ..etc)
'''
self.details = details
self.message = message
self.type = type
self.actions = actions
def showMessage(self):
# Remove message window if already exists
app.update_page('#popup-message-window', 'remove')
# Dynamically inject Popup message window
app.update_page('#wrapper', 'append', '<div id="popup-message-window">\
<div id="popup-message-container">\
</div>\
</div>')
app.update_page('#popup-message-container', 'append', '<p id="popup-message">' + \
self.message + '</p>')
if self.type == PopupMessage.ERROR and self.details:
app.update_page('#popup-message-container', 'append',
'<textarea id="details">' + self.details + '</textarea>')
elif self.type == PopupMessage.STATUS:
html_table = '<table class="table table-bordered table-condensed">'
html_table += '<thead><th>TASK</th><th>NAME</th><th>STATUS</th></thead>'
for task in self.details:
html_table += '<tr>'
html_table += '<td>{}</td><td>{}</td><td>{}</td>'.format(task[0], task[1], task[2])
html_table += '</table>'
html_table = '<div id="status-table-container">' + html_table + '</div>'
app.update_page('#popup-message-container', 'append', html_table)
elif self.type == PopupMessage.INFO:
pass # Message is already added
else:
dbg.stdout(self.type, 'message is not handled yet', 3)
buttons = ''
for action in self.actions:
buttons += '<a class="btn btn-primary" onclick="' + self.actions[
action] + ';document.title=\'\'"> ' + action + ' </a> '
app.update_page('#popup-message-container', 'append', '<div class="text-md-right">' + buttons + '</div>')
app.update_page('#popup-message-window', 'fadeIn')
class PackageManager(Thread):
def __init__(self, queue):
Thread.__init__(self)
# Don't create cache object each time instead use global cache
self.cache = cache
self.queue = queue
self.running = True
self.active = None
def __isPackageInstalled(self, package):
try:
installed = self.cache[package].is_installed
except:
installed = False
return installed
def __isSnapInstalled(self, snap):
installed = False
try:
p = subprocess.Popen(['snap', 'list', snap])
retval = p.wait()
if retval == 0:
installed = True
except:
installed = False
return installed
def hasInstalled(self, current_page, code):
if not current_page:
return self.__isPackageInstalled(code)
packages = pdata.getPackages(current_page, code)
if not packages:
# assume we are just dealing with either snaps or ppa's
repos = pdata.getRepos(current_page, code)
found = False
if repos:
# for the first element of the codename (e.g. zesty)
# repo split by the / character to get an array
# first element is the ppa organisation and second
# is the ppa name
ppa = repos[systemstate.codename][0][4:].split('/')
filename = ppa[0] + "-ubuntu-" + ppa[1] + "-" + \
systemstate.codename + ".list"
filename = '/etc/apt/sources.list.d/' + filename
p = subprocess.Popen(['grep', '^deb\ http', filename])
retval = p.wait()
if retval == 0:
found = True
else:
# if there are no repos we must be dealing with snaps
snaps = pdata.getSnap(current_page, code)
if snaps and len(snaps) > 0:
installed = True
for snap in snaps:
if not self.__isSnapInstalled(snap):
installed = False
break
return installed
return found
installed = True
for package in packages:
if not self.__isPackageInstalled(package):
installed = False
break
return installed
def run(self):
while self.running:
try:
entry = self.queue.get(timeout=1)
except Empty:
continue
self.active = entry
filename = entry.filename
code = entry.code
action = "INSTALL" if entry.task == PMEntry.INSTALL else "REMOVE"
# Steam requires GNOME Software and there is problem in running
# GNOME Software in privileged mode.
global start_location
if code == 'steam':
p = subprocess.Popen([app._data_path + 'scripts/steam'])
else:
p = subprocess.Popen(['pkexec',
start_location + 'budgie-welcome-privileged-actions',
action, filename, code, app.json_path])
retval = p.wait()
post_install = pdata.getPostInstall(filename, code)
if retval == 0 and post_install:
app.webkit._do_command("script?" + post_install)
if entry.task == PMEntry.INSTALL:
app.update_page('#' + code + '-install', 'removeClass', 'disabled')
else:
app.update_page('#' + code + '-remove', 'removeClass', 'disabled')
app.update_page('#' + code + '-status', 'fadeOut')
systemstate.removeIntermediateActions(filename, entry.actions)
action = "removal" if entry.task == PMEntry.REMOVE else "installation"
if retval == 0:
Notifier(Notifier.INFO, "Completed " + action + " of " + entry.code).show()
else:
Notifier(Notifier.ERROR, "Failed " + action + " of " + entry.code).show()
self.reload_cache()
self.active = None
app.webkit._push_config()
self.queue.task_done()
def reload_cache(self):
dbg.stdout('Apt', 'Reloading cache...', 0, 3)
self.cache.close()
self.cache = apt.Cache()
dbg.stdout('Apt', 'Cache reloaded.', 0, 2)
def getTaskList(self):
with self.queue.mutex:
task_list = list(self.queue.queue)
taskList = [["INSTALL" if self.active.task == PMEntry.INSTALL else "REMOVE", self.active.code, "ACTIVE"]]
for task in task_list:
taskList.append(["INSTALL" if task.task == PMEntry.INSTALL else "REMOVE", task.code, "PENDING"])
return taskList
def clearQueue(self):
try:
while True:
self.queue.get_nowait()
self.queue.task_done()
except Empty:
dbg.stdout('PackageMangement', 'Cleared PM Queue', 1, 0)
class Notifier(object):
INFO = 0
ERROR = 1
SUCCESS = 2
def __init__(self, type, message):
if type == self.INFO:
icon = "dialog-information"
elif type == self.ERROR:
icon = "dialog-error"
self.notification = Notification(_("Welcome App"), message, icon)
def show(self):
try:
self.notification.show()
except:
# Some error in showing notification
dbg.stdout('Notification', 'Failed to show notification', 0, 0)
class PackageData(object):
'''
Map some short codes with packages. Install/Remove buttons
will be represented by short code like #code-remove and
#code-install. This will allow one to check installation status
of each package using a loop instead of checking separately
'''
def __init__(self):
with open(app.json_path) as file:
self.data = json.load(file)
def getShortCodes(self, filename):
return self.data[filename].keys()
def getPackages(self, filename, code):
try:
full_code = code + "#" + systemstate.codename
if full_code in self.data[filename]:
return self.data[filename][full_code]["packages"]
return self.data[filename][code]["packages"]
except KeyError:
return None
def getScript(self, filename, code):
try:
full_code = code + "#" + systemstate.codename
if full_code in self.data[filename]:
return self.data[filename][full_code]["script"]
return self.data[filename][code]["script"]
except KeyError:
return None
def getRootRequirement(self, filename, code):
try:
full_code = code + "#" + systemstate.codename
if full_code in self.data[filename]:
return self.data[filename][full_code]["root"]
return self.data[filename][code]["root"]
except KeyError:
return None
def getRepos(self, filename, code):
try:
full_code = code + "#" + systemstate.codename
if full_code in self.data[filename]:
return self.data[filename][full_code]["repos"]
return self.data[filename][code]["repos"]
except KeyError:
return None
def getSnap(self, filename, code):
try:
return self.data[filename][code]["snap"]
except KeyError:
return None
def getPostInstall(self, filename, code):
try:
full_code = code + "#" + systemstate.codename
if full_code in self.data[filename]:
return self.data[filename][full_code]["post-install"]
return self.data[filename][code]["post-install"]
except KeyError:
return None
def get_size(self, filename, code):
try:
return self.data[filename][code]["size"]