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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
|
#!/usr/bin/env python2.6
# -*- encoding: UTF-8 -*-
# Copyright: David D Lowe (c) 2008-2010
#
# 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.
#
# 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, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
from __future__ import division
import sys
import gtkcrashhandler
gtkcrashhandler.initialize(app_name="Epidermis", use_apport=True)
from gtkcrashhandler import gtkcrashhandler_thread
import const
from const import logger, MY_CACHE_HOME, MY_DATA_HOME, PIGMENT_TYPES
import os, handy
import traceback
if not handy.determine_path() in sys.path:
sys.path.insert(1, handy.determine_path())
import threading
import pygtk
pygtk.require("2.0")
import gtk, gtk.glade
import gobject
if __name__ == "__main__":
gobject.threads_init()
gtk.gdk.threads_init()
import gconf
import getopt
# gtk.pygtk_version should be higher than 2.4
import subprocess
import socket
import loadrepo, managepigments
import shell
import ep_exceptions
import locale, gettext
from gettext import gettext as _
from gettext import ngettext as _n
class EpidermisApp:
# These variables are the index numbers for self.listStoreInstalled
iNAME = 0 # the name of the skin
iPIGMENT = 15 # the codename of the skin
iPIGMENT_DIR = 16 # the base directory of the pigment
# This are the index numbers for the ListStores of the TreeViews of the
# customise window
iCHOOSE_PIGMENT = 1
iCHOOSE_NAME = 2
# This is the codename of the customised skin, placed in iPIGMENT
CUSTOMISED_SKIN = "//CUSTOMISED_SKIN//"
def delete_event(self, widget=None, event=None, data=None):
"""Quit the application"""
logger.debug("Window closed, exiting")
self.openWindows = []
for win in self.controls.win, self.controls.winCustomise, self.controls.winReview, self.controls.winAbout, self.controls.winApplyChoose:
if win.get_property("visible"):
self.openWindows.append(win)
win.hide()
def open_windows_again():
for win in self.openWindows:
win.show_all()
client = gconf.client_get_default()
if self.undoClosedWindowEnabled:
undo = UndoCloseWindow(lambda: open_windows_again())
return True
else:
print "Epidermis closed"
sys.exit(0)
return False
def __init__(self):
"""Init the EpidermisApp application including the GUI"""
handy.require_main_thread()
# Load the glade file
self.wTreeFileName = handy.get_data_file("epidermis.glade")
self.wTree = gtk.glade.XML(self.wTreeFileName)
# Get the controls
class ControlsClass:
pass
self.controls = ControlsClass()
self.controls.win = self.wTree.get_widget("winEpidermisChooser")
self.controls.winCustomise = self.wTree.get_widget("winEpidermisCustomise")
self.controls.winApplyChoose = self.wTree.get_widget("winEpidermisApplyChoose")
self.controls.winReview = self.wTree.get_widget("winPigmentsReview")
self.controls.winAbout = self.wTree.get_widget("winAbout")
controls = self.controls
widgetNames = ("tgInstalled","tgFindMore","tgSettings","tvThemes","btApplySkin", \
"btCustomiseSkin", "notebook", "entryRepoURL","chkUndoClosedWindowEnabled", "btInstallPigments", \
"btSaveAs", "btDeleteSkin", "btOpenPigment", "entrySkinSearch", "btSkinSearch", "btDialogApplySkin", \
"btDialogApplySkinClose", "btAbout", "btLaunchCreator", "btCustomiseRevert", "treeviewReview", "labelReview",
"btPigmentReviewForward", "btPigmentReviewCancel", "btHelp","notebookThemes")
# the following few lines are added because pychecker doesn't understand setattr
noneList = []
for name in widgetNames:
noneList.append(None)
noneTuple = tuple(noneList)
(controls.notebookThemes,controls.tgInstalled,controls.tgFindMore,controls.tgSettings,controls.tvThemes,controls.btApplySkin,controls.btCustomiseSkin,controls.notebook,controls.entryRepoURL,controls.chkUndoClosedWindowEnabled, controls.btInstallPigments,controls.btSaveAs,controls.btDeleteSkin,controls.btOpenPigment,controls.entrySkinSearch,controls.btSkinSearch,controls.btDialogApplySkin,controls.btDialogApplySkinClose,controls.btAbout,controls.btLaunchCreator,controls.btCustomiseRevert,controls.treeviewReview, controls.labelReview,controls.btPigmentReviewForward,controls.btPigmentReviewCancel, controls.btHelp) = noneTuple
for widgetName in widgetNames:
# This is equivelent to (replace widgetName with its contets)
# self.widgetName = self.wTree.get_widget("widgetName")
setattr(controls,widgetName, self.wTree.get_widget(widgetName))
# Currently selected view is 'installed' by default
controls.tgActive = controls.tgInstalled
btClose = self.wTree.get_widget("btCustomiseClose")
# Connect to the events and signals
controls.win.connect("delete-event", self.delete_event, None)
def hide_delete_event(widget, event=None):
widget.hide()
return True
controls.winApplyChoose.connect("delete-event", hide_delete_event)
controls.winCustomise.connect("delete-event", hide_delete_event)
controls.winAbout.connect("response", lambda d, r: d.hide())
for widgetName in ("tgInstalled", "tgFindMore", "tgSettings"):
getattr(self.controls,widgetName).connect("pressed", self.toggled_callback)
controls.tvThemes.connect("cursor_changed", self.skin_selected)
controls.btApplySkin.connect("clicked", self.apply_skin_callback)
controls.btSaveAs.connect("clicked", self.save_skin_as_callback)
controls.btOpenPigment.connect("clicked", self.open_pigment_callback)
controls.btDeleteSkin.connect("clicked", self.delete_skin_callback)
controls.btCustomiseSkin.connect("clicked", self.btCustomiseSkin_callback)
controls.btSkinSearch.connect("clicked", self.skin_search_callback)
controls.entrySkinSearch.connect("activate", self.skin_search_callback)
controls.entrySkinSearch.connect("changed", self.skin_search_callback)
#controls.entryRepoURL.connect("changed", self.entryRepoURL_callback) # disabled, enabled later
controls.btInstallPigments.connect("clicked",self.btInstallPigments_callback)
btClose.connect("clicked", lambda a1, a2=None: self.controls.winCustomise.hide())
controls.btCustomiseRevert.connect("clicked", self.customise_revert_callback)
controls.btCustomiseRevert.set_sensitive(False)
controls.btSaveAs.set_sensitive(False)
controls.btDeleteSkin.set_sensitive(False)
controls.btDialogApplySkin.connect("clicked", self.btDialogApplySkin_callback)
controls.btDialogApplySkinClose.connect("clicked", lambda a1: self.controls.winApplyChoose.hide())
controls.btAbout.connect("clicked", self.btAbout_callback)
controls.btHelp.connect("clicked", self.btHelp_callback)
controls.btLaunchCreator.connect("clicked", self.btLaunchCreator_callback)
controls.btPigmentReviewForward.connect("clicked", self.btPigmentReviewForward_callback)
controls.btPigmentReviewCancel.connect("clicked", lambda widget: self.controls.winReview.hide())
# Connect to controls.winCustomise's widgets and connect them:
for info in ("Name", "KeyWords", "PrimaryColours", "SecondaryColours"):
widg = self.wTree.get_widget("entryCustomise" + info)
widg.connect("changed", lambda a1, a2=None, info=info: self.customise_changed_callback(a1,info))
widgDescription = self.wTree.get_widget("textviewCustomiseDescription")
widgDescription.get_buffer().set_modified(False)
# TODO: FIXME: this seems to have no effect, file bug?
widgDescription.get_buffer().set_modified(False)
widgDescription.get_buffer().connect("modified-changed", lambda dummy: self.customise_changed_callback(dummy,"Description"))
self.isCustomiseRefreshing = False
# Create a new ListStore for installed skins: the columns, plus the identifier and the pigment dir at the end
# str, 9 Pixbuf, 6 str
self.listStoreInstalled = gtk.ListStore(str, gtk.gdk.Pixbuf, \
gtk.gdk.Pixbuf, gtk.gdk.Pixbuf, gtk.gdk.Pixbuf, gtk.gdk.Pixbuf, \
gtk.gdk.Pixbuf, gtk.gdk.Pixbuf, gtk.gdk.Pixbuf, gtk.gdk.Pixbuf, \
str, str, str, str, str, str, str)
# Create self.displayedSkins list, should always correspond to self.listStoreInstalled
self.displayedSkins = []
# Create the corresponding TreeModelFilter
self.listFilterInstalled = self.listStoreInstalled.filter_new()
self.searchString = ""
self.listFilterInstalled.set_visible_func(self.filter_matched)
# Attach the ListStore to the TreeView
controls.tvThemes.set_model(self.listFilterInstalled)
# create the TreeViewColumn to display the data in the installed tab
# we don't have a pigment column, nor a description colum
# despite that information being saved in self.listStoreInstalled
columnNames = (_("Name"), _("Wallpaper"), _("Metacity"), _("GTK"), _("Icons"), _("Splash"), \
_("Cursors"), _("Grub"), _("GDM"), _("Xsplash"), _("Primary Colors"), _("Secondary Colors"), \
_("Key Words"), _("Version"))
tvColumns = []
# initialise the columns
for columnName in columnNames:
tvColumns.append(gtk.TreeViewColumn(columnName))
aa = tvColumns[-1]
aa.set_resizable(True)
aa.set_min_width(10)
controls.tvThemes.append_column(aa)
# create CellRendererTexts and CellRendererPixbufs to render the data
# in the tvColumns
self.cells = []
self.cells.append(gtk.CellRendererText())
tvColumns[0].pack_start(self.cells[0], True)
tvColumns[0].add_attribute(self.cells[0], 'text', 0)
for aa in xrange(9): # pictures
self.cells.append(gtk.CellRendererPixbuf())
tvColumns[aa + 1].pack_start(self.cells[aa + 1], True)
tvColumns[aa + 1].add_attribute(self.cells[aa + 1], 'pixbuf', aa + 1)
for aa in xrange(4): # strings, remember: no pigment column!
self.cells.append(gtk.CellRendererText())
tvColumns[aa + 10].pack_start(self.cells[aa + 10], True)
tvColumns[aa + 10].add_attribute(self.cells[aa + 10], 'text', aa + 10)
# create some directories
subprocess.call(["mkdir", "-p", MY_CACHE_HOME])
# set program class (useful for some window managers like compiz)
gtk.gdk.set_program_class("Epidermis")
# gconf preferences
client = gconf.client_get_default()
# if Epidermis' gconf directory does not exist, set default gconf settings:
if not client.dir_exists("/apps/epidermis"):
client.set_string("/apps/epidermis/repo_url", "http://download.tuxfamily.org/epidermis/ghns/downloads.xml")
client.set_string("/apps/epidermis/repo_last_modified","")
client.set_string("/apps/epidermis/repo_etag","")
client.set_string("/apps/epidermis/providers_url", "http://download.tuxfamily.org/epidermis/ghns/providers.xml")
client.set_bool("/apps/epidermis/undo_closed_window_enabled", True)
# get gconf settings
self.repoURL = client.get_string("/apps/epidermis/repo_url")
if self.repoURL is None:
self.repoURL = "http://download.tuxfamily.org/epidermis/ghns/downloads.xml"
self.providersURL = client.get_string("/apps/epidermis/providers_url")
if self.providersURL is None:
self.providersURL = "http://download.tuxfamily.org/epidermis/ghns/providers.xml"
controls.entryRepoURL.set_text(self.repoURL)
self.repoLastModified = client.get_string("/apps/epidermis/repo_last_modified")
self.repoETag = client.get_string("/apps/epidermis/repo_etag")
if self.repoLastModified is None: self.repoLastModified = ""
if self.repoETag is None: self.repoETag = ""
self.undoClosedWindowEnabled = client.get_bool("/apps/epidermis/undo_closed_window_enabled")
if self.undoClosedWindowEnabled is None: self.undoClosedWindowEnabled = True
controls.chkUndoClosedWindowEnabled.set_active(self.undoClosedWindowEnabled)
# connected here after setting the text to the gconf entry
controls.entryRepoURL.connect("changed", self.entryRepoURL_callback)
controls.chkUndoClosedWindowEnabled.connect("clicked", self.chkUndoClosedWindowEnabled_callback)
# make blank MY_DATA_HOME /epidermis/PIGMENT_TYPE
for pt in PIGMENT_TYPES:
pdir = managepigments.get_pigment_type(pt)().directoryName
if not os.path.exists(os.path.join(const.DATA_HOME, "epidermis", pdir)):
subprocess.call(["mkdir", "--parents", os.path.join(MY_DATA_HOME, pdir)])
# if cache is empty, unset cache gconf keys
if not os.path.exists(os.path.join(const.MY_CACHE_HOME,"preview_summary.xml")):
client.set_string("/apps/epidermis/repo_etag","")
client.set_string("/apps/epidermis/repo_last_modified","")
self.repoLastModified, self.repoETag = "",""
# Initialize other variables
self.isApplying = False
self.repoLoaded = False
self.checkOnlineRepo = True
import pigments.skin
self.currentSkin = pigments.skin.Skin()
self.customisedSkin = None
self.pigmentsData = {}
self.pigmentsToInstall = {}
self.originalPigmentsListStore = {}
self.runningManagePigments = 0
self.installedPigments = {}
for pt in PIGMENT_TYPES:
self.installedPigments[pt] = []
self.translatorCredits = _("translator-credits")
# Load the skins
self.find_and_load_installed_pigments()
self.add_skins()
# Initialize socket timeout
socket.timeout = 30
# Show the window
self.controls.win.show_all()
#self.notebook.set_show_tabs(False)
# end EpidermisApp.__init__
#---Main view: ---#00ue00#ueFFFF---------------------------------
def append_skin_to_listStore(self, skin, prepend=False):
"""Add the skin object's information to listStoreInstalled for controls.tvThemes.
Use this function instead of adding skins manually. This allows
the listStoreInstalled format to be changed more flexibally.
Use the iNAME, iPIGMENT and iPIGMENT_DIR to retrieve information from the listStore
Note: Automatically shows CUSTOM: for custom skins
"""
if prepend:
funcListStore = self.listStoreInstalled.prepend
funcSkin = lambda a1:self.displayedSkins.insert(0, a1)
else:
funcListStore = self.listStoreInstalled.append
funcSkin = self.displayedSkins.append
if skin.installationDirectory is None or skin.installationDirectory == "":
pigmentDir = MY_DATA_HOME
else:
pigmentDir = skin.installationDirectory
if skin.codeName == self.CUSTOMISED_SKIN:
name = _(const.CUSTOM) + skin.get_human_name()
else:
name = skin.get_human_name()
def get_picture(picture):
"""Returns picture pixbuf for preview, will use error icon if picture
is None"""
if picture is None:
return self.controls.win.render_icon(gtk.STOCK_DIALOG_ERROR, gtk.ICON_SIZE_BUTTON)
else:
return picture
newListStore = [name]
for pt in const.PIGMENT_TYPES[1:]:
if skin.linkedPigments.has_key(pt):
newListStore.append(get_picture(skin.linkedPigments[pt].preview))
else:
newListStore.append(self.controls.win.render_icon(gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_BUTTON))
newListStore.extend([skin.get_words(skin.primaryColours),
skin.get_words(skin.secondaryColours),
skin.get_words(skin.keyWords),
skin.version,
skin.get_description(),
skin.codeName,
pigmentDir])
funcListStore(newListStore)
funcSkin(skin)
def modify_skin_in_listStore(self, skin, index):
"""Modify skin object's information in listStoreInstalled for
controls.tvThemes.
Use this function instead of modifying listStoreInstalled
manually. This allows the ListStore format to be changed more
flexibally.
Use the iPIGMENT, iNAME and iPIGMENT_DIR to retrieve information
from the listStoreInstalled
Note: Automatically shows CUSTOM: for custom skins
"""
if skin.installationDirectory is None or skin.installationDirectory == "":
pigmentDir = MY_DATA_HOME
else:
pigmentDir = skin.installationDirectory
if skin.codeName == self.CUSTOMISED_SKIN:
name = _(const.CUSTOM) + skin.get_human_name()
else:
name = skin.get_human_name()
def get_picture(picture):
"""Returns picture pixbuf for preview, will use error icon if picture
is None"""
if picture is None:
return self.controls.win.render_icon(gtk.STOCK_DIALOG_ERROR, gtk.ICON_SIZE_BUTTON)
else:
return picture
newListStore = [name]
for pt in const.PIGMENT_TYPES[1:]:
if skin.linkedPigments.has_key(pt):
newListStore.append(get_picture(skin.linkedPigments[pt].preview))
else:
newListStore.append(self.controls.win.render_icon(gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_BUTTON))
newListStore.extend([skin.get_words(skin.primaryColours),
skin.get_words(skin.secondaryColours), skin.get_words(skin.keyWords),
skin.version, skin.get_description(), skin.codeName,
pigmentDir])
self.listStoreInstalled[index] = newListStore
self.displayedSkins[index] = skin
def remove_skin_in_listStore(self, index):
"""Remove skin from self.listStoreInstalled for controls.tvThemes
Keyword arguments:
index -- index of self.listStoreInstalled
"""
self.listStoreInstalled.remove(self.listStoreInstalled.get_iter(index))
self.displayedSkins.pop(index)
def get_skin_from_listStore(self, iterr):
"""Get Skin object corresponding to self.controls.tvThemes.get_model()'s iterr
Keyword arguments:
iterr -- iter from self.controls.tvThemes.get_model()
"""
if self.controls.tvThemes.get_model().get_path(iterr) is None:
print >> sys.stderr, "self.listStoreInstalled.get_path(iterr) in get_skin_from_listStore returned None"
return None
return self.displayedSkins[self.controls.tvThemes.get_model().get_path(iterr)[0]]
def add_skins(self):
"""Add the skins found in self.installedPigments["skin"] to self.listStoreInstalled
and so display them.
listStoreInstalled and displayedSkins will be cleared first.
If no skins are installed, displays second page of notebookThemes
"""
self.listStoreInstalled.clear()
self.displayedSkins = []
for skin in self.installedPigments["skin"]:
self.append_skin_to_listStore(skin)
self.skin_selected(self.controls.tvThemes)
if len(self.installedPigments["skin"]) > 0:
self.controls.notebookThemes.set_current_page(0)
else:
self.controls.notebookThemes.set_current_page(1)
def find_and_load_installed_pigments(self):
"""Fill self.installedPigments and load the information into the
treeviewChoose widgets of self.winCustomise
It doesn't fill self.listStoreInstalled however, you should
use self.add_skins for that.
"""
handy.require_main_thread()
self.installedPigments = {}
self.installedPigments = {"skin":[]}
allInstalledPigments = []
upgradePigmentMore = -1 # -1 means uninitalized
removePigmentDirs = [] # list of the directories of corrupted pigments
crIns = {}
shll = None
for pt in PIGMENT_TYPES[1:]:
self.installedPigments[pt] = []
self.installedPigments[pt], excps = managepigments.find_pigments(pt, \
[MY_DATA_HOME, const.SHARED_PIGMENT_DIR])
for exc in excps:
print >> sys.stderr, "Exception loading pigment in epidermis.EpidermisApp.find_and_load_installed_pigments:"
if isinstance(exc[1], ep_exceptions.FileNotFoundException):
self.show_error(_("Error loading pigment"), _("Pigment type: %(pt)s, pigment file: %(pf)s") % \
{"pt":pt, "pf":exc[1].filename}, parent=None)
removePigmentDirs.append(exc[3])
elif isinstance(exc[1], ep_exceptions.PigmentMoreOldFormat) and upgradePigmentMore == -1:
res = self.questionbox(_("One or more pigments are saved in a deprecated format. An upgrade is required. Upgrade now?"))
if res == gtk.RESPONSE_YES:
if shll is None:
shll = shell.RootShell()
shll.prepare()
print "Upgrading pigment, moving attachment:", exc[1].attachment
exc[1].pigment.upgrade_from_old_format(exc[1].attachment, shell=shll)
upgradePigmentMore = 1
else:
upgradePigmentMore = 0
self.show_error(_("Error loading pigment"), _("Pigment type: %(pt)s, pigment dir: %(pd)s") % \
{"pt":pt, "pd":exc[3]}, parent=None)
elif isinstance(exc[1], ep_exceptions.PigmentMoreOldFormat) and upgradePigmentMore == 1:
print "Upgrading pigment, moving attachment:", exc[1].attachment
exc[1].pigment.upgrade_from_old_format(exc[1].attachment, shell=shll)
else:
self.show_error(_("Error loading pigment"), _("Pigment type: %(pt)s, pigment dir: %(pd)s") % \
{"pt":pt, "pd":exc[3]}, parent=None)
removePigmentDirs.append(exc[3])
traceback.print_exception(exc[0], exc[1], exc[2])
allInstalledPigments = allInstalledPigments + self.installedPigments[pt]
if upgradePigmentMore == 1:
shll.exit()
self.messagebox(_("Upgrade complete, restarting Epidermis."))
subprocess.Popen(["python", os.path.join(determine_path(), "epidermis.py")] + sys.argv[1:])
sys.exit()
self.installedPigments["skin"], excps = managepigments.find_skins(pigments=allInstalledPigments)
for exc in excps:
print >> sys.stderr, "Exception loading skin in epidermis.EpidermisApp.find_and_load_installed_pigments"
if isinstance(exc[1], ep_exceptions.FileNotFoundException):
self.show_error(_("Error loading skin"), _("Pigment file: %s") % exc[1].filename, parent=None)
else:
self.show_error(_("Error loading skin"), _("Pigment dir: %(pd)s") % \
{"pd":exc[3]}, parent=None)
removePigmentDirs.append(exc[3])
traceback.print_exception(exc[0], exc[1], exc[2])
if len(removePigmentDirs) > 0:
res = self.questionbox(
_n("You have a badly installed pigment on your system. Do you want to remove it?",
"You have badly installed pigments on your system. Do you want to remove them?",
len(removePigmentDirs))
)
if res == gtk.RESPONSE_YES:
if shll is None:
shll = shell.RootShell()
shll.prepare()
for dd in removePigmentDirs:
print dd
shll.do(["rm","-r",dd])
if not shll is None:
shll.exit()
for pt in PIGMENT_TYPES[1:]:
# rebuild treeviews
treeview = self.wTree.get_widget("treeviewChoose" + pt.capitalize())
# delete all previous columns
for col in treeview.get_columns():
treeview.remove_column(col)
# prepare columns
colPac = gtk.TreeViewColumn(_("Pigment"))
colIns = gtk.TreeViewColumn("*")
colNam = gtk.TreeViewColumn(_("Name"))
crPac = gtk.CellRendererText()
crIns[pt] = gtk.CellRendererToggle()
crIns[pt].connect("toggled", self.customise_toggled, pt)
crNam = gtk.CellRendererText()
crIns[pt].set_radio(True)
colPac.pack_start(crPac, True)
colPac.add_attribute(crPac, "text", self.iCHOOSE_PIGMENT)
colIns.pack_start(crIns[pt], True)
colIns.add_attribute(crIns[pt], "active", 0)
colNam.pack_start(crNam, True)
colNam.add_attribute(crNam, "text", self.iCHOOSE_NAME)
# listStore is in this format: selected, pigment, name
listStore = gtk.ListStore(gobject.TYPE_BOOLEAN,str,str)
treeview.set_model(listStore)
treeview.append_column(colIns)
treeview.append_column(colNam)
treeview.append_column(colPac)
# fill listStore
for pigm in self.installedPigments[pt]:
listStore.append([False, pigm.codeName, pigm.get_human_name()])
# add none option
listStore.append([False, "", _("None")])
# verify the validity of pigments
import pigments.pigment as pigment
for pt in PIGMENT_TYPES:
for pigm in self.installedPigments[pt]:
if not pigm.is_attachment_correct():
self.show_error(_("Pigment has an invalid attachment"),
str(pigm),
terminalText="Warning: pigment %s is_attachment_correct returned False" % str(pigm))
elif pigm.get_state() != pigment.STATE_INSTALLED:
self.show_error(_("Pigment has invalid data"),
str(pigm),
terminalText="Warning: pigment %s get_state() returned %s" % (str(pigm), pigm.debug_get_state_str()))
def skin_selected(self, widget):
"""When item in treeView is selected, the Apply, Save and Customise
buttons may be updated"""
handy.require_main_thread()
modThemes, iterr = self.controls.tvThemes.get_selection().get_selected()
if not iterr is None: # if indeed an item is selected
newSkinCodename = modThemes.get_value(iterr,self.iPIGMENT)
if not self.isApplying:
#import pigments.skin
#self.currentSkin = pigments.skin.Skin()
#self.currentSkin.codeName = newSkin
self.currentSkin = self.get_skin_from_listStore(iterr)
self.controls.btApplySkin.set_sensitive(True)
self.controls.btCustomiseSkin.set_sensitive(True)
self.controls.btDeleteSkin.set_sensitive(True)
if newSkinCodename == self.CUSTOMISED_SKIN:
self.controls.btSaveAs.set_sensitive(True)
else:
self.controls.btSaveAs.set_sensitive(False)
else:
for bt in (self.controls.btApplySkin,self.controls.btDeleteSkin,
self.controls.btSaveAs,self.controls.btCustomiseSkin):
bt.set_sensitive(False)
def skin_search_callback(self, widget):
"""called when the search text entry widget is used"""
handy.require_main_thread()
self.searchString = self.controls.entrySkinSearch.get_text()
self.listFilterInstalled.refilter()
def apply_skin_callback(self, widget, data=None):
"""Apply button callback: show controls.winApplyChoose"""
handy.require_main_thread()
if self.currentSkin.codeName != "":
self.controls.winApplyChoose.set_transient_for(self.controls.win)
doneLables = {}
for pt in PIGMENT_TYPES[1:]:
doneLables[pt] = self.wTree.get_widget("lblDone" + pt.capitalize())
doneLables[pt].set_text("")
self.wTree.get_widget("chk" + pt.capitalize()).set_sensitive(False)
for pt in self.currentSkin.linkedPigments.keys():
if pt in const.PIGMENT_TYPES[1:]:
if managepigments.get_pigment_type(pt).does_system_support_me():
self.wTree.get_widget("chk" + pt.capitalize()).set_sensitive(True)
for pt in PIGMENT_TYPES[1:]:
if not pt in self.currentSkin.linkedPigments.keys():
doneLables[pt].set_markup(_("<i>None</i>"))
if not managepigments.get_pigment_type(pt).does_system_support_me():
self.wTree.get_widget("chk" + pt.capitalize()).set_sensitive(False)
doneLables[pt].set_markup(_("<i>Unsupported</i>"))
self.controls.btDialogApplySkin.set_sensitive(len(self.currentSkin.linkedPigments) > 0)
self.controls.btDialogApplySkinClose.set_sensitive(True)
self.controls.winApplyChoose.show_all()
else:
print >> sys.stderr, "apply_skin_callback called when no skin had been selected"
def btDialogApplySkin_callback(self, widget, data=None):
"""callback for the Apply button in the Apply Skin window"""
handy.require_main_thread()
whichPigments = {}
for pt in PIGMENT_TYPES[1:]:
if self.wTree.get_widget("chk" + pt.capitalize()).get_active():
whichPigments[pt] = True
else:
whichPigments[pt] = False
self.controls.win.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
self.controls.winApplyChoose.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
self.controls.btApplySkin.set_sensitive(False)
self.controls.btDialogApplySkin.set_sensitive(False)
self.controls.btDialogApplySkinClose.set_sensitive(False)
self.controls.currentApplySkinThread = self.ApplySkinThread(self.currentSkin, self, whichPigments)
self.controls.currentApplySkinThread.start()
def open_pigment_callback(self, widget, data=None):
"""Called when user clicks Open in the main view
Open an open file dialog and installs the selected pigments
"""
handy.require_main_thread()
# Open GTK file dialog and get results
filter = gtk.FileFilter()
filter.add_pattern("*.pigment")
filter.set_name("pigments")
dd = gtk.FileChooserDialog(_("Open pigments"), None, gtk.FILE_CHOOSER_ACTION_OPEN, \
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT))
dd.add_filter(filter)
dd.set_select_multiple(True)
res = dd.run()
filenames = dd.get_filenames()
dd.destroy()
# install pigments using OpenPigmentThread
if res == gtk.RESPONSE_ACCEPT:
self.open_pigment_files(filenames)
def btPigmentReviewForward_callback(self, widget):
if self.installFilesStep == 1:
self.install_filenames()
elif self.installFilesStep == 2:
self.activate_installed()
def open_pigment_files(self, filenames):
"""Open .pigment files
Keyword arguments:
filenames -- list of filenames
"""
self.controls.labelReview.set_label(_("<b><span size=\"xx-large\">Install pigments</span></b>"))
self.controls.btPigmentReviewForward.set_label(gtk.STOCK_GO_FORWARD)
# delete all previous columns
for col in self.controls.treeviewReview.get_columns():
self.controls.treeviewReview.remove_column(col)
# prepare columns
colPac = gtk.TreeViewColumn(_("Pigment"))
colIns = gtk.TreeViewColumn("*")
colNam = gtk.TreeViewColumn(_("Name"))
colType = gtk.TreeViewColumn(_("Type"))
colPreview = gtk.TreeViewColumn(_("Preview"))
# CellRenderers
crPac = gtk.CellRendererText()
crIns = gtk.CellRendererToggle()
def review_toggled(widget, path):
"""function for checkbox in the list"""
mod = self.controls.treeviewReview.get_model()
mod[path][0] = not mod[path][0]
sens = False
if self.installFilesStep == 1:
print "lala"
for ii in self.controls.treeviewReview.get_model():
if ii[0]:
sens = True
break
self.controls.btPigmentReviewForward.set_sensitive(sens)
crIns.connect("toggled", review_toggled)
crNam = gtk.CellRendererText()
crType = gtk.CellRendererText()
crPreview = gtk.CellRendererPixbuf()
crIns.set_radio(False)
# pack CellRenderers
colPac.pack_start(crPac, True)
colPac.add_attribute(crPac, "text", 1)
colIns.pack_start(crIns, True)
colIns.add_attribute(crIns, "active", 0)
colNam.pack_start(crNam, True)
colNam.add_attribute(crNam, "text", 2)
colType.pack_start(crType, True)
colType.add_attribute(crType, "text", 3)
colPreview.pack_start(crPreview, True)
colPreview.add_attribute(crPreview, "pixbuf", 4)
# listStore is in this format: selected, pigment, name, type, preview, filename
listStore = gtk.ListStore(gobject.TYPE_BOOLEAN,str,str, str, gtk.gdk.Pixbuf, str)
self.controls.treeviewReview.set_model(listStore)
self.controls.treeviewReview.append_column(colIns)
self.controls.treeviewReview.append_column(colNam)
self.controls.treeviewReview.append_column(colPac)
self.controls.treeviewReview.append_column(colType)
self.controls.treeviewReview.append_column(colPreview)
# show window
self.controls.winReview.show_all()
# add data
import pigments
for filen in filenames:
if os.path.exists(filen):
pp = pigments.pigment.Pigment()
pp.load(filen)
listStore.append([True, pp.codeName, pp.get_human_name(), pp.type.codeName, pp.preview, filen])
else:
self.messagebox(_("Error loading file: %s") % filen)
self.installFilesStep = 1
def install_filenames(self):
installfilenames = []
for ii in self.controls.treeviewReview.get_model():
if ii[0]:
installfilenames.append(ii[5])
for ii in self.controls.treeviewReview.get_model():
if not ii[0]:
self.controls.treeviewReview.get_model().remove(ii.iter)
installfilenames = [os.path.abspath(ff) for ff in installfilenames]
operationWin = self.wTree.get_widget("winOperations")
operationWin.show_all()
self.wTree.get_widget("lblOperationsSummary").set_label(_("Installing pigments"))
self.wTree.get_widget("lblOperationsInformation").set_label(_("Loading and installing pigments"))
operationWin.set_title(_("Installing"))
thr = self.OpenPigmentThread(installfilenames, self)
thr.start()
self.controls.btPigmentReviewForward.set_sensitive(False)
self.installFilesStep = 2
def activate_installed(self):
self.controls.btPigmentReviewForward.set_sensitive(False)
self.controls.winReview.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
import shell
rootShell = shell.RootShell()
ignoredSomePigments = False
for ii in self.controls.treeviewReview.get_model():
if ii[0]:
codeName = ii[1]
pt = ii[3]
foundPigment = False
if not managepigments.get_pigment_type(pt).does_system_support_me():
ignoredSomePigments = True
continue
for pigm in self.installedPigments[pt]:
if pigm.codeName == codeName:
foundPigment = True
if pigm.does_activation_require_root():
if not rootShell.ready:
rootShell.prepare()
pigm.activate(shell=rootShell)
else:
pigm.activate()
break
if not foundPigment:
print >> sys.stderr, "Could not find", ii[1], ii[3]
if ignoredSomePigments:
self.messagebox(_("One or more pigments were not activated because they are not supported on your system"),parent=self.controls.winReview)
self.controls.btPigmentReviewForward.set_sensitive(True)
self.controls.winReview.window.set_cursor(None)
self.controls.winReview.hide()
class OpenPigmentThread(threading.Thread):
"""Thread used to install pigments using Open button in main view"""
def __init__(self, files, parent):
"""files: list of files to open
parent: the EpidermisApp"""
threading.Thread.__init__(self)
self.files = files
self.parent = parent
self.operationWin = self.parent.wTree.get_widget("winOperations")
self.progressBar = self.parent.wTree.get_widget("progressbarOperations")
self.setName("OpenPigmentThread")
@gtkcrashhandler_thread
def run(self):
handy.require_non_main_thread()
gobject.idle_add(lambda:self.parent.controls.win.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH)))
import pigments.pigment
import pigments.pack
import shell
# prepare RootShell
shll = shell.RootShell()
shll.prepare()
if not shll.ready:
raise(Exception(shell.ShellNotReadyException()))
# load and install each pigment
fileCounter = 0
for file in self.files:
gobject.idle_add(lambda:self.progressBar.set_fraction(fileCounter / len(self.files)))
pp = pigments.pigment.Pigment()
pp.load(file)
gobject.idle_add(lambda:self.progressBar.set_fraction((fileCounter + 0.5) / len(self.files)))
def progress_(progress, query=None):
gobject.idle_add(lambda:self.progressBar.set_fraction((fileCounter + 0.5 + (progress / 2)) / len(self.files)))
return False
if pp.type.codeName == "pack": # packs need special progress display
import pigments.pack
pack = pigments.pack.Pack()
pack.load(file)
pack.install(MY_DATA_HOME, shell=shll, progressCallback=progress_)
elif pp.type.codeName == "skin": # skins need special progress display and exception handling
pigm = managepigments.create_pigment("skin")
try:
pigm.load(file)
except ep_exceptions.PigmentNotFoundException, ee:
handy.show_error("Could not find linked pigment: %s of type %s" % (ee.pigment, ee.pigmentType))
raise(ee)
pigm.install(MY_DATA_HOME, shell=shll, progressCallback=progress_)
else: # all other types of pigment
pigm = managepigments.create_pigment(pp.type.codeName)
pigm.load(file)
pigm.install(MY_DATA_HOME, shell=shll)
fileCounter += 1
# finishing touches
shll.do(["chown", "-R", "%s:%s" % (const.USERNAME, const.USERNAME), MY_DATA_HOME])
shll.exit()
# Reload the installed pigments
gobject.idle_add(lambda:self.parent.find_and_load_installed_pigments())
gobject.idle_add(lambda:self.parent.add_skins())
# done
gobject.idle_add(lambda:self.parent.controls.btPigmentReviewForward.set_sensitive(True))
gobject.idle_add(lambda:self.parent.controls.labelReview.set_label(_("<b><span size=\"xx-large\">Apply pigments</span></b>")))
gobject.idle_add(lambda:self.parent.controls.btPigmentReviewForward.set_label(_("Finish")))
self.parent.controls.win.window.set_cursor(None)
gobject.idle_add(lambda:self.operationWin.hide())
def save_skin_as_callback(self, widget, data=None):
"""callback for the Save as button in the main window"""
handy.require_main_thread()
self.customisedSkin.codeName = self.customisedSkin.get_human_name().lower().replace(" ", "-")
self.customisedSkin.author = "AUTO"
self.customisedSkin.copyright = "Unknown"
subprocess.call(["mkdir", "-p", os.path.join(MY_DATA_HOME, "skins", self.customisedSkin.codeName)])
self.customisedSkin.write(os.path.join(MY_DATA_HOME, "skins", self.customisedSkin.codeName, "pigment.xml"))
self.find_and_load_installed_pigments()
self.add_skins()
def delete_skin_callback(self, widget, data=None):
"""callback for the delete button on the main view"""
handy.require_main_thread()
mod, iterr = self.controls.tvThemes.get_selection().get_selected()
if not iterr is None:
if not mod.get_value(iterr, self.iPIGMENT) == self.CUSTOMISED_SKIN:
# delete installed skin
selSkin = self.get_skin_from_listStore(iterr)
if selSkin.does_uninstallation_require_root():
import shell
shll = shell.RootShell()
shll.prepare()
selSkin.remove(shell=shll)
else:
selSkin.remove()
self.remove_skin_in_listStore(self.listStoreInstalled.get_path(mod.convert_iter_to_child_iter(iterr))[0])
import pigments.skin
self.customisedSkin = pigments.skin.Skin()
self.controls.btApplySkin.set_sensitive(False)
self.controls.btSaveAs.set_sensitive(False)
self.controls.btDeleteSkin.set_sensitive(False)
self.controls.btCustomiseSkin.set_sensitive(False)
shll.exit()
if len(self.listStoreInstalled) <= 0:
self.controls.notebookThemes.set_page(1)
class ApplySkinThread(threading.Thread):
"""The thread that is called when applying skin
This allows for the skin to be applied without freezing the GUI"""
def __init__(self, skin, parent, whichPigments=None):
"""Initialise.
Keyword argumetns:
skin -- the Skin object to be applied
parent -- the EpidermisApp instance
whichPigments -- dictionary that selects which pigments to
apply, by default, it selects all the pigments
"""
self.skin = skin
self.parent = parent
self.parent.set_isApplying(True)
self.whichPigments = whichPigments
threading.Thread.__init__(self)
self.setName("ApplySkinThread")
@gtkcrashhandler_thread
def run(self):
handy.require_non_main_thread()
#try:
self.parent.apply_skin(self.skin, self.whichPigments)
gobject.idle_add(lambda:self.parent.set_isApplying(False))
gobject.idle_add(lambda:self.parent.controls.win.window.set_cursor(None))
gobject.idle_add(lambda:self.parent.controls.winApplyChoose.window.set_cursor(None))
gobject.idle_add(lambda:self.parent.controls.btDialogApplySkinClose.set_sensitive(True))
#except Exception:
# print >> sys.stderr, "ApplySkinThread returned an error"
def apply_skin(self, skin, whichPigments=None):
"""Apply the skin for the user first, and then system-wide.
Keyword arguments:
skin -- Skin object
whichPigments -- a dictionary of the pigments to apply, the keys are
the pigment types, the values are boolean
specifying whether to activate the linked
pigment of that type
"""
handy.require_non_main_thread()
if whichPigments is None:
whichPigments = {}
def progress_callback(progress, pt):
if progress >= 1:
gobject.idle_add(lambda: self.wTree.get_widget("lblDone" + pt.capitalize()).set_text("Done"))
return False # continue working
# check if we need to a RootShell object prepared
requireRoot = False
for pt in skin.linkedPigments.keys():
if whichPigments.get(pt, False):
if skin.linkedPigments[pt].does_activation_require_root():
requireRoot = True
break
import shell
if requireRoot:
shll = shell.RootShell()
# we will run shll.prepare() later
# activate each pigment
for pt in skin.linkedPigments.keys():
if whichPigments.get(pt, False):
if skin.linkedPigments[pt].does_activation_require_root():
if not shll.ready:
shll.prepare()
if shll.ready:
skin.linkedPigments[pt].activate(progressCallback=\
lambda progress, pt=pt: progress_callback(progress, pt), \
shell=shll)
else:
logger.debug("shell could not be prepared for " + pt)
else:
skin.linkedPigments[pt].activate(progressCallback=\
lambda progress, pt=pt: progress_callback(progress, pt))
def btCustomiseSkin_callback(self, widget, data=None):
"""callback for the customise button on the main window"""
handy.require_main_thread()
self.controls.winCustomise.set_transient_for(self.controls.win)
self.controls.winCustomise.set_destroy_with_parent(True)
self.controls.winCustomise.show_all()
self.refresh_customise_window()
def refresh_customise_window(self):
"""Fill in the information in the customise window, based on the
selected entry
"""
handy.require_main_thread()
# - self.customiseOriginalSkin is a Skin object containing the original
# information of the customised skin before it was customised
# - self.selectedOriginalSkin is a Skin object containing the original
# information of the selected skin
# - self.currentSkin is the current Skin of the information displayed
# in the window
# note: the names of these skin don't contain the CUSTOM: prefix
# show basic information deduced from displayedSkins' item
self.isCustomiseRefreshing = True
mod, iterr = self.controls.tvThemes.get_selection().get_selected()
selSkin = self.get_skin_from_listStore(iterr)
widg = {}
for widgetName in ("Name", "KeyWords", "PrimaryColours", "SecondaryColours"):
widg[widgetName] = self.wTree.get_widget("entryCustomise" + widgetName)
widg["Description"] = self.wTree.get_widget("textviewCustomiseDescription")
widg["KeyWords"].set_text(selSkin.get_words(selSkin.keyWords))
widg["PrimaryColours"].set_text(selSkin.get_words(selSkin.primaryColours))
widg["SecondaryColours"].set_text(selSkin.get_words(selSkin.secondaryColours))
tb = gtk.TextBuffer()
tb.set_text(selSkin.get_description())
tb.set_modified(False)
widg["Description"].set_buffer(tb)
# widg["Name"] is set later
import pigments.skin
self.selectedOriginalSkin = pigments.skin.Skin()
self.selectedOriginalSkin.codeName = selSkin.codeName
self.selectedOriginalSkin.humanName = selSkin.humanName
self.selectedOriginalSkin.keyWords = selSkin.keyWords
self.selectedOriginalSkin.primaryColours = selSkin.primaryColours
self.selectedOriginalSkin.secondaryColours = selSkin.secondaryColours
self.selectedOriginalSkin.description = selSkin.description
self.selectedOriginalSkin.installationDirectory = selSkin.installationDirectory
# unselect all the treeview entries
for pt in PIGMENT_TYPES[1:]:
tv = self.wTree.get_widget("treeviewChoose" + pt.capitalize())
mod2 = tv.get_model()
for ii in range(mod2.iter_n_children(None)):
mod2.set_value(mod2.get_iter(ii),0, False)
tvs = {}
if mod.get_value(iterr, self.iPIGMENT) == self.CUSTOMISED_SKIN:
# selected skin is customised skin
self.selectedOriginalSkin.codeName = self.CUSTOMISED_SKIN
widg["Name"].set_text(selSkin.get_human_name())
# select correct pigment for each pigment type
for tvName in PIGMENT_TYPES[1:]:
tvs[tvName] = self.wTree.get_widget("treeviewChoose" + tvName.capitalize())
mod2 = tvs[tvName].get_model()
if self.currentSkin.linkedPigments.has_key(tvName):
pigment = self.currentSkin.linkedPigments[tvName]
# find matching entry
for ii in range(mod2.iter_n_children(None)):
if mod2.get_value(mod2.get_iter(ii), self.iCHOOSE_PIGMENT) == pigment.codeName:
mod2.set_value(mod2.get_iter(ii), 0, True)
self.selectedOriginalSkin.linkedPigments[tvName] = pigment
else:
for ii in range(mod2.iter_n_children(None)):
if mod2.get_value(mod2.get_iter(ii), self.iCHOOSE_PIGMENT) == "":
mod2.set_value(mod2.get_iter(ii), 0, True)
if self.selectedOriginalSkin.linkedPigments.has_key(tvName):
self.selectedOriginalSkin.linkedPigments.pop(tvName)
self.controls.btCustomiseRevert.set_sensitive(True)
else:
# installed skin
self.selectedOriginalSkin.codeName = selSkin.codeName
widg["Name"].set_text(selSkin.get_human_name())
#self.customisedInfo = {}
#self.customisedInfo["Description"] = mod.get_value(iterr, self.iDESCRIPTION)
tvs = {}
foundSkin = None
for skin in self.installedPigments["skin"]:
if skin.codeName == selSkin.codeName:
foundSkin = skin
break
if foundSkin is None:
raise(Exception("Could not find skin " + selSkin.codeName))
for tvName in PIGMENT_TYPES[1:]:
tvs[tvName] = self.wTree.get_widget("treeviewChoose" + tvName.capitalize())
mod2 = tvs[tvName].get_model()
if foundSkin.linkedPigments.has_key(tvName):
pigment = foundSkin.linkedPigments[tvName].codeName
for ii in range(mod2.iter_n_children(None)):
if mod2.get_value(mod2.get_iter(ii),self.iCHOOSE_PIGMENT) == pigment:
mod2.set_value(mod2.get_iter(ii),0,True)
self.selectedOriginalSkin.linkedPigments[tvName] = \
managepigments.load_pigment(foundSkin.linkedPigments[tvName].codeName, tvName)
else:
for ii in range(mod2.iter_n_children(None)):
if mod2.get_value(mod2.get_iter(ii),self.iCHOOSE_PIGMENT) == "":
mod2.set_value(mod2.get_iter(ii),0,True)
break
self.controls.btCustomiseRevert.set_sensitive(False)
self.isCustomiseRefreshing = False
# copy selectedOriginalSkin to currentSkin
self.currentSkin = pigments.skin.Skin()
self.currentSkin.codeName = self.selectedOriginalSkin.codeName
self.currentSkin.humanName = self.selectedOriginalSkin.humanName
self.currentSkin.keyWords = self.selectedOriginalSkin.keyWords
self.currentSkin.primaryColours = self.selectedOriginalSkin.primaryColours
self.currentSkin.secondaryColours = self.selectedOriginalSkin.secondaryColours
self.currentSkin.description = self.selectedOriginalSkin.description
self.currentSkin.installationDirectory = self.selectedOriginalSkin.installationDirectory
def get_is_customised(self):
"""Return whether the skin has been customised"""
handy.require_main_thread()
if self.currentSkin.codeName == self.CUSTOMISED_SKIN:
cos = self.customiseOriginalSkin
else:
cos = self.selectedOriginalSkin
for pt in PIGMENT_TYPES[1:]:
treeview = self.wTree.get_widget("treeviewChoose" + pt.capitalize())
mod = treeview.get_model()
for item in mod:
if item[0]:
if not cos.linkedPigments.has_key(pt):
if (item[self.iCHOOSE_PIGMENT] != ""):
return True
elif cos.linkedPigments[pt].codeName != item[self.iCHOOSE_PIGMENT]:
return True
for info, property in (("KeyWords", "keyWords"), ("PrimaryColours", "primaryColours"), ("SecondaryColours", "secondaryColours")):
widg = self.wTree.get_widget("entryCustomise" + info)
if widg.get_text() != cos.get_words(getattr(cos, property)):
return True
if self.wTree.get_widget("entryCustomiseName").get_text() != cos.get_human_name():
return True
widg = self.wTree.get_widget("textviewCustomiseDescription")
buff = widg.get_buffer()
if buff.get_text(buff.get_iter_at_offset(0), buff.get_iter_at_offset(buff.get_char_count())) != \
cos.get_description():
return True
return False
def customise_toggled(self, cell, path, pigmentType):
"""Callback for the treeviews of the customisation window.
Toggle the checkbox and then calls self.customise_changed_callback
"""
handy.require_main_thread()
# toggle
tv = self.wTree.get_widget("treeviewChoose" + pigmentType.capitalize())
mod = tv.get_model()
newValue = not mod[path][0]
for item in mod:
item[0] = False
mod[path][0] = newValue
# call self.customise_changed_callback
self.customise_changed_callback(tv, pigmentType)
def customise_revert_callback(self, widget, data=None):
"""callback for the Revert button of the customise window"""
handy.require_main_thread()
modThemes, iterr = self.controls.tvThemes.get_selection().get_selected()
selSkin = self.get_skin_from_listStore(iterr)
if selSkin.codeName == self.CUSTOMISED_SKIN:
# currently selected the custom skin
if self.customiseOriginalSkin.codeName != self.CUSTOMISED_SKIN:
# back to installed pigment
for ii in range(self.listStoreInstalled.iter_n_children(None)):
if self.listStoreInstalled[ii][self.iPIGMENT] == self.CUSTOMISED_SKIN:
self.remove_skin_in_listStore(ii)
break
for ii in range(self.listStoreInstalled.iter_n_children(None)):
if self.listStoreInstalled[ii][self.iPIGMENT] == self.customiseOriginalSkin.codeName:
self.controls.tvThemes.get_selection().select_path(modThemes.convert_child_path_to_path(ii))
self.controls.tvThemes.scroll_to_cell(modThemes.convert_child_path_to_path(ii))
self.refresh_customise_window()
break
self.skin_selected(self.controls.tvThemes)
#self.customisedInfo = {}
else:
print >> sys.stderr, "unexpected issue n0 from customise_revert_callback"
def customise_changed_callback(self, widget, type):
"""called whenever something changes in the customise window
This is the function that automatically addes a customised skin or
removes it
"""
handy.require_main_thread()
self.wTree.get_widget("textviewCustomiseDescription").get_buffer().set_modified(False)
# get information from the window
if self.isCustomiseRefreshing:
return
modThemes, iterr = self.controls.tvThemes.get_selection().get_selected()
selSkin = self.get_skin_from_listStore(iterr)
import pigments.skin
sk = pigments.skin.Skin()
for pt in PIGMENT_TYPES[1:]:
widg = self.wTree.get_widget("treeviewChoose" + pt.capitalize())
modd = widg.get_model()
for num in range(modd.iter_n_children(None)):
if modd[num][0] is True:
if modd[num][self.iCHOOSE_PIGMENT] == "":
if sk.linkedPigments.has_key(pt):
sk.linkedPigments.pop(pt)
else:
sk.linkedPigments[pt] = managepigments.load_pigment(modd[num][self.iCHOOSE_PIGMENT], pt)
break
for bit, property in (("PrimaryColours","primaryColours"), ("SecondaryColours", "secondaryColours")):
setattr(sk, property, self.wTree.get_widget("entryCustomise" + bit).get_text().split(", "))
sk.keyWords["en"] = self.wTree.get_widget("entryCustomiseKeyWords").get_text().split(", ")
sk.set_human_name(self.wTree.get_widget("entryCustomiseName").get_text())
buff = self.wTree.get_widget("textviewCustomiseDescription").get_buffer()
sk.set_description(buff.get_text(buff.get_iter_at_offset(0), buff.get_iter_at_offset(buff.get_char_count())))
sk.installationDircetory = self.currentSkin.installationDirectory
sk.codeName = self.currentSkin.codeName
if selSkin.codeName == self.CUSTOMISED_SKIN:
# currently selected skin is CUSTOMISED_SKIN
different = False
for func in ("get_human_name", "get_description"):
if getattr(sk, func)() != getattr(self.customiseOriginalSkin, func)():
different = True
break
for lod in ("keyWords", "primaryColours", "secondaryColours"):
if selSkin.get_words(getattr(sk, lod)) != self.customiseOriginalSkin.get_words(getattr(self.customiseOriginalSkin,lod)):
different = True
break
for pt in PIGMENT_TYPES[1:]:
if not sk.linkedPigments.has_key(pt):
if self.customiseOriginalSkin.linkedPigments.has_key(pt):
different = True
break
elif not self.customiseOriginalSkin.linkedPigments.has_key(pt):
different = True
break
elif sk.linkedPigments[pt].codeName != self.customiseOriginalSkin.linkedPigments[pt].codeName:
different = True
break
if not different:
# has been changed back to original options
# delete the custom skin
for ii in range(self.listStoreInstalled.iter_n_children(None)):
if self.listStoreInstalled[ii][self.iPIGMENT] == self.CUSTOMISED_SKIN:
#self.listStoreInstalled.remove(self.listStoreInstalled.get_iter(ii))
self.remove_skin_in_listStore(ii)
break
# select the old scheme
for ii in range(modThemes.iter_n_children(None)):
if modThemes[ii][self.iPIGMENT] == self.customiseOriginalSkin.codeName:
self.controls.tvThemes.get_selection().select_path(ii)
self.controls.tvThemes.scroll_to_cell(ii)
self.refresh_customise_window()
break
self.skin_selected(self.controls.tvThemes)
self.controls.btCustomiseRevert.set_sensitive(False)
# TODO: fix self.selectedInfo["Pigment"] = self.customiseOriginalInfo["Pigment"]
else:
# customised skin is still different from original skin
# change accordingly
pass
sk.version = "unknown"
sk.codeName = self.CUSTOMISED_SKIN
sk.installationDirectory = self.customiseOriginalSkin.installationDirectory
self.modify_skin_in_listStore(sk, modThemes.get_path(iterr)[0])
self.currentSkin.codeName = self.CUSTOMISED_SKIN
self.controls.btCustomiseRevert.set_sensitive(True)
else: # currently selected skin is an installed pigment
if self.get_is_customised():
# we need to add a new custom skin
# is there already a custom skin? remove it
for num in range(self.listStoreInstalled.iter_n_children(None)):
if self.listStoreInstalled[num][self.iPIGMENT] == self.CUSTOMISED_SKIN:
self.listStoreInstalled.remove(self.listStoreInstalled.get_iter(num))
break
# make a seperate custom skin
sk.version = "unknown"
sk.codeName = self.CUSTOMISED_SKIN
sk.installationDirectory = MY_DATA_HOME
import copy
self.customiseOriginalSkin = pigments.skin.Skin()
self.customiseOriginalSkin = copy.copy(self.selectedOriginalSkin)
self.append_skin_to_listStore(sk, prepend=True)
# select it
for num in range(self.listStoreInstalled.iter_n_children(None)):
if self.listStoreInstalled[num][self.iPIGMENT] == self.CUSTOMISED_SKIN:
self.controls.tvThemes.get_selection().select_path(modThemes.convert_child_path_to_path(num))
self.controls.tvThemes.scroll_to_cell(modThemes.convert_child_path_to_path(num))
break
self.skin_selected(self.controls.tvThemes)
self.currentSkin.codeName = self.CUSTOMISED_SKIN
# save it
self.customisedSkin = copy.copy(sk)
# enable revert button
self.controls.btCustomiseRevert.set_sensitive(True)
else:
# currently selected skin is installed and its still the same(!)
self.currentSkin.codename = self.selectedOriginalSkin.codeName
for key in const.PIGMENT_TYPES[1:]:
if sk.linkedPigments.has_key(key):
self.currentSkin.linkedPigments[key] = sk.linkedPigments[key]
elif self.currentSkin.linkedPigments.has_key(key):
self.currentSkin.linkedPigments.pop(key)
self.currentSkin.set_human_name(sk.get_human_name())
self.currentSkin.set_description(sk.get_description())
for key in ("keyWords", "primaryColours", "secondaryColours"):
setattr(self.currentSkin, key, getattr(sk, key))
def filter_matched(self, model, iterr, data=None):
"""function for TreeModelFilter"""
if len(self.listStoreInstalled) == len(self.displayedSkins):
return self.displayedSkins[model.get_path(iterr)[0]].match_filter(self.searchString)
else:
# TODO: fixme: disable this function when self.displayedSkins hasn't finished loading
return True
#---Repo management:---#00ue00#ueFFFF------------------------------------------------------
class PigmentTypeData():
"""This class would contain information about several pigments of the same type.
It possesses a ListStore, TreeViewColumns and creates CellRenderers
It used for pigment management (installation and uninstallation, repo)"""
def __init__(self, pigmentType, installed_toggled=None, treeView=None):
"""Initialise.
Keyword arguments:
pigmentType -- string of the pigmentType
installed_toggled -- function to be called when items are ticked or unticked
treeView -- the attached treeView for this data
"""
self.pigmentType = pigmentType
self.treeView = treeView
self.pigments = []
# listStore(name, pigment, copyright, description, author, preview, installed)
self.listStoreInstalled = gtk.ListStore(str, str, str, str, str, gtk.gdk.Pixbuf, gobject.TYPE_BOOLEAN)
self.columns = [gtk.TreeViewColumn(_("Installed")), gtk.TreeViewColumn(_("Preview")), gtk.TreeViewColumn(_("Name")), \
gtk.TreeViewColumn(_("Description")), gtk.TreeViewColumn(_("Copyright"))]
ct = gtk.CellRendererToggle()
ct.set_property("activatable",True)
ct.connect('toggled',self.__ct_toggled)
self.installed_toggled = installed_toggled
self.columns[0].pack_start(ct, True)
self.columns[0].add_attribute(ct, "active", 6)
pb = gtk.CellRendererPixbuf()
self.columns[1].pack_start(pb, True)
self.columns[1].add_attribute(pb, "pixbuf", 5)
self.depends = []
tt = []
jj = [0,3,2]
for xx in range(3):
tt.append(gtk.CellRendererText())
self.columns[xx + 2].pack_start(tt[xx], True)
self.columns[xx + 2].add_attribute(tt[xx], "text", jj[xx])
self.treeView.set_model(self.listStoreInstalled)
# clear columns first
for col in self.treeView.get_columns():
self.treeView.remove_column(col)
for col in self.columns:
self.treeView.append_column(col)
def get_pigmentType(self):
"""Return the pigmentType string"""
return self.pigmentType
def get_listStore(self):
"""Return the object's listStore"""
return self.listStoreInstalled
def get_columns(self):
"""Return the object's columns"""
return self.columns
def get_treeView(self):
"""Return the object's treeView"""
return self.treeView
def append_to_listStore(self, pigment, installed=False, listStore=None):
"""Append to listStore the information, if listStore is not specified,
self's listStore is used.
"""
if listStore is None:
listStore = self.listStoreInstalled
if pigment.type.codeName != self.pigmentType:
class PigmentTypeDoesNotMatch(Exception):
def __str__(self): return "Pigment Type does not match"
raise(PigmentTypeDoesNotMatch())
listStore.append([pigment.get_human_name(),
pigment.codeName, pigment.copyright, pigment.get_description(),
pigment.author, pigment.get_preview(), installed])
self.pigments.append(pigment)
def get_pigment(self, itemNumber):
"""Returns the Pigment object referenced by itemNumber"""
try:
return self.pigments[itemNumber]
except TypeError, ee:
print itemNumber
raise(ee)
def get_installed(self, itemNumber, listStore=None):
"""Return whether the Pigment object referenced by itemNumber is
installed according to this object's memory
"""
if listStore is None:
listStore = self.listStoreInstalled
item = listStore[itemNumber]
return item[6]
def modify_item(self, itemNumber, newPigment, installed=False):
handy.require_main_thread()
if newPigment.type.codeName != self.pigmentType:
class PigmentTypeDoesNotMatch(Exception):
def __str__(self): return "Pigment Type does not match"
raise(PigmentTypeDoesNotMatch())
self.listStoreInstalled[itemNumber] = [newPigment.get_human_name(),
newPigment.codeName, newPigment.copyright, newPigment.get_description(),
newPigment.author, newPigment.get_preview(), installed]
self.pigments[itemNumber] = newPigment
def modify_installed(self, itemNumber, installed, listStore=None):
if listStore is None:
listStore = self.listStoreInstalled
listStore[itemNumber][6] = installed
def get_dependancies(self,itemNumber):
"""Return dependancies in a dictionary format.
Example:
{"gdm":"codeName1", "metacity":"codeName2", ...}
"""
depends = {}
for pt in self.pigments[itemNumber].linkedPigments:
if pt in const.PIGMENT_TYPES[1:]:
depends[pt] = self.pigments[itemNumber].linkedPigments[pt].codeName
return depends
def __ct_toggled(self, cell, path):
"""Provide ticking and unticking functionality"""
self.listStoreInstalled[path][6] = not self.listStoreInstalled[path][6]
self.installed_toggled(cell,path, self.pigmentType)
return
def blank_listStore(self):
return gtk.ListStore(str, str, str, str, str, gtk.gdk.Pixbuf, gobject.TYPE_BOOLEAN)
def set_isApplying(self, isApplying):
"""Sets isApplying.
isApplying is used to stop two skins being applied at once.
"""
handy.require_main_thread()
self.isApplying = isApplying
modThemes, iterr = self.controls.tvThemes.get_selection().get_selected()
newSkinStr = modThemes.get_value(iterr, self.iPIGMENT)
if not isApplying:
if newSkinStr != self.currentSkin.codeName:
self.controls.btApplySkin.set_sensitive(True)
else:
self.controls.btApplySkin.set_sensitive(False)
def toggled_callback(self, widget, data=None):
"""Installed, Find more and Settings signals"""
handy.require_main_thread()
for t in (self.controls.tgInstalled, self.controls.tgFindMore, self.controls.tgSettings):
t.set_active(False)
if widget.get_name() == self.controls.tgInstalled.get_name():
self.controls.notebook.set_current_page(0)
elif widget.get_name() == self.controls.tgFindMore.get_name():
self.controls.notebook.set_current_page(1)
self.load_repo()
elif widget.get_name() == self.controls.tgSettings.get_name():
self.controls.notebook.set_current_page(2)
if widget.get_active():
# TODO: find out why we need a False here
widget.set_active(False)
#widget.set_active(True)
def switch_to_toggled(self, widget):
"""toggle view from code function"""
handy.require_main_thread()
for t in (self.controls.tgInstalled, self.controls.tgFindMore, self.controls.tgSettings):
if t.get_active():
t.set_active(False)
if widget.get_name() == self.controls.tgInstalled.get_name():
self.controls.notebook.set_current_page(0)
elif widget.get_name() == self.controls.tgFindMore.get_name():
self.controls.notebook.set_current_page(1)
self.load_repo()
elif widget.get_name() == self.controls.tgSettings.get_name():
self.controls.notebook.set_current_page(2)
widget.set_active(True)
self.tgActive = widget
def load_repo(self):
"""Load repo into the appropriate TreeView widgets, downloads repo
information if necessary"""
loadrepo.load_repo(self)
def btInstallPigments_callback(self, widget, data=None):
handy.require_main_thread()
if self.runningManagePigments > 0:
print "already running manage_repo_pigments"
return
# make pigmentsToInstall and pigmentsToUninstall dictionaries
pigmentsToInstall = {}
pigmentsToUninstall = {}
for pt in PIGMENT_TYPES:
pigmentsToInstall[pt] = []
pigmentsToUninstall[pt] = []
coun = 0
while coun < self.pigmentsData[pt].get_listStore().iter_n_children(None):
# compare new status with old status
newIn = self.pigmentsData[pt].get_installed(coun)
oldIn = self.pigmentsData[pt].get_installed(coun, \
listStore=self.originalPigmentsListStore[pt])
if oldIn != newIn: # status different
if not newIn: # uninstall
pigmentsToUninstall[pt].append(self.pigmentsData[pt].get_pigment(coun).codeName)
else: # install
pigmentsToInstall[pt].append(self.pigmentsData[pt].get_pigment(coun).codeName)
coun += 1
# send dictionaries to manage_repo_pigments
self.controls.btInstallPigments.set_sensitive(False)
self.manage_repo_pigments(pigmentsToInstall,pigmentsToUninstall)
def manage_repo_pigments(self,installDict,removeDict):
for pt in PIGMENT_TYPES:
if not installDict.has_key(pt):
installDict[pt] = []
if not removeDict.has_key(pt):
removeDict[pt] = []
managepigments.manage_repo_pigments(self,installDict,removeDict)
def is_pigment_installed(self, pigmentType, pigment):
"""Return whether epidermis pigment is installed"""
if os.path.exists(os.path.join(MY_DATA_HOME, get_dirname(pigmentType),pigment, "pigment.xml")):
return True
elif os.path.exists(os.path.join(const.SHARED_PIGMENT_DIR, get_dirname(pigmentType), pigment, "pigment.xml")):
return True
else:
return False
def installed_toggled(self, cell, path, pigmentType):
"""called whenever a epidermis pigment in repository browser is ticked
or unticked. It automatically ticks dependencies of newly ticked shemes,
and automatically unticks dependant skins of newly ticked epidermis pigments
"""
handy.require_main_thread()
if pigmentType == "skin":
# automatically tick any of the skin's dependancies
coun = 0
while coun < self.pigmentsData["skin"].get_listStore().iter_n_children(None):
newIn = self.pigmentsData["skin"].get_installed(coun)
oldIn = self.pigmentsData["skin"].get_installed(coun, \
listStore=self.originalPigmentsListStore["skin"])
if oldIn != newIn and newIn: # if this skin is newly to be installed
dependancies = self.pigmentsData["skin"].get_dependancies(coun)
for pt in dependancies:
for ii in range(self.pigmentsData[pt].get_listStore().iter_n_children(None)):
if self.pigmentsData[pt].get_pigment(ii).codeName == dependancies[pt]:
self.pigmentsData[pt].modify_installed(ii,True)
coun += 1
else:
# when uninstalling pigment, uninstall the skins that depend on it
coun = 0
pac = self.pigmentsData[pigmentType].get_pigment(int(path)).codeName
while coun < self.pigmentsData["skin"].get_listStore().iter_n_children(None):
if self.pigmentsData["skin"].get_dependancies(coun).has_key(pigmentType):
if self.pigmentsData["skin"].get_dependancies(coun)[pigmentType] == pac:
self.pigmentsData["skin"].modify_installed(coun, False)
coun += 1
#---Settings view:---#00ue00#ueFFFF------------------------------------------------------
def entryRepoURL_callback(self, widget, data=None):
"""entryRepoURL changed signal"""
handy.require_main_thread()
self.repoURL = self.controls.entryRepoURL.get_text()
client = gconf.client_get_default()
client.set_string("/apps/epidermis/repo_url", self.repoURL)
client.set_string("/apps/epidermis/repo_last_modified", "")
client.set_string("/apps/epidermis/repo_etag", "")
self.repoLoaded = False
def chkUndoClosedWindowEnabled_callback(self, widget, data=None):
"""chkUndoClosedWindowEnabled clicked signal"""
handy.require_main_thread()
self.undoClosedWindowEnabled = self.controls.chkUndoClosedWindowEnabled.get_active()
client = gconf.client_get_default()
client.set_bool("/apps/epidermis/undo_closed_window_enabled", self.undoClosedWindowEnabled)
def btAbout_callback(self, widget, data=None):
handy.require_main_thread()
winAbout = self.controls.winAbout
winAbout.set_version(const.VERSION + const.VERSION_TAG)
print "translator", _("translator-credits")
winAbout.set_translator_credits(_("translator-credits"))
winAbout.show_all()
def btHelp_callback(self, widget):
lc = locale.getlocale()[0]
if lc is None:
lc = "C"
if os.path.exists(os.path.join("/".join(determine_path().split("/")[:-1]), "help", lc, "epidermis-doc.xml")):
subprocess.Popen(["yelp", os.path.abspath(os.path.join("/".join(determine_path().split("/")[:-1]), "help", lc, "epidermis-doc.xml"))])
elif os.path.exists(os.path.join("/".join(determine_path().split("/")[:-1]), "help/C/epidermis-doc.xml")):
subprocess.Popen(["yelp", os.path.abspath(os.path.join("/".join(determine_path().split("/")[:-1]), "help/C/epidermis-doc.xml"))])
elif os.path.exists(os.path.join(sys.prefix, "share/gnome/help/epidermis", lc, "epidermis-doc.xml")):
subprocess.Popen(["yelp", os.path.join(sys.prefix, "share/gnome/help/epidermis", lc, "epidermis-doc.xml")])
else:
subprocess.Popen(["yelp", os.path.join(sys.prefix, "share/gnome/help/epidermis/C/epidermis-doc.xml")])
def btLaunchCreator_callback(self, widget):
creator = os.path.join(determine_path(), "creator.py")
if os.path.exists(creator):
subprocess.Popen(["python", creator])
else:
self.show_error("Cannot find Creator app", terminalText="cannot find " + creator)
#---Other:---#00ue00#ueFFFF------------------------------------------------------
def messagebox(self, text=None, type=gtk.MESSAGE_INFO, parent=None, secondaryText=""):
"""Display a modal message box with the message and blocks until user
clicks OK.
Please use this from the gtk.main thread
"""
handy.require_main_thread()
if parent is None:
dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, type, gtk.BUTTONS_OK, text)
else:
dialog = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_MODAL, \
type, gtk.BUTTONS_OK, text)
dialog.set_transient_for(parent)
dialog.set_destroy_with_parent(True)
dialog.set_title("Epidermis")
dialog.set_property("skip-taskbar-hint", False)
if not secondaryText is None:
dialog.format_secondary_text(secondaryText)
gtk.gdk.threads_enter()
dialog.run()
gtk.gdk.threads_leave()
dialog.destroy()
def questionbox(self, text, parent=None):
"""Display a modal message box with Yes/No buttons and blocks until user
clicks OK.
Please use this from the gtk.main thread
Returns response (gtk.RESPONSE_YES, gtk.RESPONSE_NO or cancel)
"""
handy.require_main_thread()
if parent is None:
dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION,
gtk.BUTTONS_YES_NO, text)
else:
dialog = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_MODAL,
gtk.BUTTONS_YES_NO, text)
dialog.set_transient_for(parent)
dialog.set_destroy_with_parent(True)
res = dialog.run()
gobject.idle_add(lambda:dialog.hide())
return res
def show_error(self, text="", secondaryText=None, terminalText=None, parent="$DEFAULTVAR$"):
"""Display an error alert box using messagebox() and print to sys.stderr"""
if parent=="$DEFAULTVAR$":
parent = self.controls.win
if terminalText is None:
terminalText = text
print >> sys.stderr, terminalText
self.messagebox(text, gtk.MESSAGE_ERROR, parent, secondaryText)
def handle_uncaught_error(self, error):
self.messagebox("Uncaught Error", gtk.MESSAGE_ERROR, self.controls.win, str(error))
class UndoCloseWindow:
"""Originally written by Laszlo Pandy.
See the following URL for more details:
http://geekdeck.wordpress.com/2009/06/13/programming-undo-adds-usability-to-our-frictionless-desktop/
"""
def __init__(self, callback):
win = gtk.Window(gtk.WINDOW_POPUP)
win.set_name ("gtk-tooltip")
win.set_decorated(False)
win.set_position(gtk.WIN_POS_NONE)
win.set_border_width(6)
win.move(-1000, -1000)
progress = gtk.ProgressBar()
progress.set_text(_("Epidermis has been closed."))
progress.set_fraction(0)
button = gtk.Button(gtk.STOCK_UNDO)
button.set_use_stock(True)
button.connect("clicked", self.on_undo_close)
button.set_flags(gtk.CAN_FOCUS | gtk.CAN_DEFAULT)
hbox = gtk.HBox()
hbox.add(progress)
hbox.add(button)
hbox.set_spacing(12)
win.add(hbox)
win.show_all()
win.connect("map-event", self.on_map)
self.win = win
self.progress = progress
self.button = button
self.callback = callback
self.cancel_quit = False
def on_map(self, widget, group_cycling):
width, height = self.win.get_size()
x = (gtk.gdk.screen_width()/2) - (width/2)
self.win.move(x, 10)
for ii in xrange(1, 4):
gobject.timeout_add_seconds(ii, lambda ii=ii: self.progress.set_fraction(ii/4))
gobject.timeout_add_seconds(4, self.on_timeline)
def on_timeline(self):
if not self.cancel_quit:
if not const.DEBUG: # as an exception, we will change the behaviour of the program based on const.DEBUG
subprocess.call(["rm", "-r", "-f", "/tmp/epidermis"])
gtk.main_quit()
sys.exit()
return False
def on_undo_close(self, widget):
self.cancel_quit = True
self.win.destroy()
self.callback()
def start(args=None):
"""Start the application"""
assert not None in (const.CACHE_HOME, const.CONFIG_HOME, const.DATA_HOME)
# i18n stuff
locale.setlocale(locale.LC_ALL, '')
logger.debug("locale.getlocale() " + str(locale.getlocale()))
if not const.INSTALLED and os.path.isdir(os.path.join(const.PAR_DIR, const.LOCALE_DIR)):
print "Using custom locale dir"
locale_dir = os.path.join(const.PAR_DIR, const.LOCALE_DIR)
else:
locale_dir = "/usr/share/locale"
for module in (gtk.glade, gettext):
module.bindtextdomain(const.APP_NAME, locale_dir)
module.textdomain(const.APP_NAME)
# to view languages on your computer, use:
# locale -a
# if you want to test, say, the canadian translation, run this:
# LANG=en_CA.utf8 python epidermis.py
# to use placeholders:
# _("We want %(first)s to be %(second)s" % {"first":"this", "second":"that"})
logger.debug("const.INSTALLED is %s" % const.INSTALLED)
logger.debug("const.PAR_DIR is %s" % const.PAR_DIR)
# legal stuff
print _("""Epidermis %s, Copyright (C) 2008-2009 David D Lowe
Epidermis comes with ABSOLUTELY NO WARRANTY; for details click on the About button, License
This is free software, and you are welcome to redistribute it
under certain conditions; for details click on the About button, License""") % const.VERSION
# gtk stuff
import webbrowser
gtk.about_dialog_set_url_hook(lambda dialog, link, data=None: webbrowser.open(link))
try:
opts, args = getopt.getopt(sys.argv[1:], "", ["creator", "debug"])
except getopt.GetoptError:
print >> sys.stderr, """The only accepted options are --creator and --debug, ignoring command-line parameters"""
opts, args = [], []
creator = None
for opt, val in opts:
if opt == '--creator': # run Creator instead of Epidermis
creator = os.path.join(determine_path(), "creator.py")
if os.path.exists(creator):
subprocess.Popen(["python", creator] + sys.argv[1:])
break
else:
print >> sys.stderr, "cannot find creator.py"
handy.show_error("Cannot find Creator app", terminalText="cannot find " + creator)
sys.exit(1)
elif opt == '--debug':
import debuginfo
print debuginfo.debuginfo()
# const.py should automatically set const.DEBUG to True
if creator is None:
app = EpidermisApp()
threading.currentThread().setName(const.GTK_LOOP_THREAD_NAME)
if len(args) > 0:
gobject.idle_add(lambda:app.open_pigment_files(args))
try:
gtk.main()
except KeyboardInterrupt:
app.delete_event()
def determine_path ():
"""Return the path of this .py file (just the directory)
Borrowed from wxglade.py"""
try:
root = __file__
if os.path.islink (root):
root = os.path.realpath (root)
return os.path.dirname (os.path.abspath (root))
except Exception, ee:
print >> sys.stderr, "I'm sorry, but something is wrong."
print >> sys.stderr, "There is no __file__ variable. Please contact the author."
sys.exit (1)
raise(ee)
def get_dirname(singular):
"""Turn nouns into the corresponding directory found in dataHome +
\"epidermis/\"
Eg: wallpaper into wallpapers, gdm into gdm"""
return managepigments.get_pigment_type(singular).directoryName
def main():
"""Launch start(sys.argv)"""
start(sys.argv)
if __name__ == "__main__":
main()
|