summaryrefslogtreecommitdiff
path: root/src/leap/bitmask/gui/mainwindow.py
blob: 6eaf2dfb6a98eb3820389140ce5f427fb7331465 (plain)
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
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
# -*- coding: utf-8 -*-
# mainwindow.py
# Copyright (C) 2013, 2014 LEAP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Main window for Bitmask.
"""
import logging
import socket

from threading import Condition
from datetime import datetime

from PySide import QtCore, QtGui
from zope.proxy import ProxyBase, setProxiedObject
from twisted.internet import reactor, threads

from leap.bitmask import __version__ as VERSION
from leap.bitmask import __version_hash__ as VERSION_HASH
from leap.bitmask.config import flags
from leap.bitmask.config.leapsettings import LeapSettings
from leap.bitmask.config.providerconfig import ProviderConfig

from leap.bitmask.gui.loggerwindow import LoggerWindow
from leap.bitmask.gui.advanced_key_management import AdvancedKeyManagement
from leap.bitmask.gui.login import LoginWidget
from leap.bitmask.gui.preferenceswindow import PreferencesWindow
from leap.bitmask.gui.eip_preferenceswindow import EIPPreferencesWindow
from leap.bitmask.gui import statemachines
from leap.bitmask.gui.eip_status import EIPStatusWidget
from leap.bitmask.gui.mail_status import MailStatusWidget
from leap.bitmask.gui.wizard import Wizard
from leap.bitmask.gui.systray import SysTray

from leap.bitmask import provider
from leap.bitmask.platform_init import IS_WIN, IS_MAC, IS_LINUX
from leap.bitmask.platform_init.initializers import init_platform

from leap.bitmask import backend

from leap.bitmask.services import get_service_display_name

from leap.bitmask.services.mail import conductor as mail_conductor

from leap.bitmask.services import EIP_SERVICE, MX_SERVICE
from leap.bitmask.services.eip import eipconfig
from leap.bitmask.services.eip import get_openvpn_management
from leap.bitmask.services.eip.connection import EIPConnection
from leap.bitmask.services.eip.vpnprocess import VPN
from leap.bitmask.services.eip.vpnprocess import OpenVPNAlreadyRunning
from leap.bitmask.services.eip.vpnprocess import AlienOpenVPNAlreadyRunning

from leap.bitmask.services.eip.vpnlauncher import VPNLauncherException
from leap.bitmask.services.eip.vpnlauncher import OpenVPNNotFoundException
from leap.bitmask.services.eip.linuxvpnlauncher import EIPNoPkexecAvailable
from leap.bitmask.services.eip.linuxvpnlauncher import \
    EIPNoPolkitAuthAgentAvailable
from leap.bitmask.services.eip.darwinvpnlauncher import EIPNoTunKextLoaded
from leap.bitmask.services.soledad.soledadbootstrapper import \
    SoledadBootstrapper

from leap.bitmask.util import make_address
from leap.bitmask.util.keyring_helpers import has_keyring
from leap.bitmask.util.leap_log_handler import LeapLogHandler

if IS_WIN:
    from leap.bitmask.platform_init.locks import WindowsLock
    from leap.bitmask.platform_init.locks import raise_window_ack

from leap.common.check import leap_assert
from leap.common.events import register
from leap.common.events import events_pb2 as proto

from leap.mail.imap.service.imap import IMAP_PORT

from ui_mainwindow import Ui_MainWindow

logger = logging.getLogger(__name__)


class MainWindow(QtGui.QMainWindow):
    """
    Main window for login and presenting status updates to the user
    """

    # StackedWidget indexes
    LOGIN_INDEX = 0
    EIP_STATUS_INDEX = 1

    # Signals
    eip_needs_login = QtCore.Signal([])
    offline_mode_bypass_login = QtCore.Signal([])
    new_updates = QtCore.Signal(object)
    raise_window = QtCore.Signal([])
    soledad_ready = QtCore.Signal([])
    mail_client_logged_in = QtCore.Signal([])
    logout = QtCore.Signal([])

    # We use this flag to detect abnormal terminations
    user_stopped_eip = False

    # We give EIP some time to come up before starting soledad anyway
    EIP_TIMEOUT = 60000  # in milliseconds

    # We give each service some time to come to a halt before forcing quit
    SERVICE_STOP_TIMEOUT = 20

    def __init__(self, quit_callback,
                 bypass_checks=False,
                 start_hidden=False):
        """
        Constructor for the client main window

        :param quit_callback: Function to be called when closing
                              the application.
        :type quit_callback: callable

        :param bypass_checks: Set to true if the app should bypass
                              first round of checks for CA
                              certificates at bootstrap
        :type bypass_checks: bool
        :param start_hidden: Set to true if the app should not show the window
                             but just the tray.
        :type start_hidden: bool
        """
        QtGui.QMainWindow.__init__(self)

        # register leap events ########################################
        register(signal=proto.UPDATER_NEW_UPDATES,
                 callback=self._new_updates_available,
                 reqcbk=lambda req, resp: None)  # make rpc call async
        register(signal=proto.RAISE_WINDOW,
                 callback=self._on_raise_window_event,
                 reqcbk=lambda req, resp: None)  # make rpc call async
        register(signal=proto.IMAP_CLIENT_LOGIN,
                 callback=self._on_mail_client_logged_in,
                 reqcbk=lambda req, resp: None)  # make rpc call async
        # end register leap events ####################################

        self._quit_callback = quit_callback
        self._updates_content = ""

        # setup UI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.menuBar().setNativeMenuBar(not IS_LINUX)
        self._backend = backend.Backend(bypass_checks)
        self._backend.start()

        self._settings = LeapSettings()

        self._login_widget = LoginWidget(
            self._settings,
            self)
        self.ui.loginLayout.addWidget(self._login_widget)

        # Qt Signal Connections #####################################
        # TODO separate logic from ui signals.

        self._login_widget.login.connect(self._login)
        self._login_widget.cancel_login.connect(self._cancel_login)
        self._login_widget.show_wizard.connect(self._launch_wizard)
        self._login_widget.logout.connect(self._logout)

        self._eip_status = EIPStatusWidget(self)
        self.ui.eipLayout.addWidget(self._eip_status)
        self._login_widget.logged_in_signal.connect(
            self._eip_status.enable_eip_start)
        self._login_widget.logged_in_signal.connect(
            self._enable_eip_start_action)

        self._mail_status = MailStatusWidget(self)
        self.ui.mailLayout.addWidget(self._mail_status)

        self._eip_connection = EIPConnection()

        # XXX this should be handled by EIP Conductor
        self._eip_connection.qtsigs.connecting_signal.connect(
            self._start_eip)
        self._eip_connection.qtsigs.disconnecting_signal.connect(
            self._stop_eip)

        self._eip_status.eip_connection_connected.connect(
            self._on_eip_connected)
        self._eip_status.eip_connection_connected.connect(
            self._maybe_run_soledad_setup_checks)
        self.offline_mode_bypass_login.connect(
            self._maybe_run_soledad_setup_checks)

        self.eip_needs_login.connect(
            self._eip_status.disable_eip_start)
        self.eip_needs_login.connect(
            self._disable_eip_start_action)

        # This is loaded only once, there's a bug when doing that more
        # than once
        # XXX HACK!! But we need it as long as we are using
        # provider_config in here
        self._provider_config = self._backend.get_provider_config()

        # Used for automatic start of EIP
        self._provisional_provider_config = ProviderConfig()
        self._eip_config = eipconfig.EIPConfig()

        self._already_started_eip = False
        self._already_started_soledad = False

        # This is created once we have a valid provider config
        self._srp_auth = None
        self._logged_user = None
        self._logged_in_offline = False

        self._backend_connected_signals = {}
        self._backend_connect()

        self._vpn = VPN()

        # connect vpn process signals
        self._vpn.qtsigs.state_changed.connect(
            self._eip_status.update_vpn_state)
        self._vpn.qtsigs.status_changed.connect(
            self._eip_status.update_vpn_status)
        self._vpn.qtsigs.process_finished.connect(
            self._eip_finished)
        self._vpn.qtsigs.network_unreachable.connect(
            self._on_eip_network_unreachable)
        self._vpn.qtsigs.process_restart_tls.connect(
            self._do_eip_restart)
        self._vpn.qtsigs.process_restart_ping.connect(
            self._do_eip_restart)

        self._soledad_bootstrapper = SoledadBootstrapper()
        self._soledad_bootstrapper.download_config.connect(
            self._soledad_intermediate_stage)
        self._soledad_bootstrapper.gen_key.connect(
            self._soledad_bootstrapped_stage)
        self._soledad_bootstrapper.local_only_ready.connect(
            self._soledad_bootstrapped_stage)
        self._soledad_bootstrapper.soledad_timeout.connect(
            self._retry_soledad_connection)
        self._soledad_bootstrapper.soledad_invalid_auth_token.connect(
            self._mail_status.set_soledad_invalid_auth_token)
        self._soledad_bootstrapper.soledad_failed.connect(
            self._mail_status.set_soledad_failed)

        self.ui.action_preferences.triggered.connect(self._show_preferences)
        self.ui.action_eip_preferences.triggered.connect(
            self._show_eip_preferences)
        self.ui.action_about_leap.triggered.connect(self._about)
        self.ui.action_quit.triggered.connect(self.quit)
        self.ui.action_wizard.triggered.connect(self._launch_wizard)
        self.ui.action_show_logs.triggered.connect(self._show_logger_window)
        self.ui.action_help.triggered.connect(self._help)
        self.ui.action_create_new_account.triggered.connect(
            self._launch_wizard)

        self.ui.action_advanced_key_management.triggered.connect(
            self._show_AKM)

        if IS_MAC:
            self.ui.menuFile.menuAction().setText(self.tr("File"))

        self.raise_window.connect(self._do_raise_mainwindow)

        # Used to differentiate between real quits and close to tray
        self._really_quit = False

        self._systray = None

        # XXX separate actions into a different
        # module.
        self._action_mail_status = QtGui.QAction(self.tr("Mail is OFF"), self)
        self._mail_status.set_action_mail_status(self._action_mail_status)

        self._action_eip_startstop = QtGui.QAction("", self)
        self._eip_status.set_action_eip_startstop(self._action_eip_startstop)

        self._action_visible = QtGui.QAction(self.tr("Hide Main Window"), self)
        self._action_visible.triggered.connect(self._toggle_visible)

        # disable buttons for now, may come back later.
        # self.ui.btnPreferences.clicked.connect(self._show_preferences)
        # self.ui.btnEIPPreferences.clicked.connect(self._show_eip_preferences)

        self._enabled_services = []

        # last minute UI manipulations

        self._center_window()
        self.ui.lblNewUpdates.setVisible(False)
        self.ui.btnMore.setVisible(False)
        #########################################
        # We hide this in height temporarily too
        self.ui.lblNewUpdates.resize(0, 0)
        self.ui.btnMore.resize(0, 0)
        #########################################
        self.ui.btnMore.clicked.connect(self._updates_details)
        if flags.OFFLINE is True:
            self._set_label_offline()

        # Services signals/slots connection
        self.new_updates.connect(self._react_to_new_updates)

        # XXX should connect to mail_conductor.start_mail_service instead
        self.soledad_ready.connect(self._start_smtp_bootstrapping)
        self.soledad_ready.connect(self._start_imap_service)
        self.mail_client_logged_in.connect(self._fetch_incoming_mail)
        self.logout.connect(self._stop_imap_service)
        self.logout.connect(self._stop_smtp_service)

        ################################# end Qt Signals connection ########

        init_platform()

        self._wizard = None
        self._wizard_firstrun = False

        self._logger_window = None

        self._bypass_checks = bypass_checks
        self._start_hidden = start_hidden

        # We initialize Soledad and Keymanager instances as
        # transparent proxies, so we can pass the reference freely
        # around.
        self._soledad = ProxyBase(None)
        self._keymanager = ProxyBase(None)

        self._soledad_defer = None

        self._mail_conductor = mail_conductor.MailConductor(
            self._soledad, self._keymanager)
        self._mail_conductor.connect_mail_signals(self._mail_status)

        # Eip machine is a public attribute where the state machine for
        # the eip connection will be available to the different components.
        # Remember that this will not live in the  +1600LOC mainwindow for
        # all the eternity, so at some point we will be moving this to
        # the EIPConductor or some other clever component that we will
        # instantiate from here.

        self.eip_machine = None
        # start event machines
        self.start_eip_machine()
        self._mail_conductor.start_mail_machine()

        self._eip_name = get_service_display_name(EIP_SERVICE)

        if self._first_run():
            self._wizard_firstrun = True
            self._disconnect_and_untrack()
            self._wizard = Wizard(backend=self._backend,
                                  bypass_checks=bypass_checks)
            # Give this window time to finish init and then show the wizard
            QtCore.QTimer.singleShot(1, self._launch_wizard)
            self._wizard.accepted.connect(self._finish_init)
            self._wizard.rejected.connect(self._rejected_wizard)
        else:
            # during finish_init, we disable the eip start button
            # so this has to be done after eip_machine is started
            self._finish_init()

    def _not_logged_in_error(self):
        """
        Handle the 'not logged in' backend error if we try to do an operation
        that requires to be logged in.
        """
        logger.critical("You are trying to do an operation that requires "
                        "log in first.")
        QtGui.QMessageBox.critical(
            self, self.tr("Application error"),
            self.tr("You are trying to do an operation "
                    "that requires logging in first."))

    def _connect_and_track(self, signal, method):
        """
        Helper to connect signals and keep track of them.

        :param signal: the signal to connect to.
        :type signal: QtCore.Signal
        :param method: the method to call when the signal is triggered.
        :type method: callable, Slot or Signal
        """
        self._backend_connected_signals[signal] = method
        signal.connect(method)

    def _backend_connect(self):
        """
        Helper to connect to backend signals
        """
        sig = self._backend.signaler
        self._connect_and_track(sig.prov_name_resolution,
                                self._intermediate_stage)
        self._connect_and_track(sig.prov_https_connection,
                                self._intermediate_stage)
        self._connect_and_track(sig.prov_download_ca_cert,
                                self._intermediate_stage)

        self._connect_and_track(sig.prov_download_provider_info,
                                self._load_provider_config)
        self._connect_and_track(sig.prov_check_api_certificate,
                                self._provider_config_loaded)

        self._connect_and_track(sig.prov_problem_with_provider,
                                self._login_problem_provider)

        self._connect_and_track(sig.prov_cancelled_setup,
                                self._set_login_cancelled)

        self._connect_and_track(sig.srp_auth_ok, self._authentication_finished)

        auth_error = (
            lambda: self._authentication_error(self.tr("Unknown error.")))
        self._connect_and_track(sig.srp_auth_error, auth_error)

        auth_server_error = (
            lambda: self._authentication_error(
                self.tr("There was a server problem with authentication.")))
        self._connect_and_track(sig.srp_auth_server_error, auth_server_error)

        auth_connection_error = (
            lambda: self._authentication_error(
                self.tr("Could not establish a connection.")))
        self._connect_and_track(sig.srp_auth_connection_error,
                                auth_connection_error)

        auth_bad_user_or_password = (
            lambda: self._authentication_error(
                self.tr("Invalid username or password.")))
        self._connect_and_track(sig.srp_auth_bad_user_or_password,
                                auth_bad_user_or_password)

        self._connect_and_track(sig.srp_logout_ok, self._logout_ok)
        self._connect_and_track(sig.srp_logout_error, self._logout_error)

        self._connect_and_track(sig.srp_not_logged_in_error,
                                self._not_logged_in_error)

        # We don't want to disconnect some signals so don't track them:
        sig.prov_unsupported_client.connect(self._needs_update)
        sig.prov_unsupported_api.connect(self._incompatible_api)

    def _disconnect_and_untrack(self):
        """
        Helper to disconnect the tracked signals.

        Some signals are emitted from the wizard, and we want to
        ignore those.
        """
        for signal, method in self._backend_connected_signals.items():
            try:
                signal.disconnect(method)
            except RuntimeError:
                pass  # Signal was not connected

        self._backend_connected_signals = {}

    def _rejected_wizard(self):
        """
        SLOT
        TRIGGERS: self._wizard.rejected

        Called if the wizard has been cancelled or closed before
        finishing.
        This is executed for the first run wizard only. Any other execution of
        the wizard won't reach this point.
        """
        providers = self._settings.get_configured_providers()
        has_provider_on_disk = len(providers) != 0
        if not has_provider_on_disk:
            # if we don't have any provider configured (included a pinned
            # one) we can't use the application, so quit.
            self.quit()
        else:
            # This happens if the user finishes the provider
            # setup but does not register
            self._wizard = None
            self._backend_connect()
            if self._wizard_firstrun:
                self._finish_init()

    def _launch_wizard(self):
        """
        SLOT
        TRIGGERS:
          self._login_widget.show_wizard
          self.ui.action_wizard.triggered

        Also called in first run.

        Launches the wizard, creating the object itself if not already
        there.
        """
        if self._wizard is None:
            self._disconnect_and_untrack()
            self._wizard = Wizard(backend=self._backend,
                                  bypass_checks=self._bypass_checks)
            self._wizard.accepted.connect(self._finish_init)
            self._wizard.rejected.connect(self._rejected_wizard)

        self.setVisible(False)
        # Do NOT use exec_, it will use a child event loop!
        # Refer to http://www.themacaque.com/?p=1067 for funny details.
        self._wizard.show()
        if IS_MAC:
            self._wizard.raise_()
        self._wizard.finished.connect(self._wizard_finished)
        self._settings.set_skip_first_run(True)

    def _wizard_finished(self):
        """
        SLOT
        TRIGGERS
          self._wizard.finished

        Called when the wizard has finished.
        """
        self.setVisible(True)

    def _get_leap_logging_handler(self):
        """
        Gets the leap handler from the top level logger

        :return: a logging handler or None
        :rtype: LeapLogHandler or None
        """
        # TODO this can be a function, does not need
        # to be a method.
        leap_logger = logging.getLogger('leap')
        for h in leap_logger.handlers:
            if isinstance(h, LeapLogHandler):
                return h
        return None

    def _show_logger_window(self):
        """
        SLOT
        TRIGGERS:
          self.ui.action_show_logs.triggered

        Displays the window with the history of messages logged until now
        and displays the new ones on arrival.
        """
        if self._logger_window is None:
            leap_log_handler = self._get_leap_logging_handler()
            if leap_log_handler is None:
                logger.error('Leap logger handler not found')
                return
            else:
                self._logger_window = LoggerWindow(handler=leap_log_handler)
                self._logger_window.setVisible(
                    not self._logger_window.isVisible())
        else:
            self._logger_window.setVisible(not self._logger_window.isVisible())

    def _show_AKM(self):
        """
        SLOT
        TRIGGERS:
            self.ui.action_advanced_key_management.triggered

        Displays the Advanced Key Management dialog.
        """
        domain = self._login_widget.get_selected_provider()
        logged_user = "{0}@{1}".format(self._logged_user, domain)
        self._akm = AdvancedKeyManagement(
            logged_user, self._keymanager, self._soledad)
        self._akm.show()

    def _show_preferences(self):
        """
        SLOT
        TRIGGERS:
          self.ui.btnPreferences.clicked (disabled for now)
          self.ui.action_preferences

        Displays the preferences window.
        """
        preferences = PreferencesWindow(
            self, self._backend, self._provider_config, self._soledad,
            self._login_widget.get_selected_provider())

        self.soledad_ready.connect(preferences.set_soledad_ready)
        preferences.show()
        preferences.preferences_saved.connect(self._update_eip_enabled_status)

    def _update_eip_enabled_status(self):
        """
        SLOT
        TRIGGER:
            PreferencesWindow.preferences_saved

        Enable or disable the EIP start/stop actions and stop EIP if the user
        disabled that service.

        :returns: if the eip actions were enabled or disabled
        :rtype: bool
        """
        settings = self._settings
        default_provider = settings.get_defaultprovider()
        enabled_services = []
        if default_provider is not None:
            enabled_services = settings.get_enabled_services(default_provider)

        eip_enabled = False
        if EIP_SERVICE in enabled_services:
            should_autostart = settings.get_autostart_eip()
            if should_autostart and default_provider is not None:
                self._eip_status.enable_eip_start()
                self._eip_status.set_eip_status("")
                eip_enabled = True
            else:
                # we don't have an usable provider
                # so the user needs to log in first
                self._eip_status.disable_eip_start()
        else:
            self._stop_eip()
            self._eip_status.disable_eip_start()
            self._eip_status.set_eip_status(self.tr("Disabled"))

        return eip_enabled

    def _show_eip_preferences(self):
        """
        SLOT
        TRIGGERS:
          self.ui.btnEIPPreferences.clicked
          self.ui.action_eip_preferences (disabled for now)

        Displays the EIP preferences window.
        """
        domain = self._login_widget.get_selected_provider()
        EIPPreferencesWindow(self, domain).show()

    #
    # updates
    #

    def _new_updates_available(self, req):
        """
        Callback for the new updates event

        :param req: Request type
        :type req: leap.common.events.events_pb2.SignalRequest
        """
        self.new_updates.emit(req)

    def _react_to_new_updates(self, req):
        """
        SLOT
        TRIGGER: self._new_updates_available

        Displays the new updates label and sets the updates_content
        """
        self.moveToThread(QtCore.QCoreApplication.instance().thread())
        self.ui.lblNewUpdates.setVisible(True)
        self.ui.btnMore.setVisible(True)
        self._updates_content = req.content

    def _updates_details(self):
        """
        SLOT
        TRIGGER: self.ui.btnMore.clicked

        Parses and displays the updates details
        """
        msg = self.tr("The Bitmask app is ready to update, please"
                      " restart the application.")

        # We assume that if there is nothing in the contents, then
        # the Bitmask bundle is what needs updating.
        if len(self._updates_content) > 0:
            files = self._updates_content.split(", ")
            files_str = ""
            for f in files:
                final_name = f.replace("/data/", "")
                final_name = final_name.replace(".thp", "")
                files_str += final_name
                files_str += "\n"
            msg += self.tr(" The following components will be updated:\n%s") \
                % (files_str,)

        QtGui.QMessageBox.information(self,
                                      self.tr("Updates available"),
                                      msg)

    def _finish_init(self):
        """
        SLOT
        TRIGGERS:
          self._wizard.accepted

        Also called at the end of the constructor if not first run.

        Implements the behavior after either constructing the
        mainwindow object, loading the saved user/password, or after
        the wizard has been executed.
        """
        # XXX: May be this can be divided into two methods?

        providers = self._settings.get_configured_providers()
        self._login_widget.set_providers(providers)
        self._show_systray()

        if not self._start_hidden:
            self.show()
            if IS_MAC:
                self.raise_()

        self._hide_unsupported_services()

        if self._wizard:
            possible_username = self._wizard.get_username()
            possible_password = self._wizard.get_password()

            # select the configured provider in the combo box
            domain = self._wizard.get_domain()
            self._login_widget.select_provider_by_name(domain)

            self._login_widget.set_remember(self._wizard.get_remember())
            self._enabled_services = list(self._wizard.get_services())
            self._settings.set_enabled_services(
                self._login_widget.get_selected_provider(),
                self._enabled_services)
            if possible_username is not None:
                self._login_widget.set_user(possible_username)
            if possible_password is not None:
                self._login_widget.set_password(possible_password)
                self._login()
            else:
                self.eip_needs_login.emit()

            self._wizard = None
            self._backend_connect()
        else:
            self._try_autostart_eip()

            domain = self._settings.get_provider()
            if domain is not None:
                self._login_widget.select_provider_by_name(domain)

            if not self._settings.get_remember():
                # nothing to do here
                return

            saved_user = self._settings.get_user()

            if saved_user is not None and has_keyring():
                if self._login_widget.load_user_from_keyring(saved_user):
                    self._login()

    def _hide_unsupported_services(self):
        """
        Given a set of configured providers, it creates a set of
        available services among all of them and displays the service
        widgets of only those.

        This means, for example, that with just one provider with EIP
        only, the mail widget won't be displayed.
        """
        providers = self._settings.get_configured_providers()

        services = set()

        for prov in providers:
            provider_config = ProviderConfig()
            loaded = provider_config.load(
                provider.get_provider_path(prov))
            if loaded:
                for service in provider_config.get_services():
                    services.add(service)

        self.ui.eipWidget.setVisible(EIP_SERVICE in services)
        self.ui.mailWidget.setVisible(MX_SERVICE in services)

    def _set_label_offline(self):
        """
        Set the login label to reflect offline status.
        """
        if self._logged_in_offline:
            provider = ""
        else:
            provider = self.ui.lblLoginProvider.text()

        self.ui.lblLoginProvider.setText(
            provider +
            self.tr(" (offline mode)"))

    #
    # systray
    #

    def _show_systray(self):
        """
        Sets up the systray icon
        """
        if self._systray is not None:
            self._systray.setVisible(True)
            return

        # Placeholder action
        # It is temporary to display the tray as designed
        help_action = QtGui.QAction(self.tr("Help"), self)
        help_action.setEnabled(False)

        systrayMenu = QtGui.QMenu(self)
        systrayMenu.addAction(self._action_visible)
        systrayMenu.addSeparator()

        eip_status_label = "{0}: {1}".format(self._eip_name, self.tr("OFF"))
        eip_menu = systrayMenu.addMenu(eip_status_label)
        eip_menu.addAction(self._action_eip_startstop)
        self._eip_status.set_eip_status_menu(eip_menu)
        systrayMenu.addSeparator()
        systrayMenu.addAction(self._action_mail_status)
        systrayMenu.addSeparator()
        systrayMenu.addAction(self.ui.action_quit)
        self._systray = SysTray(self)
        self._systray.setContextMenu(systrayMenu)
        self._systray.setIcon(self._eip_status.ERROR_ICON_TRAY)
        self._systray.setVisible(True)
        self._systray.activated.connect(self._tray_activated)

        self._mail_status.set_systray(self._systray)
        self._eip_status.set_systray(self._systray)

        hello = lambda: self._systray.showMessage(
            self.tr('Hello!'),
            self.tr('Bitmask has started in the tray.'))
        # we wait for the systray to be ready
        reactor.callLater(1, hello)

    def _tray_activated(self, reason=None):
        """
        SLOT
        TRIGGER: self._systray.activated

        Displays the context menu from the tray icon
        """
        self._update_hideshow_menu()

        context_menu = self._systray.contextMenu()
        if not IS_MAC:
            # for some reason, context_menu.show()
            # is failing in a way beyond my understanding.
            # (not working the first time it's clicked).
            # this works however.
            context_menu.exec_(self._systray.geometry().center())

    def _update_hideshow_menu(self):
        """
        Updates the Hide/Show main window menu text based on the
        visibility of the window.
        """
        get_action = lambda visible: (
            self.tr("Show Main Window"),
            self.tr("Hide Main Window"))[int(visible)]

        # set labels
        visible = self.isVisible() and self.isActiveWindow()
        self._action_visible.setText(get_action(visible))

    def _toggle_visible(self):
        """
        SLOT
        TRIGGER: self._action_visible.triggered

        Toggles the window visibility
        """
        visible = self.isVisible() and self.isActiveWindow()

        if not visible:
            QtGui.QApplication.setQuitOnLastWindowClosed(True)
            self.show()
            self.activateWindow()
            self.raise_()
        else:
            # We set this in order to avoid dialogs shutting down the
            # app on close, as they will be the only visible window.
            # e.g.: PreferencesWindow, LoggerWindow
            QtGui.QApplication.setQuitOnLastWindowClosed(False)
            self.hide()

        # Wait a bit until the window visibility has changed so
        # the menu is set with the correct value.
        QtCore.QTimer.singleShot(500, self._update_hideshow_menu)

    def _center_window(self):
        """
        Centers the mainwindow based on the desktop geometry
        """
        geometry = self._settings.get_geometry()
        state = self._settings.get_windowstate()

        if geometry is None:
            app = QtGui.QApplication.instance()
            width = app.desktop().width()
            height = app.desktop().height()
            window_width = self.size().width()
            window_height = self.size().height()
            x = (width / 2.0) - (window_width / 2.0)
            y = (height / 2.0) - (window_height / 2.0)
            self.move(x, y)
        else:
            self.restoreGeometry(geometry)

        if state is not None:
            self.restoreState(state)

    def _about(self):
        """
        SLOT
        TRIGGERS: self.ui.action_about_leap.triggered

        Display the About Bitmask dialog
        """
        today = datetime.now().date()
        greet = ("Happy New 1984!... or not ;)<br><br>"
                 if today.month == 1 and today.day < 15 else "")
        QtGui.QMessageBox.about(
            self, self.tr("About Bitmask - %s") % (VERSION,),
            self.tr("Version: <b>%s</b> (%s)<br>"
                    "<br>%s"
                    "Bitmask is the Desktop client application for "
                    "the LEAP platform, supporting encrypted internet "
                    "proxy, secure email, and secure chat (coming soon).<br>"
                    "<br>"
                    "LEAP is a non-profit dedicated to giving "
                    "all internet users access to secure "
                    "communication. Our focus is on adapting "
                    "encryption technology to make it easy to use "
                    "and widely available. <br>"
                    "<br>"
                    "<a href='https://leap.se'>More about LEAP"
                    "</a>") % (VERSION, VERSION_HASH[:10], greet))

    def _help(self):
        """
        SLOT
        TRIGGERS: self.ui.action_help.triggered

        Display the Bitmask help dialog.
        """
        # TODO: don't hardcode!
        smtp_port = 2013

        url = ("<a href='https://addons.mozilla.org/es/thunderbird/"
               "addon/bitmask/'>bitmask addon</a>")

        msg = self.tr(
            "<strong>Instructions to use mail:</strong><br>"
            "If you use Thunderbird you can use the Bitmask extension helper. "
            "Search for 'Bitmask' in the add-on manager or download it "
            "from: {0}.<br><br>"
            "You can configure Bitmask manually with these options:<br>"
            "<em>"
            "   Incoming -> IMAP, port: {1}<br>"
            "   Outgoing -> SMTP, port: {2}<br>"
            "   Username -> your bitmask username.<br>"
            "   Password -> does not matter, use any text. "
            " Just don't leave it empty and don't use your account's password."
            "</em>").format(url, IMAP_PORT, smtp_port)
        QtGui.QMessageBox.about(self, self.tr("Bitmask Help"), msg)

    def _needs_update(self):
        """
        Display a warning dialog to inform the user that the app needs update.
        """
        url = "https://dl.bitmask.net/"
        msg = self.tr(
            "The current client version is not supported "
            "by this provider.<br>"
            "Please update to latest version.<br><br>"
            "You can get the latest version from "
            "<a href='{0}'>{1}</a>").format(url, url)
        QtGui.QMessageBox.warning(self, self.tr("Update Needed"), msg)

    def _incompatible_api(self):
        """
        Display a warning dialog to inform the user that the provider has an
        incompatible API.
        """
        msg = self.tr(
            "This provider is not compatible with the client.<br><br>"
            "Error: API version incompatible.")
        QtGui.QMessageBox.warning(self, self.tr("Incompatible Provider"), msg)

    def changeEvent(self, e):
        """
        Reimplements the changeEvent method to minimize to tray
        """
        if not IS_MAC and \
           QtGui.QSystemTrayIcon.isSystemTrayAvailable() and \
           e.type() == QtCore.QEvent.WindowStateChange and \
           self.isMinimized():
            self._toggle_visible()
            e.accept()
            return
        QtGui.QMainWindow.changeEvent(self, e)

    def closeEvent(self, e):
        """
        Reimplementation of closeEvent to close to tray
        """
        if QtGui.QSystemTrayIcon.isSystemTrayAvailable() and \
                not self._really_quit:
            self._toggle_visible()
            e.ignore()
            return

        self._settings.set_geometry(self.saveGeometry())
        self._settings.set_windowstate(self.saveState())

        QtGui.QMainWindow.closeEvent(self, e)

    def _first_run(self):
        """
        Returns True if there are no configured providers. False otherwise

        :rtype: bool
        """
        providers = self._settings.get_configured_providers()
        has_provider_on_disk = len(providers) != 0
        skip_first_run = self._settings.get_skip_first_run()
        return not (has_provider_on_disk and skip_first_run)

    def _download_provider_config(self):
        """
        Starts the bootstrapping sequence. It will download the
        provider configuration if it's not present, otherwise will
        emit the corresponding signals inmediately
        """
        # XXX should rename this provider, name clash.
        provider = self._login_widget.get_selected_provider()
        self._backend.setup_provider(provider)

    def _load_provider_config(self, data):
        """
        SLOT
        TRIGGER: self._backend.signaler.prov_download_provider_info

        Once the provider config has been downloaded, this loads the
        self._provider_config instance with it and starts the second
        part of the bootstrapping sequence

        :param data: result from the last stage of the
                     run_provider_select_checks
        :type data: dict
        """
        if data[self._backend.PASSED_KEY]:
            selected_provider = self._login_widget.get_selected_provider()
            self._backend.provider_bootstrap(selected_provider)
        else:
            logger.error(data[self._backend.ERROR_KEY])
            self._login_widget.set_enabled(True)

    def _login_problem_provider(self):
        """
        Warns the user about a problem with the provider during login.
        """
        self._login_widget.set_status(
            self.tr("Unable to login: Problem with provider"))
        self._login_widget.set_enabled(True)

    def _login(self):
        """
        SLOT
        TRIGGERS:
          self._login_widget.login

        Starts the login sequence. Which involves bootstrapping the
        selected provider if the selection is valid (not empty), then
        start the SRP authentication, and as the last step
        bootstrapping the EIP service
        """
        # TODO most of this could ve handled by the login widget,
        # but we'd have to move lblLoginProvider into the widget itself,
        # instead of having it as a top-level attribute.
        if flags.OFFLINE is True:
            logger.debug("OFFLINE mode! bypassing remote login")
            # TODO reminder, we're not handling logout for offline
            # mode.
            self._login_widget.logged_in()
            self._logged_in_offline = True
            self._set_label_offline()
            self.offline_mode_bypass_login.emit()
        else:
            leap_assert(self._provider_config, "We need a provider config")
            self.ui.action_create_new_account.setEnabled(False)
            if self._login_widget.start_login():
                self._download_provider_config()

    def _authentication_error(self, msg):
        """
        SLOT
        TRIGGERS:
            Signaler.srp_auth_error
            Signaler.srp_auth_server_error
            Signaler.srp_auth_connection_error
            Signaler.srp_auth_bad_user_or_password

        Handle the authentication errors.

        :param msg: the message to show to the user.
        :type msg: unicode
        """
        self._login_widget.set_status(msg)
        self._login_widget.set_enabled(True)
        self.ui.action_create_new_account.setEnabled(True)

    def _cancel_login(self):
        """
        SLOT
        TRIGGERS:
          self._login_widget.cancel_login

        Stops the login sequence.
        """
        logger.debug("Cancelling log in.")
        self._cancel_ongoing_defers()

    def _cancel_ongoing_defers(self):
        """
        Cancel the running defers to avoid app blocking.
        """
        # XXX: Should we stop all the backend defers?
        self._backend.cancel_setup_provider()
        self._backend.cancel_login()

        if self._soledad_defer is not None:
            logger.debug("Cancelling soledad defer.")
            self._soledad_defer.cancel()
            self._soledad_defer = None

    def _set_login_cancelled(self):
        """
        SLOT
        TRIGGERS:
            Signaler.prov_cancelled_setup fired by
            self._backend.cancel_setup_provider()

        This method re-enables the login widget and display a message for
        the cancelled operation.
        """
        self._login_widget.set_status(self.tr("Log in cancelled by the user."))
        self._login_widget.set_enabled(True)

    def _provider_config_loaded(self, data):
        """
        SLOT
        TRIGGER: self._backend.signaler.prov_check_api_certificate

        Once the provider configuration is loaded, this starts the SRP
        authentication
        """
        leap_assert(self._provider_config, "We need a provider config!")

        if data[self._backend.PASSED_KEY]:
            username = self._login_widget.get_user()
            password = self._login_widget.get_password()

            self._hide_unsupported_services()

            domain = self._provider_config.get_domain()
            self._backend.login(domain, username, password)
        else:
            self._login_widget.set_status(
                "Unable to login: Problem with provider")
            logger.error(data[self._backend.ERROR_KEY])
            self._login_widget.set_enabled(True)

    def _authentication_finished(self):
        """
        SLOT
        TRIGGER: self._srp_auth.authentication_finished

        Once the user is properly authenticated, try starting the EIP
        service
        """
        self._login_widget.set_status(self.tr("Succeeded"), error=False)

        self._logged_user = self._login_widget.get_user()
        user = self._logged_user
        domain = self._provider_config.get_domain()
        full_user_id = make_address(user, domain)
        self._mail_conductor.userid = full_user_id
        self._start_eip_bootstrap()
        self.ui.action_create_new_account.setEnabled(True)

        # if soledad/mail is enabled:
        if MX_SERVICE in self._enabled_services:
            btn_enabled = self._login_widget.set_logout_btn_enabled
            btn_enabled(False)
            self.soledad_ready.connect(lambda: btn_enabled(True))
            self._soledad_bootstrapper.soledad_failed.connect(
                lambda: btn_enabled(True))

    def _start_eip_bootstrap(self):
        """
        Changes the stackedWidget index to the EIP status one and
        triggers the eip bootstrapping.
        """

        self._login_widget.logged_in()
        provider = self._provider_config.get_domain()
        self.ui.lblLoginProvider.setText(provider)

        self._enabled_services = self._settings.get_enabled_services(
            self._provider_config.get_domain())

        # TODO separate UI from logic.
        if self._provides_mx_and_enabled():
            self._mail_status.about_to_start()
        else:
            self._mail_status.set_disabled()

        self._maybe_start_eip()

    def _provides_mx_and_enabled(self):
        """
        Defines if the current provider provides mx and if we have it enabled.

        :returns: True if provides and is enabled, False otherwise
        :rtype: bool
        """
        provider_config = self._get_best_provider_config()
        return (provider_config.provides_mx() and
                MX_SERVICE in self._enabled_services)

    def _provides_eip_and_enabled(self):
        """
        Defines if the current provider provides eip and if we have it enabled.

        :returns: True if provides and is enabled, False otherwise
        :rtype: bool
        """
        provider_config = self._get_best_provider_config()
        return (provider_config.provides_eip() and
                EIP_SERVICE in self._enabled_services)

    def _maybe_run_soledad_setup_checks(self):
        """
        Conditionally start Soledad.
        """
        # TODO split.
        if self._already_started_soledad is True:
            return

        if not self._provides_mx_and_enabled():
            return

        username = self._login_widget.get_user()
        password = unicode(self._login_widget.get_password())
        provider_domain = self._login_widget.get_selected_provider()

        sb = self._soledad_bootstrapper
        if flags.OFFLINE is True:
            provider_domain = self._login_widget.get_selected_provider()
            sb._password = password

            self._provisional_provider_config.load(
                provider.get_provider_path(provider_domain))

            full_user_id = make_address(username, provider_domain)
            uuid = self._settings.get_uuid(full_user_id)
            self._mail_conductor.userid = full_user_id

            if uuid is None:
                # We don't need more visibility at the moment,
                # this is mostly for internal use/debug for now.
                logger.warning("Sorry! Log-in at least one time.")
                return
            fun = sb.load_offline_soledad
            fun(full_user_id, password, uuid)
        else:
            provider_config = self._provider_config

            if self._logged_user is not None:
                self._soledad_defer = sb.run_soledad_setup_checks(
                    provider_config, username, password,
                    download_if_needed=True)

    ###################################################################
    # Service control methods: soledad

    def _soledad_intermediate_stage(self, data):
        # TODO missing param docstring
        """
        SLOT
        TRIGGERS:
          self._soledad_bootstrapper.download_config

        If there was a problem, displays it, otherwise it does nothing.
        This is used for intermediate bootstrapping stages, in case
        they fail.
        """
        passed = data[self._soledad_bootstrapper.PASSED_KEY]
        if not passed:
            # TODO display in the GUI:
            # should pass signal to a slot in status_panel
            # that sets the global status
            logger.error("Soledad failed to start: %s" %
                         (data[self._soledad_bootstrapper.ERROR_KEY],))
            self._retry_soledad_connection()

    def _retry_soledad_connection(self):
        """
        Retries soledad connection.
        """
        # XXX should move logic to soledad boostrapper itself
        logger.debug("Retrying soledad connection.")
        if self._soledad_bootstrapper.should_retry_initialization():
            self._soledad_bootstrapper.increment_retries_count()
            # XXX should cancel the existing socket --- this
            # is avoiding a clean termination.
            self._maybe_run_soledad_setup_checks()
        else:
            logger.warning("Max number of soledad initialization "
                           "retries reached.")

    def _soledad_bootstrapped_stage(self, data):
        """
        SLOT
        TRIGGERS:
          self._soledad_bootstrapper.gen_key
          self._soledad_bootstrapper.local_only_ready

        If there was a problem, displays it, otherwise it does nothing.
        This is used for intermediate bootstrapping stages, in case
        they fail.

        :param data: result from the bootstrapping stage for Soledad
        :type data: dict
        """
        passed = data[self._soledad_bootstrapper.PASSED_KEY]
        if not passed:
            # TODO should actually *display* on the panel.
            logger.debug("ERROR on soledad bootstrapping:")
            logger.error("%r" % data[self._soledad_bootstrapper.ERROR_KEY])
            return

        logger.debug("Done bootstrapping Soledad")

        # Update the proxy objects to point to
        # the initialized instances.
        setProxiedObject(self._soledad,
                         self._soledad_bootstrapper.soledad)
        setProxiedObject(self._keymanager,
                         self._soledad_bootstrapper.keymanager)

        # Ok, now soledad is ready, so we can allow other things that
        # depend on soledad to start.
        self._soledad_defer = None

        # this will trigger start_imap_service
        # and start_smtp_boostrapping
        self.soledad_ready.emit()

    ###################################################################
    # Service control methods: smtp

    @QtCore.Slot()
    def _start_smtp_bootstrapping(self):
        """
        SLOT
        TRIGGERS:
            self.soledad_ready
        """
        if flags.OFFLINE is True:
            logger.debug("not starting smtp in offline mode")
            return

        # TODO for simmetry, this should be called start_smtp_service
        # (and delegate all the checks to the conductor)
        if self._provides_mx_and_enabled():
            self._mail_conductor.smtp_bootstrapper.run_smtp_setup_checks(
                self._provider_config,
                self._mail_conductor.smtp_config,
                download_if_needed=True)

    # XXX --- should remove from here, and connecte directly to the state
    # machine.
    @QtCore.Slot()
    def _stop_smtp_service(self):
        """
        SLOT
        TRIGGERS:
            self.logout
        """
        # TODO call stop_mail_service
        self._mail_conductor.stop_smtp_service()

    ###################################################################
    # Service control methods: imap

    @QtCore.Slot()
    def _start_imap_service(self):
        """
        SLOT
        TRIGGERS:
            self.soledad_ready
        """
        # TODO in the OFFLINE mode we should also modify the  rules
        # in the mail state machine so it shows that imap is active
        # (but not smtp since it's not yet ready for offline use)
        start_fun = self._mail_conductor.start_imap_service
        if flags.OFFLINE is True:
            provider_domain = self._login_widget.get_selected_provider()
            self._provider_config.load(
                provider.get_provider_path(provider_domain))
        provides_mx = self._provider_config.provides_mx()

        if flags.OFFLINE is True and provides_mx:
            start_fun()
            return

        if self._provides_mx_and_enabled():
            start_fun()

    def _on_mail_client_logged_in(self, req):
        """
        Triggers qt signal when client login event is received.
        """
        self.mail_client_logged_in.emit()

    @QtCore.Slot()
    def _fetch_incoming_mail(self):
        """
        SLOT
        TRIGGERS:
            self.mail_client_logged_in
        """
        # TODO connect signal directly!!!
        self._mail_conductor.fetch_incoming_mail()

    @QtCore.Slot()
    def _stop_imap_service(self):
        """
        SLOT
        TRIGGERS:
            self.logout
        """
        cv = Condition()
        cv.acquire()
        # TODO call stop_mail_service
        threads.deferToThread(self._mail_conductor.stop_imap_service, cv)
        # and wait for it to be stopped
        logger.debug('Waiting for imap service to stop.')
        cv.wait(self.SERVICE_STOP_TIMEOUT)

    # end service control methods (imap)

    ###################################################################
    # Service control methods: eip

    def start_eip_machine(self):
        """
        Initializes and starts the EIP state machine
        """
        button = self._eip_status.eip_button
        action = self._action_eip_startstop
        label = self._eip_status.eip_label
        builder = statemachines.ConnectionMachineBuilder(self._eip_connection)
        eip_machine = builder.make_machine(button=button,
                                           action=action,
                                           label=label)
        self.eip_machine = eip_machine
        self.eip_machine.start()
        logger.debug('eip machine started')

    @QtCore.Slot()
    def _disable_eip_start_action(self):
        """
        Disables the EIP start action in the systray menu.
        """
        self._action_eip_startstop.setEnabled(False)

    @QtCore.Slot()
    def _enable_eip_start_action(self):
        """
        Enables the EIP start action in the systray menu.
        """
        self._action_eip_startstop.setEnabled(True)

    @QtCore.Slot()
    def _on_eip_connected(self):
        """
        SLOT
        TRIGGERS:
            self._eip_status.eip_connection_connected
        Emits the EIPConnection.qtsigs.connected_signal

        This is a little workaround for connecting the vpn-connected
        signal that currently is beeing processed under status_panel.
        After the refactor to EIPConductor this should not be necessary.
        """
        self._eip_connection.qtsigs.connected_signal.emit()

        # check for connectivity
        provider_config = self._get_best_provider_config()
        domain = provider_config.get_domain()
        self._check_name_resolution(domain)

    def _check_name_resolution(self, domain):
        """
        Check if we can resolve the given domain name.

        :param domain: the domain to check.
        :type domain: str
        """
        def do_check():
            """
            Try to resolve the domain name.
            """
            socket.gethostbyname(domain.encode('idna'))

        def check_err(failure):
            """
            Errback handler for `do_check`.

            :param failure: the failure that triggered the errback.
            :type failure: twisted.python.failure.Failure
            """
            logger.error(repr(failure))
            logger.error("Can't resolve hostname.")

            msg = self.tr(
                "The server at {0} can't be found, because the DNS lookup "
                "failed. DNS is the network service that translates a "
                "website's name to its Internet address. Either your computer "
                "is having trouble connecting to the network, or you are "
                "missing some helper files that are needed to securely use "
                "DNS while {1} is active. To install these helper files, quit "
                "this application and start it again."
            ).format(domain, self._eip_name)

            show_err = lambda: QtGui.QMessageBox.critical(
                self, self.tr("Connection Error"), msg)
            reactor.callLater(0, show_err)

            # python 2.7.4 raises socket.error
            # python 2.7.5 raises socket.gaierror
            failure.trap(socket.gaierror, socket.error)

        d = threads.deferToThread(do_check)
        d.addErrback(check_err)

    def _try_autostart_eip(self):
        """
        Tries to autostart EIP
        """
        settings = self._settings

        if not self._update_eip_enabled_status():
            return

        default_provider = settings.get_defaultprovider()
        self._enabled_services = settings.get_enabled_services(
            default_provider)

        loaded = self._provisional_provider_config.load(
            provider.get_provider_path(default_provider))
        if loaded:
            # XXX I think we should not try to re-download config every time,
            # it adds some delay.
            # Maybe if it's the first run in a session,
            # or we can try only if it fails.
            self._maybe_start_eip()
        else:
            # XXX: Display a proper message to the user
            self.eip_needs_login.emit()
            logger.error("Unable to load %s config, cannot autostart." %
                         (default_provider,))

    @QtCore.Slot()
    def _start_eip(self):
        """
        SLOT
        TRIGGERS:
          self._eip_connection.qtsigs.do_connect_signal
          (via state machine)
        or called from _finish_eip_bootstrap

        Starts EIP
        """
        provider_config = self._get_best_provider_config()
        provider = provider_config.get_domain()
        self._eip_status.eip_pre_up()
        self.user_stopped_eip = False

        # until we set an option in the preferences window,
        # we'll assume that by default we try to autostart.
        # If we switch it off manually, it won't try the next
        # time.
        self._settings.set_autostart_eip(True)

        loaded = eipconfig.load_eipconfig_if_needed(
            provider_config, self._eip_config, provider)

        if not loaded:
            eip_status_label = self.tr("Could not load {0} configuration.")
            eip_status_label = eip_status_label.format(self._eip_name)
            self._eip_status.set_eip_status(eip_status_label, error=True)
            # signal connection aborted to state machine
            qtsigs = self._eip_connection.qtsigs
            qtsigs.connection_aborted_signal.emit()
            logger.error("Tried to start EIP but cannot find any "
                         "available provider!")
            return

        try:
            # XXX move this to EIPConductor
            host, port = get_openvpn_management()
            self._vpn.start(eipconfig=self._eip_config,
                            providerconfig=provider_config,
                            socket_host=host,
                            socket_port=port)
            self._settings.set_defaultprovider(provider)

            # XXX move to the state machine too
            self._eip_status.set_provider(provider)

        # TODO refactor exceptions so they provide translatable
        # usef-facing messages.
        except EIPNoPolkitAuthAgentAvailable:
            self._eip_status.set_eip_status(
                # XXX this should change to polkit-kde where
                # applicable.
                self.tr("We could not find any "
                        "authentication "
                        "agent in your system.<br/>"
                        "Make sure you have "
                        "<b>polkit-gnome-authentication-"
                        "agent-1</b> "
                        "running and try again."),
                error=True)
            self._set_eipstatus_off()
        except EIPNoTunKextLoaded:
            self._eip_status.set_eip_status(
                self.tr("{0} cannot be started because "
                        "the tuntap extension is not installed properly "
                        "in your system.").format(self._eip_name))
            self._set_eipstatus_off()
        except EIPNoPkexecAvailable:
            self._eip_status.set_eip_status(
                self.tr("We could not find <b>pkexec</b> "
                        "in your system."),
                error=True)
            self._set_eipstatus_off()
        except OpenVPNNotFoundException:
            self._eip_status.set_eip_status(
                self.tr("We could not find openvpn binary."),
                error=True)
            self._set_eipstatus_off()
        except OpenVPNAlreadyRunning as e:
            self._eip_status.set_eip_status(
                self.tr("Another openvpn instance is already running, and "
                        "could not be stopped."),
                error=True)
            self._set_eipstatus_off()
        except AlienOpenVPNAlreadyRunning as e:
            self._eip_status.set_eip_status(
                self.tr("Another openvpn instance is already running, and "
                        "could not be stopped because it was not launched by "
                        "Bitmask. Please stop it and try again."),
                error=True)
            self._set_eipstatus_off()
        except VPNLauncherException as e:
            # XXX We should implement again translatable exceptions so
            # we can pass a translatable string to the panel (usermessage attr)
            self._eip_status.set_eip_status("%s" % (e,), error=True)
            self._set_eipstatus_off()
        else:
            self._already_started_eip = True

    @QtCore.Slot()
    def _stop_eip(self):
        """
        SLOT
        TRIGGERS:
          self._eip_connection.qtsigs.do_disconnect_signal
          (via state machine)
        or called from _eip_finished

        Stops vpn process and makes gui adjustments to reflect
        the change of state.

        :param abnormal: whether this was an abnormal termination.
        :type abnormal: bool
        """
        self.user_stopped_eip = True
        self._vpn.terminate()

        self._set_eipstatus_off(False)
        self._already_started_eip = False

        logger.debug('Setting autostart to: False')
        self._settings.set_autostart_eip(False)

        if self._logged_user:
            self._eip_status.set_provider(
                make_address(
                    self._logged_user,
                    self._get_best_provider_config().get_domain()))
        self._eip_status.eip_stopped()

    @QtCore.Slot()
    def _on_eip_network_unreachable(self):
        # XXX Should move to EIP Conductor
        """
        SLOT
        TRIGGERS:
            self._eip_connection.qtsigs.network_unreachable

        Displays a "network unreachable" error in the EIP status panel.
        """
        self._eip_status.set_eip_status(self.tr("Network is unreachable"),
                                        error=True)
        self._eip_status.set_eip_status_icon("error")

    @QtCore.Slot()
    def _do_eip_restart(self):
        # XXX Should move to EIP Conductor
        """
        SLOT
            self._eip_connection.qtsigs.process_restart

        Restart the connection.
        """
        # for some reason, emitting the do_disconnect/do_connect
        # signals hangs the UI.
        self._stop_eip()
        QtCore.QTimer.singleShot(2000, self._start_eip)

    def _set_eipstatus_off(self, error=True):
        """
        Sets eip status to off
        """
        # XXX this should be handled by the state machine.
        self._eip_status.set_eip_status("", error=error)
        self._eip_status.set_eip_status_icon("error")

    def _eip_finished(self, exitCode):
        """
        SLOT
        TRIGGERS:
          self._vpn.process_finished

        Triggered when the EIP/VPN process finishes to set the UI
        accordingly.

        Ideally we would have the right exit code here,
        but the use of different wrappers (pkexec, cocoasudo) swallows
        the openvpn exit code so we get zero exit in some cases  where we
        shouldn't. As a workaround we just use a flag to indicate
        a purposeful switch off, and mark everything else as unexpected.

        In the near future we should trigger a native notification from here,
        since the user really really wants to know she is unprotected asap.
        And the right thing to do will be to fail-close.

        :param exitCode: the exit code of the eip process.
        :type exitCode: int
        """
        # TODO move to EIPConductor.
        # TODO Add error catching to the openvpn log observer
        # so we can have a more precise idea of which type
        # of error did we have (server side, local problem, etc)

        logger.info("VPN process finished with exitCode %s..."
                    % (exitCode,))

        qtsigs = self._eip_connection.qtsigs
        signal = qtsigs.disconnected_signal

        # XXX check if these exitCodes are pkexec/cocoasudo specific
        if exitCode in (126, 127):
            eip_status_label = self.tr(
                "{0} could not be launched "
                "because you did not authenticate properly.")
            eip_status_label = eip_status_label.format(self._eip_name)
            self._eip_status.set_eip_status(eip_status_label, error=True)
            self._vpn.killit()
            signal = qtsigs.connection_aborted_signal

        elif exitCode != 0 or not self.user_stopped_eip:
            eip_status_label = self.tr("{0} finished in an unexpected manner!")
            eip_status_label = eip_status_label.format(self._eip_name)
            self._eip_status.eip_stopped()
            self._eip_status.set_eip_status_icon("error")
            self._eip_status.set_eip_status(eip_status_label, error=True)
            signal = qtsigs.connection_died_signal

        if exitCode == 0 and IS_MAC:
            # XXX remove this warning after I fix cocoasudo.
            logger.warning("The above exit code MIGHT BE WRONG.")

        # We emit signals to trigger transitions in the state machine:
        signal.emit()

    # eip boostrapping, config etc...

    def _maybe_start_eip(self):
        """
        Start the EIP bootstrapping sequence if the client is configured to
        do so.
        """
        provider_config = self._get_best_provider_config()

        if self._provides_eip_and_enabled() and not self._already_started_eip:
            # XXX this should be handled by the state machine.
            self._eip_status.set_eip_status(
                self.tr("Starting..."))

            domain = self._login_widget.get_selected_provider()
            self._backend.setup_eip(domain)

            self._already_started_eip = True
            # we want to start soledad anyway after a certain timeout if eip
            # fails to come up
            QtCore.QTimer.singleShot(
                self.EIP_TIMEOUT,
                self._maybe_run_soledad_setup_checks)
        else:
            if not self._already_started_eip:
                if EIP_SERVICE in self._enabled_services:
                    self._eip_status.set_eip_status(
                        self.tr("Not supported"),
                        error=True)
                else:
                    self._eip_status.disable_eip_start()
                    self._eip_status.set_eip_status(self.tr("Disabled"))
            # eip will not start, so we start soledad anyway
            self._maybe_run_soledad_setup_checks()

    def _finish_eip_bootstrap(self, data):
        """
        SLOT
        TRIGGER: self._backend.signaler.eip_download_client_certificate

        Starts the VPN thread if the eip configuration is properly
        loaded
        """
        leap_assert(self._eip_config, "We need an eip config!")
        passed = data[self._backend.PASSED_KEY]

        if not passed:
            error_msg = self.tr("There was a problem with the provider")
            self._eip_status.set_eip_status(error_msg, error=True)
            logger.error(data[self._backend.ERROR_KEY])
            self._already_started_eip = False
            return

        provider_config = self._get_best_provider_config()
        domain = provider_config.get_domain()

        # XXX  move check to _start_eip ?
        loaded = eipconfig.load_eipconfig_if_needed(
            provider_config, self._eip_config, domain)

        if loaded:
            # DO START EIP Connection!
            self._eip_connection.qtsigs.do_connect_signal.emit()
        else:
            eip_status_label = self.tr("Could not load {0} configuration.")
            eip_status_label = eip_status_label.format(self._eip_name)
            self._eip_status.set_eip_status(eip_status_label, error=True)

    def _eip_intermediate_stage(self, data):
        # TODO missing param
        """
        SLOT
        TRIGGERS:
          self._backend.signaler.eip_download_config

        If there was a problem, displays it, otherwise it does nothing.
        This is used for intermediate bootstrapping stages, in case
        they fail.
        """
        passed = data[self._backend.PASSED_KEY]
        if not passed:
            self._login_widget.set_status(
                self.tr("Unable to connect: Problem with provider"))
            logger.error(data[self._backend.ERROR_KEY])
            self._already_started_eip = False

    # end of EIP methods ---------------------------------------------

    def _get_best_provider_config(self):
        """
        Returns the best ProviderConfig to use at a moment. We may
        have to use self._provider_config or
        self._provisional_provider_config depending on the start
        status.

        :rtype: ProviderConfig
        """
        # TODO move this out of gui.
        leap_assert(self._provider_config is not None or
                    self._provisional_provider_config is not None,
                    "We need a provider config")

        provider_config = None
        if self._provider_config.loaded():
            provider_config = self._provider_config
        elif self._provisional_provider_config.loaded():
            provider_config = self._provisional_provider_config
        else:
            leap_assert(False, "We could not find any usable ProviderConfig.")

        return provider_config

    @QtCore.Slot()
    def _logout(self):
        """
        SLOT
        TRIGGER: self._login_widget.logout

        Starts the logout sequence
        """
        self._soledad_bootstrapper.cancel_bootstrap()
        setProxiedObject(self._soledad, None)

        self._cancel_ongoing_defers()

        # reset soledad status flag
        self._already_started_soledad = False

        # XXX: If other defers are doing authenticated stuff, this
        # might conflict with those. CHECK!
        self._backend.logout()
        self.logout.emit()

    def _logout_error(self):
        """
        SLOT
        TRIGGER: self._srp_auth.logout_error

        Inform the user about a logout error.
        """
        self._login_widget.done_logout()
        self.ui.lblLoginProvider.setText(self.tr("Login"))
        self._login_widget.set_status(
            self.tr("Something went wrong with the logout."))

    def _logout_ok(self):
        """
        SLOT
        TRIGGER: self._srp_auth.logout_ok

        Switches the stackedWidget back to the login stage after
        logging out
        """
        self._login_widget.done_logout()
        self.ui.lblLoginProvider.setText(self.tr("Login"))

        self._logged_user = None
        self._login_widget.logged_out()
        self._mail_status.mail_state_disabled()

    def _intermediate_stage(self, data):
        # TODO this method name is confusing as hell.
        """
        SLOT
        TRIGGERS:
          self._backend.signaler.prov_name_resolution
          self._backend.signaler.prov_https_connection
          self._backend.signaler.prov_download_ca_cert
          self._backend.signaler.eip_download_config

        If there was a problem, displays it, otherwise it does nothing.
        This is used for intermediate bootstrapping stages, in case
        they fail.
        """
        passed = data[self._backend.PASSED_KEY]
        if not passed:
            msg = self.tr("Unable to connect: Problem with provider")
            self._login_widget.set_status(msg)
            self._login_widget.set_enabled(True)
            logger.error(data[self._backend.ERROR_KEY])

    #
    # window handling methods
    #

    def _on_raise_window_event(self, req):
        """
        Callback for the raise window event
        """
        if IS_WIN:
            raise_window_ack()
        self.raise_window.emit()

    def _do_raise_mainwindow(self):
        """
        SLOT
        TRIGGERS:
            self._on_raise_window_event

        Triggered when we receive a RAISE_WINDOW event.
        """
        TOPFLAG = QtCore.Qt.WindowStaysOnTopHint
        self.setWindowFlags(self.windowFlags() | TOPFLAG)
        self.show()
        self.setWindowFlags(self.windowFlags() & ~TOPFLAG)
        self.show()
        if IS_MAC:
            self.raise_()

    #
    # cleanup and quit methods
    #

    def _cleanup_pidfiles(self):
        """
        Removes lockfiles on a clean shutdown.

        Triggered after aboutToQuit signal.
        """
        if IS_WIN:
            WindowsLock.release_all_locks()

    def _cleanup_and_quit(self):
        """
        Call all the cleanup actions in a serialized way.
        Should be called from the quit function.
        """
        logger.debug('About to quit, doing cleanup...')

        self._stop_imap_service()

        if self._logged_user is not None:
            self._backend.logout()

        if self._soledad_bootstrapper.soledad is not None:
            logger.debug("Closing soledad...")
            self._soledad_bootstrapper.soledad.close()
        else:
            logger.error("No instance of soledad was found.")

        logger.debug('Terminating vpn')
        self._vpn.terminate(shutdown=True)

        self._cancel_ongoing_defers()

        # TODO missing any more cancels?

        logger.debug('Cleaning pidfiles')
        self._cleanup_pidfiles()

    def quit(self):
        """
        Cleanup and tidely close the main window before quitting.
        """
        # TODO separate the shutting down of services from the
        # UI stuff.

        # first thing to do quitting, hide the mainwindow and show tooltip.
        self.hide()
        self._systray.showMessage(
            self.tr('Quitting...'),
            self.tr('The app is quitting, please wait.'))

        # explicitly process events to display tooltip immediately
        QtCore.QCoreApplication.processEvents()

        # Set this in case that the app is hidden
        QtGui.QApplication.setQuitOnLastWindowClosed(True)

        self._backend.stop()
        self._cleanup_and_quit()
        self._really_quit = True

        if self._wizard:
            self._wizard.close()

        if self._logger_window:
            self._logger_window.close()

        self.close()

        if self._quit_callback:
            self._quit_callback()

        logger.debug('Bye.')