summaryrefslogtreecommitdiffstats
path: root/tails_installer/gui.py
blob: cc0f7c05fcaad1810d77193564526185cff8e6c3 (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
# -*- coding: utf-8 -*-
#
# Copyright © 2008-2013  Red Hat, Inc. All rights reserved.
# Copyright © 2008-2013  Luke Macken <lmacken@redhat.com>
# Copyright © 2008  Kushal Das <kushal@fedoraproject.org>
# Copyright © 2012-2016  Tails Developers <tails@boum.org>
#
# This copyrighted material is made available to anyone wishing to use, modify,
# copy, or redistribute it subject to the terms and conditions of the GNU
# General Public License v.2.  This program is distributed in the hope that it
# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
# implied warranties 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., 51 Franklin Street, Fifth
# Floor, Boston, MA 02110-1301, USA. Any Red Hat trademarks that are
# incorporated in the source code or documentation are not subject to the GNU
# General Public License and may only be used or replicated with the express
# permission of Red Hat, Inc.
#
# Author(s): Luke Macken <lmacken@redhat.com>
#            Kushal Das <kushal@fedoraproject.org>
#            Tails Developers <tails@boum.org>

"""
A cross-platform graphical interface for the Tails Installer
"""

import os
import sys
import logging
import threading
import urlparse
import traceback

from time import sleep
from datetime import datetime

from gi.repository import Gdk, GLib, Gtk

from tails_installer import TailsInstallerCreator, TailsInstallerError, _
from tails_installer.config import config
from tails_installer.source import SourceError, LocalIsoSource
from tails_installer.source import RunningLiveSystemSource
from tails_installer.releases import releases, get_fedora_releases
from tails_installer.utils import _to_unicode, _format_bytes_in_gb, _get_datadir
from tails_installer.utils import is_running_from_tails
from urlgrabber.grabber import URLGrabber, URLGrabError
from urlgrabber.progress import BaseMeter

MAX_FAT16 = 2047
MAX_FAT32 = 3999
MAX_EXT = 2097152

# FIXME: port to Gtk.Application

class ReleaseDownloader(threading.Thread):
    def __init__(self, release, progress, proxies, parent):
        threading.Thread.__init__(self)
        self.release = release
        self.progress = progress
        self.proxies = proxies
        self.parent = parent
        for rel in releases:
            if rel['name'] == str(release):
                self.url = rel['url']
                break
        else:
            raise TailsInstallerError(_("Unknown release: %s") % release)

    def run(self):
        GLib.idle_add(self.parent.update_log,
                      _("Downloading %s...") % os.path.basename(self.url))
        grabber = URLGrabber(progress_obj=self.progress, proxies=self.proxies)
        home = os.getenv('HOME', 'USERPROFILE')
        filename = os.path.basename(urlparse.urlparse(self.url).path)
        for folder in ('Downloads', 'My Documents'):
            if os.path.isdir(os.path.join(home, folder)):
                filename = os.path.join(home, folder, filename)
                break
        try:
            iso = grabber.urlgrab(self.url, reget='simple')
        except URLGrabError, e:
            GLib.idle_add(self.parent.download_complete, e.strerror)
        else:
            GLib.idle_add(self.parent.download_complete, iso)


class DownloadProgress(BaseMeter):
    """ An urlgrabber BaseMeter class.

    This class is called automatically by urlgrabber with our download details.
    This class then sends signals to our main dialog window to update the
    progress bar.
    """
    def __init__(self, parent):
        BaseMeter.__init__(self)
        self.parent = parent
        self.size = 0

    def start(self, filename=None, url=None, basename=None, size=None,
              now=None, text=None):
        self.size = size

    def update(self, amount_read, now=None):
        """ Update our download progressbar.

        :read: the number of bytes read so far
        """
        GLib.idle_add(parent.progress, float(amount_read) / self.size)

    def end(self, amount_read):
        self.update(amount_read)


class ProgressThread(threading.Thread):
    """ A thread that monitors the progress of Live USB creation.

    This thread periodically checks the amount of free space left on the
    given drive and sends a signal to our main dialog window to update the
    progress bar.
    """
    totalsize = 0
    orig_free = 0
    drive = None
    get_free_bytes = None

    def __init__(self, parent):
        threading.Thread.__init__(self)
        self.parent = parent
        self.terminate = False

    def set_data(self, size, drive, freebytes):
        self.totalsize = size / 1024
        self.drive = drive
        self.get_free_bytes = freebytes
        self.orig_free = self.get_free_bytes()

    def run(self):
        while not self.terminate:
            free = self.get_free_bytes()
            if free is None:
                break
            value = (self.orig_free - free) / 1024
            GLib.idle_add(self.parent.progress, float(value) / self.totalsize)
            if value >= self.totalsize:
                break
            sleep(3)

    def stop(self):
        self.terminate = True

    def __del__(self):
        GLib.idle_add(self.parent.progress, 1.0)
        threading.Thread.__del__(self)

class TailsInstallerThread(threading.Thread):

    def __init__(self, live, progress, parent):
        threading.Thread.__init__(self)
        self.progress = progress
        self.live = live
        self.parent = parent
        self.maximum = 0

    def status(self, text):
        GLib.idle_add(self.parent.status, text)

    def rescan_devices(self, force_partitions=False):
        self._waiting_detection = True

        def detection_done():
            self._waiting_detection = False

        self.live.detect_supported_drives(
            callback=detection_done,
            force_partitions=force_partitions)

        while self._waiting_detection:
            self.sleep(1)

    def installation_complete(self):
        GLib.idle_add(self.parent.on_installation_complete, None)

    def run(self):
        self.handler = TailsInstallerLogHandler(self.status)
        self.live.log.addHandler(self.handler)
        self.now = datetime.now()
        self.live.save_full_drive()
        try:
            if self.parent.opts.partition:
                self.live.unmount_device()
                if not self.live.can_read_partition_table():
                    self.live.log.info('Clearing unreadable partition table.')
                    self.live.clear_all_partition_tables()
                # If there is a partition already in place and we need
                # to reinstall, then we need to change the selected
                # device for its saved parent, if it exists
                if self.parent.force_reinstall and \
                   self.live.drive['parent_data'] is not None:
                    parent_data = self.live.drive['parent_data']
                    self.live.drives[parent_data['device']] = parent_data
                    self.live.drive = parent_data['device']
                    self.live.save_full_drive()
                self.live.partition_device()
                self.rescan_devices(force_partitions=True)
                self.live.switch_drive_to_system_partition()
                self.live.format_device()
                self.live.mount_device()

            self.live.verify_filesystem()
            if not self.live.drive['uuid'] and not self.live.label:
                self.status(_("Error: Cannot set the label or obtain "
                              "the UUID of your device.  Unable to continue."))
                self.live.log.removeHandler(self.handler)
                return

            self.live.check_free_space()

            if not self.parent.opts.noverify:
                # If we know about this ISO, and it's SHA1 -- verify it
                release = self.live.source.get_release()
                if release and ('sha1' in release or 'sha256' in release):
                    if not self.live.verify_iso_sha1(progress=self):
                        self.live.log.removeHandler(self.handler)
                        return

            # Setup the progress bar
            self.progress.set_data(size=self.live.totalsize,
                                   drive=self.live.drive['device'],
                                   freebytes=self.live.get_free_bytes)
            self.progress.start()

            self.live.extract_iso()
            self.live.read_extracted_mbr()
            self.live.create_persistent_overlay()
            self.live.update_configs()

            self.live.install_bootloader()
            # self.live.bootable_partition()

            if self.parent.opts.device_checksum:
                self.live.calculate_device_checksum(progress=self)
            if self.parent.opts.liveos_checksum:
                self.live.calculate_liveos_checksum()

            self.progress.stop()

            # Flush all filesystem buffers and unmount
            self.live.flush_buffers()
            self.live.unmount_device()

            if self.parent.opts.partition:
                self.live.switch_back_to_full_drive()

            self.live.reset_mbr()
            self.live.flush_buffers()

            duration = str(datetime.now() - self.now).split('.')[0]
            self.status(_("Installation complete! (%s)") % duration)
            self.installation_complete()

        except Exception, e:
            self.status(e)
            self.status(_("Tails installation failed!"))
            self.live.log.exception(unicode(e))
            self.live.log.debug(traceback.format_exc())

        self.live.log.removeHandler(self.handler)
        self.progress.stop()

    def set_max_progress(self, maximum):
        self.maximum = maximum

    def update_progress(self, value):
        GLib.idle_add(self.parent.progress, float(value) / maximum)

    def __del__(self):
        self.wait()


class TailsInstallerLogHandler(logging.Handler):

    def __init__(self, cb):
        logging.Handler.__init__(self)
        self.cb = cb

    def emit(self, record):
        if record.levelname in ('INFO', 'ERROR', 'WARN'):
            self.cb(record.msg)


class TailsInstallerWindow(Gtk.ApplicationWindow):
    """ Our main dialog class """

    def __init__(self, app=None, opts=None, args=None):
        Gtk.ApplicationWindow.__init__(self, application=app)

        self.opts = opts
        self.args = args
        self.in_process = False
        self.signals_connected = []
        self.source_available = False
        self.target_available = False
        self.target_selected  = False
        self.devices_with_persistence = []
        self.force_reinstall = False
        self.deprecated = False

        if self.opts.unprivileged == None:
            self.opts.unprivileged = True
        if self.opts.noverify == None:
            self.opts.noverify = True

        if os.path.isfile('/etc/tails-installer/deprecated-outside-of-Tails') \
           and not is_running_from_tails():
            self.deprecated = True
            self._build_ui()
            self.show()
            return

        self._build_ui()

        self.opts.clone = is_running_from_tails()
        self.live = TailsInstallerCreator(opts=opts)

        # Intercept all tails_installer.INFO log messages, and display them
        # in the GUI
        self.handler = TailsInstallerLogHandler(lambda x: self.append_to_log(x))
        self.live.log.addHandler(self.handler)
        if not self.opts.verbose:
            self.live.log.removeHandler(self.live.stream_handler)

        # Initialize the visibility and state of the clone/ISO source
        # selection widgets. This triggers on_radio_button_source_iso_toggled
        # that will in turn initialize self.live.source, self.source_available,
        # and populate the list of candidate devices.
        # - inside Tails
        if self.opts.clone:
            self.__radio_button_source_device.set_active(True)
            self.__filechooserbutton_source_file.set_sensitive(False)
        # - outside of Tails
        else:
            self.__radio_button_source_device.set_visible(False)
            self.__filechooserbutton_source_file.set_sensitive(True)

        self.__box_source_dl.set_visible(False)
        if not self.opts.clone:
            self.populate_releases()
        self.update_start_button()
        self.downloader = None
        self.progress_thread = ProgressThread(parent=self)
        self.download_progress = DownloadProgress(parent=self)
        self.live_thread = TailsInstallerThread(live=self.live,
                                                progress=self.progress_thread,
                                                parent=self)
        self.live.connect_drive_monitor(self.populate_devices)
        self.confirmed = False
        self.delete_existing_liveos_confirmed = False

        # If an ISO was specified on the command line, use it.
        if args:
            for arg in self.args:
                if arg.lower().endswith('.iso') and os.path.exists(arg):
                    self.select_source_iso(arg)

        # Determine if we have admin rights
        if not self.opts.unprivileged and not self.live.is_admin():
            self.live.log.error(_('Warning: This tool needs to be run as an '
                'Administrator. To do this, right click on the icon and open '
                'the Properties. Under the Compatibility tab, check the "Run '
                'this program as an administrator" box.'))

        # Show the UI
        self.show()

    def _build_ui(self):
        # Set windows properties
        self.set_deletable(True)
        self.connect('delete-event', Gtk.main_quit)
        self.set_title(_("Tails Installer"))

        # Import window content from UI file
        builder = Gtk.Builder.new_from_file(
                os.path.join(_get_datadir(), 'tails-installer.ui'))
        self.__box_installer = builder.get_object('box_installer')
        self.__image_header = builder.get_object('image_header')
        self.__infobar = builder.get_object('infobar')
        self.__label_infobar_title = builder.get_object('label_infobar_title')
        self.__label_infobar_details = builder.get_object('label_infobar_details')
        self.__box_source = builder.get_object('box_source')
        self.__box_source_select = builder.get_object('box_source_select')
        self.__box_source_file = builder.get_object('box_source_file')
        self.__filechooserbutton_source_file = builder.get_object('filechooserbutton_source_file')
        self.__box_source_dl = builder.get_object('box_source_dl')
        self.__liststore_source_dl = builder.get_object('liststore_source_dl')
        self.__combobox_source_dl = builder.get_object('combobox_source_dl')
        self.__box_target = builder.get_object('box_target')
        self.__combobox_target = builder.get_object('combobox_target')
        self.__liststore_target = builder.get_object('liststore_target')
        self.__textview_log = builder.get_object('textview_log')
        self.__progressbar = builder.get_object('progressbar_progress')
        self.__button_start = builder.get_object('button_start')
        self.__radio_button_source_iso = builder.get_object('radio_button_source_iso')
        self.__radio_button_source_device = builder.get_object('radio_button_source_device')
        self.__button_force_reinstall = builder.get_object('check_force_reinstall')
        self.__help_link = builder.get_object('help_link')

        self.add(self.__box_installer)
        builder.connect_signals(self)

        # Add a cell renderer to the comboboxes
        cell = Gtk.CellRendererText()
        self.__combobox_target.pack_start(cell, True)
        self.__combobox_target.add_attribute(cell, 'text', 0)

        cell = Gtk.CellRendererText()
        self.__combobox_source_dl.pack_start(cell, True)
        self.__combobox_source_dl.add_attribute(cell, 'text', 0)

        # Add image header
        self.__image_header.set_from_file(
                os.path.join(_get_datadir(), config['branding']['header']))
        rgba = Gdk.RGBA()
        rgba.parse(config['branding']['color'])
        self.__image_header.override_background_color(Gtk.StateFlags.NORMAL, rgba)

        if self.deprecated:
            self.__help_link.hide()
            self.__box_source.hide()
            self.__box_target.hide()
            builder.get_object('scrolledwindow_log').hide()
            self.__textview_log.hide()
            self.__progressbar.hide()
            self.__button_start.hide()
            self.__box_installer.set_valign(Gtk.Align.START)
            self.__image_header.set_valign(Gtk.Align.START)
            self.__label_infobar_details.set_use_markup(True)
            self.__infobar.set_message_type(Gtk.MessageType.INFO)
            self.__label_infobar_title.set_text(
                _("Tails Installer is deprecated"))
            self.__label_infobar_details.set_markup(
                _("To install a new Tails, see the <a href='https://tails.boum.org/install/'>installation documentation</a>.\n"
                  "To upgrade an existing Tails, see the <a href='https://tails.boum.org/upgrade/'>upgrade documentation</a>."))
            self.__infobar.set_visible(True)

    def on_radio_button_source_iso_toggled(self, radio_button):
        self.live.log.debug("Entering on_radio_button_source_iso_toggled")
        active_radio = [r for r in radio_button.get_group() if r.get_active()][0]
        if active_radio.get_label() == _("Clone the current Tails"):
            self.live.log.debug("Mode: clone")
            self.opts.clone = True
            self.live.source = RunningLiveSystemSource(
                path=config['running_liveos_mountpoint'])
            self.source_available = True
            self.__filechooserbutton_source_file.set_sensitive(False)
        elif active_radio.get_label() == _("Use a downloaded Tails ISO image"):
            self.live.log.debug("Mode: from ISO")
            self.opts.clone = False
            self.live.source = None
            self.source_available = False
            self.__filechooserbutton_source_file.set_sensitive(True)
        # previous error messages may be invalid now
        self.clear_log()
        # some previously rejected devices may now be valid candidates
        # and vice-versa
        self.live.log.debug("Calling populate_devices()"
                            " from on_radio_button_source_iso_toggled")
        self.populate_devices()

    def on_force_reinstall_clicked(self, button):
        # If the user has chosen install from ISO, but no ISO is selected
        if not self.live.opts.clone and not self.is_ISO_selected():
            self.warn_ISO_not_selected()
            return
        self.force_reinstall = True
        self.opts.partition = True
        self.__button_force_reinstall.set_visible(False)
        self.on_start_clicked(button)

    def on_source_file_set(self, filechooserbutton):
        self.select_source_iso(filechooserbutton.get_filename())

    def on_target_changed(self, combobox_target):
        # get selected device
        drive = self.get_selected_drive()
        if drive == None:
           return
        device = self.live.drives[drive]

        if self.live.device_can_be_upgraded(device):
            self.opts.partition = False
            self.force_reinstall = False
            self.__button_start.set_label(_('Upgrade'))
            self.__help_link.set_label(
                                     _('Manual Upgrade Instructions'))
            self.__help_link.set_uri(
                        _('https://tails.boum.org/upgrade/'))
            if device['is_device_big_enough_for_reinstall']:
                self.__button_force_reinstall.set_visible(True)
            else:
                self.__button_force_reinstall.set_visible(False)
        else:
            self.opts.partition = True
            self.force_reinstall = True
            self.__button_start.set_label(_('Install'))
            self.__button_force_reinstall.set_visible(False)
            self.__help_link.set_label(
                                     _('Installation Instructions'))
            self.__help_link.set_uri(
                        _('https://tails.boum.org/install/'))

    def get_device_pretty_name(self, device):
        size = _format_bytes_in_gb(device['parent_size']
                                    if device['parent_size']
                                    else device['size'])
        pretty_name = _("%(size)s %(vendor)s %(model)s device (%(device)s)") % {
                    'size':   size,
                    'vendor': device['vendor'],
                    'model':  device['model'],
                    'device': device['device']
        }
        return pretty_name

    def is_ISO_selected(self):
        return (self.live.source.__class__ == LocalIsoSource)

    def warn_ISO_not_selected(self):
        self.show_confirmation_dialog(_("No ISO image selected"),
                                      _("Please select a Tails ISO image."),
                                        True)

    def on_start_clicked(self, button):
        # If the user has chosen install from ISO, but no ISO is selected
        if not self.live.opts.clone and not self.is_ISO_selected():
            self.warn_ISO_not_selected()
            return
        self.begin()

    def on_infobar_response(self, infobar, response):
        self.__infobar.set_visible(False)
        self.__label_infobar_title.set_text("")
        self.__label_infobar_details.set_text("")

    def clear_log(self):
        text_buffer = self.__textview_log.get_buffer()
        text_buffer.set_text('')

    def append_to_log(self, text):
        if not text.endswith('\n'):
            text = text + '\n'
        text_buffer = self.__textview_log.get_buffer()
        text_buffer.insert(text_buffer.get_end_iter(), text)
        self.__textview_log.scroll_to_iter(text_buffer.get_end_iter(),
                                           0, False, 0, 0)

    def update_start_button(self):
        if self.source_available and self.target_available:
            self.__button_start.set_sensitive(True)
        else:
            self.__button_start.set_sensitive(False)

    def populate_devices(self, *args, **kw):
        if self.in_process or self.target_selected:
            return

        def add_devices():
            self.__liststore_target.clear()
            if not len(self.live.drives):
                self.__infobar.set_message_type(Gtk.MessageType.INFO)
                self.__label_infobar_title.set_text(
                        _("No device suitable to install Tails could be found"))
                self.__label_infobar_details.set_text(
                        _("Please plug a USB flash drive or SD card of at least %0.1f GB.")
                        % (config['official_min_installation_device_size'] / 1000.))
                self.__infobar.set_visible(True)
                self.target_available = False
                self.update_start_button()
                return
            else:
                self.__infobar.set_visible(False)
            self.live.log.debug('drives: %s' % self.live.drives)
            target_list = []
            self.devices_with_persistence = []
            for device, info in self.live.drives.items():
                # Skip the device that is the source of the copy
                if (
                        self.live.source and
                        self.live.source.dev and (
                            info['udi'] == self.live.source.dev or
                            info['parent_udi'] == self.live.source.dev
                        )
                    ):
                    self.live.log.debug('Skipping source device: %s' % info['device'])
                    continue
                # Skip the running device
                if self.live.running_device() in [info['udi'], info['parent_udi']]:
                    self.live.log.debug('Skipping running device: %s' % info['device'])
                    continue
                # Skip LUKS-encrypted partitions
                if info['fstype'] and info['fstype'] == 'crypto_LUKS':
                    self.live.log.debug('Skipping LUKS-encrypted partition: %s' % info['device'])
                    self.devices_with_persistence.append(info['parent'])
                    continue
                pretty_name = self.get_device_pretty_name(info)
                # Skip devices with non-removable bit enabled
                if not info['removable']:
                    message =_('The USB stick "%(pretty_name)s"'
                               ' is configured as non-removable by its'
                               ' manufacturer and Tails will fail to start on it.'
                               ' Please try installing on a different model.') % {
                               'pretty_name':  pretty_name
                               }
                    self.status(message)
                    continue
                # Skip too small devices, but inform the user
                if not info['is_device_big_enough_for_installation']:
                    message =_('The device "%(pretty_name)s"'
                               ' is too small to install'
                               ' Tails (at least %(size)s GB is required).') % {
                               'pretty_name': pretty_name,
                               'size': (float(
                                   config['official_min_installation_device_size'])
                                        / 1000)
                               }
                    self.status(message)
                    continue
                # Skip devices too small for cloning, but inform the user
                if self.opts.clone \
                   and not info['is_device_big_enough_for_upgrade']:
                    message = _('To upgrade device "%(pretty_name)s"'
                                ' from this Tails, you need to use'
                                " a downloaded Tails ISO image:\n"
                                'https://tails.boum.org/install/download') % {
                                    'pretty_name': pretty_name,
                                }
                    self.status(message)
                    continue
                target_list.append([pretty_name, device])
            if len(target_list):
                for target in target_list:
                    self.__liststore_target.append(target)
                self.target_available = True
                self.__combobox_target.set_active(0)
                self.update_start_button()

        try:
            self.live.detect_supported_drives(callback=add_devices)
        except TailsInstallerError, e:
            self.__infobar.set_message_type(Gtk.MessageType.ERROR)
            self.__label_infobar_title.set_text(
                    _("An error happened while installing Tails"))
            self.__label_infobar_details.set_text(e.args[0])
            self.__infobar.set_visible(True)
            self.append_to_log(e.args[0])
            self.target_available = False
            self.update_start_button()

    def populate_releases(self):
       for release in [release['name'] for release in releases]:
            self.__liststore_source_dl.append([release, None])

    def refresh_releases(self):
        self.live.log.info(_('Refreshing releases...'))
        fedora_releases = get_fedora_releases()
        self.__liststore_source_dl.clear()
        for release in [release['name'] for release in fedora_releases]:
            self.__liststore_source_dl.add(release)
        self.live.log.info(_('Releases updated!'))

    def progress(self, value):
        self.__progressbar.set_fraction(value)

    def status(self, obj):
        try:
            if isinstance(obj, str) or isinstance(obj, unicode):
                text = obj
            elif isinstance(obj, Exception) \
                 and hasattr(obj, 'args') \
                 and type(obj.args).__name__ == 'list':
                text = obj.args[0]
            else:
                text = str(obj)
            self.append_to_log(text)
        except Exception as e:
            self.live.log.exception(
                "Failed to set status to object of type '{type}'"
                .format(type=type(obj).__name__)
            )
            raise e

    def enable_widgets(self, enabled=True):
        if enabled:
            self.update_start_button()
        else:
            self.__button_start.set_sensitive(False)
            self.__button_force_reinstall.set_visible(False)
        self.__box_source.set_sensitive(enabled)
        self.__combobox_source_dl.set_sensitive(enabled)
        self.__combobox_target.set_sensitive(enabled and not self.target_selected)
        # FIXME: this may be useful when we'll support windows
        #if hasattr(self, 'refreshDevicesButton'):
        #    self.refreshDevicesButton.setEnabled(enabled)
        #if hasattr(self, 'refreshReleasesButton'):
        #    self.refreshReleasesButton.setEnabled(enabled)
        self.in_process = not enabled

    def get_selected_drive(self):
        drive = None
        iter = self.__combobox_target.get_active_iter()
        if iter != None:
            drive = self.__liststore_target.get(iter, 1)[0]
        if drive:
            return _to_unicode(drive)

    def on_installation_complete(self, data=None):
        # FIXME: replace content by a specific page
        dialog = Gtk.MessageDialog(parent=self,
                                   flags=Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                   message_type=Gtk.MessageType.INFO,
                                   buttons=Gtk.ButtonsType.CLOSE,
                                   message_format=_("Installation complete!"))
        dialog.run()
        self.close()

    def show_confirmation_dialog(self, title, message, warning,
                                 label_string=_("Install")):
        if (warning):
            buttons=Gtk.ButtonsType.OK
        else:
            buttons=Gtk.ButtonsType.NONE
        dialog = Gtk.MessageDialog(parent=self,
                                   flags=Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                   message_type=Gtk.MessageType.QUESTION,
                                   buttons=buttons,
                                   message_format=title)
        dialog.format_secondary_text(message)
        dialog.add_button(_("Cancel"), Gtk.ResponseType.CANCEL);
        dialog.add_button(label_string, Gtk.ResponseType.YES);
        reply = dialog.run()
        dialog.hide()
        if (reply == Gtk.ResponseType.YES):
            return True
        else:
            self.target_selected = None
            self.enable_widgets(True)
            return False

    def begin(self):
        """ Begin the Tails installation process.

        This method is called when the "Install Tails" button is clicked.
        """
        self.enable_widgets(False)
        if not self.target_selected:
            self.live.drive = self.get_selected_drive()
        self.target_selected = True
        for signal_match in self.signals_connected:
            signal_match.remove()

        # Unmount the device if needed
        if self.live.drive['mount']:
            self.live.dest = self.live.drive['mount']
            self.live.unmount_device()

        if not self.opts.partition:
            try:
                self.live.mount_device()
            except TailsInstallerError, e:
                self.status(e.args[0])
                self.enable_widgets(True)
                return
            except OSError, e:
                self.status(_('Unable to mount device'))
                self.enable_widgets(True)
                return

        if self.opts.partition:
            if not self.confirmed:
                if self.show_confirmation_dialog(
                        _("Confirm the target USB stick"),
                        _("%(size)s %(vendor)s %(model)s device (%(device)s)\n\n"
                          "All data on this USB stick will be lost.") %
                          {'vendor': self.live.drive['vendor'],
                           'model':  self.live.drive['model'],
                           'device': self.live.drive['device'],
                           'size':   _format_bytes_in_gb(self.live.drive['parent_size']
                                    if self.live.drive['parent_size']
                                    else self.live.drive['size'])
                          },
                          False,
                          label_string=_("Install")):
                    self.confirmed = True
                else:
                    return
            else:
                # The user has confirmed that they wish to partition their device,
                # let's go on
                self.confirmed = False
        else:
            description = _("%(parent_size)s %(vendor)s %(model)s device (%(device)s)") % {
                'vendor': self.live.drive['vendor'],
                'model':  self.live.drive['model'],
                'device': self.live.drive['device'],
                'parent_size': _format_bytes_in_gb(self.live.drive['parent_size']),
            }
            persistence_message = ""
            if self.devices_with_persistence:
                persistence_message = _("\n\nThe persistent storage on this USB stick will be preserved.")
            msg = _("%(description)s%(persistence_message)s") % {
                'description': description,
                'persistence_message': persistence_message,
            }
            if self.show_confirmation_dialog(_("Confirm the target USB stick"), \
               msg, False, label_string=_("Upgrade")):
                # The user has confirmed that they wish to overwrite their
                # existing Live OS.  Here we delete it first, in order to
                # accurately calculate progress.
                self.delete_existing_liveos_confirmed = False
                try:
                    self.live.delete_liveos()
                except TailsInstallerError, e:
                    self.status(e.args[0])
                    #self.live.unmount_device()
                    self.enable_widgets(True)
                    return
            else:
                return

        # Remove the log handler, because our live thread will register its own
        self.live.log.removeHandler(self.handler)

        # If we are running in clone mode, move on.
        if self.live.opts.clone:
            self.enable_widgets(False)
            self.live_thread.start()
        # If the user has selected an ISO, use it.
        elif self.live.source.__class__ == LocalIsoSource:
            self.enable_widgets(False)
            self.live_thread.start()
        else:
            raise NotImplementedError

    def download_complete(self, iso):
        """ Called by our ReleaseDownloader thread upon completion.

        Upon success, the thread passes in the filename of the downloaded
        release.  If the 'iso' argument is not an existing file, then
        it is assumed that the download failed and 'iso' should contain
        the error message.
        """
        if os.path.exists(iso):
            self.status(_("Download complete!"))
            self.live.source = LocalIsoSource(path=iso)
            self.live_thread.start()
        else:
            self.status(_("Download failed: " + iso))
            self.status(_("You can try again to resume your download"))
            self.enable_widgets(True)

    def on_source_file_set(self, filechooserbutton):
        self.select_source_iso(filechooserbutton.get_filename())

    def select_source_iso(self, isofile):
        if not os.access(isofile, os.R_OK):
            self.status(_("The selected file is unreadable. "
                          "Please fix its permissions or select another file."))
            return False
        try:
            self.live.source = LocalIsoSource(path=isofile)
        except Exception, e:
            self.status(_("Unable to use the selected file.  "
                          "You may have better luck if you move your ISO "
                          "to the root of your drive (ie: C:\)"))
            self.live.log.exception(e.args[0])
            return False

        self.live.log.info(_("%(filename)s selected")
                             % {'filename': str(os.path.basename(self.live.source.path))})
        self.source_available = True
        self.live.log.debug("Calling populate_devices()"
                            " from select_source_iso")
        self.populate_devices()

    def terminate(self):
        """ Final clean up """
        self.live.terminate()