Ejemplo n.º 1
0
def smartRemove(args):
    """
    Command for running Smart-Remove from Terminal.

    Args:
        args (argparse.Namespace):
                        previously parsed arguments

    Raises:
        SystemExit:     0 if okay
                        2 if Smart-Remove is not configured
    """
    setQuiet(args)
    printHeader()
    cfg = getConfig(args)
    sn = snapshots.Snapshots(cfg)

    enabled, keep_all, keep_one_per_day, keep_one_per_week, keep_one_per_month = cfg.smartRemove(
    )
    if enabled:
        _mount(cfg)
        del_snapshots = sn.smartRemoveList(datetime.today(), keep_all,
                                           keep_one_per_day, keep_one_per_week,
                                           keep_one_per_month)
        logger.info('Smart Remove will remove {} snapshots'.format(
            len(del_snapshots)))
        sn.smartRemove(del_snapshots, log=logger.info)
        _umount(cfg)
        sys.exit(RETURN_OK)
    else:
        logger.error('Smart Remove is not configured.')
        sys.exit(RETURN_NO_CFG)
Ejemplo n.º 2
0
 def setUp(self):
     super(SnapshotsTestCase, self).setUp()
     os.makedirs(self.snapshotPath)
     self.sn = snapshots.Snapshots(self.cfg)
     #use a tmp-file for flock because test_flockExclusive would deadlock
     #otherwise if a regular snapshot is running in background
     self.sn.GLOBAL_FLOCK = TMP_FLOCK.name
Ejemplo n.º 3
0
    def flockSecondInstance(self):
        cfgFile = os.path.abspath(os.path.join(__file__, os.pardir, 'config'))
        cfg = config.Config(cfgFile)
        sn = snapshots.Snapshots(cfg)
        sn.GLOBAL_FLOCK = self.sn.GLOBAL_FLOCK

        cfg.setGlobalFlock(True)
        sn.flockExclusive()
        sn.flockRelease()
Ejemplo n.º 4
0
def take_snapshot(cfg, force=True):
    """
    Take a new snapshot.

    cfg:    config.Config instance
    force:  take the snapshot even if it wouldn't need to or would be
            prevented (e.g. running on battery)
    """
    tools.load_env(cfg.get_cron_env_file())
    ret = snapshots.Snapshots(cfg).take_snapshot(force)
    return ret
Ejemplo n.º 5
0
    def __init__(self):
        self.snapshots = snapshots.Snapshots()
        self.config = self.snapshots.config

        if len(sys.argv) > 1:
            if not self.config.set_current_profile(sys.argv[1]):
                logger.warning("Failed to change Profile_ID %s" % sys.argv[1],
                               self)

        self.qapp = qt4tools.create_qapplication(self.config.APP_NAME)

        import icon
        self.icon = icon
        self.qapp.setWindowIcon(icon.BIT_LOGO)

        self.status_icon = QSystemTrayIcon(icon.BIT_LOGO)
        #self.status_icon.actionCollection().clear()
        self.contextMenu = QMenu()

        self.menuProfileName = self.contextMenu.addAction(
            _('Profile: "%s"') % self.config.get_profile_name())
        qt4tools.set_font_bold(self.menuProfileName)
        self.contextMenu.addSeparator()

        self.menuStatusMessage = self.contextMenu.addAction(_('Done'))
        self.menuProgress = self.contextMenu.addAction('')
        self.menuProgress.setVisible(False)
        self.contextMenu.addSeparator()
        self.startBIT = self.contextMenu.addAction(icon.BIT_LOGO,
                                                   _('Start BackInTime'))
        QObject.connect(self.startBIT, SIGNAL('triggered()'), self.onStartBIT)
        self.status_icon.setContextMenu(self.contextMenu)

        self.pixmap = icon.BIT_LOGO.pixmap(24)
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)
        self.progressBar.setTextVisible(False)
        self.progressBar.resize(24, 6)
        self.progressBar.render(self.pixmap,
                                sourceRegion=QRegion(0, -14, 24, 6),
                                flags=QWidget.RenderFlags(
                                    QWidget.DrawChildren))

        self.first_error = self.config.is_notify_enabled()
        self.popup = None
        self.last_message = None

        self.timer = QTimer()
        QObject.connect(self.timer, SIGNAL('timeout()'), self.update_info)

        self.ppid = os.getppid()
Ejemplo n.º 6
0
def remove(cfg, snapshot_ids = None, force = None):
    snapshots_list = snapshots.listSnapshots(cfg)
    if not snapshot_ids:
        snapshot_ids = (None,)
    sids = [selectSnapshot(snapshots_list, sid, 'SnapshotID to remove') for sid in snapshot_ids]

    if not force:
        print('Do you really want to remove this snapshots?')
        [print(sid.displayName) for sid in sids]
        if not 'yes' == input('(no/yes): '):
            return

    s = snapshots.Snapshots(cfg)
    [s.remove_snapshot(sid) for sid in sids]
Ejemplo n.º 7
0
def takeSnapshot(cfg, force=True):
    """
    Take a new snapshot.

    Args:
        cfg (config.Config):    config that should be used
        force (bool):           take the snapshot even if it wouldn't need to
                                or would be prevented (e.g. running on battery)

    Returns:
        bool:                   ``True`` if successful
    """
    tools.envLoad(cfg.cronEnvFile())
    ret = snapshots.Snapshots(cfg).backup(force)
    return ret
Ejemplo n.º 8
0
    def setUp(self):
        self.pathFolder = '/tmp/test/foo'
        self.pathFile = '/tmp/test/bar'
        if os.path.exists(self.pathFolder):
            shutil.rmtree(self.pathFolder)
        if os.path.exists(self.pathFile):
            os.remove(self.pathFile)
        os.makedirs(self.pathFolder)
        with open(self.pathFile, 'wt') as f:
            pass

        self.modeFolder = os.stat(self.pathFolder).st_mode
        self.modeFile = os.stat(self.pathFile).st_mode

        super(TestRestorePathInfo, self).setUp()
        self.sn = snapshots.Snapshots(self.cfg)
        self.run = False
Ejemplo n.º 9
0
    def load(self, snapshots=None, cfg=None, force=False):
        if self.loaded and not force:
            return

        if snapshots is None:
            import snapshots as snapshots_
            snapshots = snapshots_.Snapshots(cfg)

        self.loaded = True
        self.plugins = []
        self.hasGuiPlugins = False

        loadedPlugins = []
        for path in ('plugins', 'common/plugins', 'qt/plugins'):
            fullPath = tools.backintimePath(path)
            if os.path.isdir(fullPath):
                logger.debug('Register plugin path %s' % fullPath, self)
                tools.registerBackintimePath(path)
                for f in os.listdir(fullPath):
                    if f not in loadedPlugins and f.endswith(
                            '.py') and not f.startswith('__'):
                        try:
                            module = __import__(f[:-3])
                            module_dict = module.__dict__

                            for key, value in list(module_dict.items()):
                                if key.startswith('__'):
                                    continue

                                if type(value) is type:
                                    if issubclass(value, Plugin):
                                        plugin = value()
                                        if plugin.init(snapshots):
                                            logger.debug(
                                                'Add plugin %s' % f, self)
                                            if plugin.isGui():
                                                self.hasGuiPlugins = True
                                                self.plugins.insert(0, plugin)
                                            else:
                                                self.plugins.append(plugin)
                            loadedPlugins.append(f)
                        except BaseException as e:
                            logger.error(
                                'Failed to load plugin %s: %s' % (f, str(e)),
                                self)
Ejemplo n.º 10
0
 def setUp(self):
     super(TestSshSnapshots, self).setUp()
     self.sn = snapshots.Snapshots(self.cfg)
     os.makedirs(self.remoteFullPath)
Ejemplo n.º 11
0
 def setUp(self):
     super(TestRestore, self).setUp()
     self.sn = snapshots.Snapshots(self.cfg)
     self.run = False
Ejemplo n.º 12
0
 def setUp(self):
     super(TestSshSnapshots, self).setUp()
     self.sn = snapshots.Snapshots(self.cfg)
     os.mkdir(self.remotePath)
Ejemplo n.º 13
0
    def __init__(self):
        self.snapshots = snapshots.Snapshots()
        self.config = self.snapshots.config
        self.decode = None

        if len(sys.argv) > 1:
            if not self.config.setCurrentProfile(sys.argv[1]):
                logger.warning("Failed to change Profile_ID %s" % sys.argv[1],
                               self)

        self.qapp = qttools.createQApplication(self.config.APP_NAME)
        translator = qttools.translator()
        self.qapp.installTranslator(translator)
        self.qapp.setQuitOnLastWindowClosed(False)

        import icon
        self.icon = icon
        self.qapp.setWindowIcon(icon.BIT_LOGO)

        self.status_icon = QSystemTrayIcon(icon.BIT_LOGO)
        #self.status_icon.actionCollection().clear()
        self.contextMenu = QMenu()

        self.menuProfileName = self.contextMenu.addAction(
            _('Profile: "%s"') % self.config.profileName())
        qttools.setFontBold(self.menuProfileName)
        self.contextMenu.addSeparator()

        self.menuStatusMessage = self.contextMenu.addAction(_('Done'))
        self.menuProgress = self.contextMenu.addAction('')
        self.menuProgress.setVisible(False)
        self.contextMenu.addSeparator()

        self.btnPause = self.contextMenu.addAction(icon.PAUSE,
                                                   _('Pause snapshot process'))
        action = lambda: os.kill(self.snapshots.pid(), signal.SIGSTOP)
        self.btnPause.triggered.connect(action)

        self.btnResume = self.contextMenu.addAction(
            icon.RESUME, _('Resume snapshot process'))
        action = lambda: os.kill(self.snapshots.pid(), signal.SIGCONT)
        self.btnResume.triggered.connect(action)
        self.btnResume.setVisible(False)

        self.btnStop = self.contextMenu.addAction(icon.STOP,
                                                  _('Stop snapshot process'))
        self.btnStop.triggered.connect(self.onBtnStop)
        self.contextMenu.addSeparator()

        self.btnDecode = self.contextMenu.addAction(icon.VIEW_SNAPSHOT_LOG,
                                                    _('decode paths'))
        self.btnDecode.setCheckable(True)
        self.btnDecode.setVisible(self.config.snapshotsMode() == 'ssh_encfs')
        self.btnDecode.toggled.connect(self.onBtnDecode)

        self.openLog = self.contextMenu.addAction(icon.VIEW_LAST_LOG,
                                                  _('View Last Log'))
        self.openLog.triggered.connect(self.onOpenLog)
        self.startBIT = self.contextMenu.addAction(icon.BIT_LOGO,
                                                   _('Start BackInTime'))
        self.startBIT.triggered.connect(self.onStartBIT)
        self.status_icon.setContextMenu(self.contextMenu)

        self.pixmap = icon.BIT_LOGO.pixmap(24)
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)
        self.progressBar.setTextVisible(False)
        self.progressBar.resize(24, 6)
        self.progressBar.render(self.pixmap,
                                sourceRegion=QRegion(0, -14, 24, 6),
                                flags=QWidget.RenderFlags(
                                    QWidget.DrawChildren))

        self.first_error = self.config.notify()
        self.popup = None
        self.last_message = None

        self.timer = QTimer()
        self.timer.timeout.connect(self.updateInfo)

        self.ppid = os.getppid()
Ejemplo n.º 14
0
 def setUp(self):
     super(TestSnapshots, self).setUp()
     self.sn = snapshots.Snapshots(self.cfg)
Ejemplo n.º 15
0

with TemporaryDirectory() as tmp:
    cfgFile = os.path.join(tmp, 'config')
    appInstanceFile = os.path.join(tmp, 'appinstance')
    cfg = config.Config(cfgFile)
    appInstance = GUIApplicationInstance(appInstanceFile, '')

    cfg.setSnapshotsPath(tmp)
    cfg.setInclude([
        ('/home/janedoe', 0),
    ])
    cfg.checkConfig()
    cfg.save()

    sn = snapshots.Snapshots(cfg)
    rootSid = snapshots.RootSnapshot(cfg)

    global qapp
    qapp = qttools.createQApplication(cfg.APP_NAME)
    translator = qttools.translator()
    qapp.installTranslator(translator)

    #########################
    ### Snapshot Log View ###
    #########################

    cmd = ['../backintime/common/backintime', '--config', cfgFile, 'backup']
    proc = subprocess.Popen(cmd)
    proc.communicate()
Ejemplo n.º 16
0
def start_app(callback=None):
    cfg = config.Config()
    print_version(cfg)

    for arg in sys.argv[1:]:
        if arg == '--backup' or arg == '-b':
            if not callback is None:
                callback.init(cfg)
            take_snapshot(cfg, callback, True)
            sys.exit(0)

        if arg == '--backup-job':
            if not callback is None:
                callback.init(cfg)
            take_snapshot(cfg, callback, False)
            sys.exit(0)

        if arg == '--version' or arg == '-v':
            sys.exit(0)

        if arg == '--license':
            print cfg.get_license()
            sys.exit(0)

        if arg == '--help' or arg == '-h':
            print_help(cfg)
            sys.exit(0)

        if arg == '--snapshots-path':
            if not cfg.is_configured():
                print "The application is not configured !"
            else:
                print "SnapshotsPath: %s" % cfg.get_snapshots_full_path()
            sys.exit(0)

        if arg == '--snapshots-list':
            if not cfg.is_configured():
                print "The application is not configured !"
            else:
                list = snapshots.Snapshots(cfg).get_snapshots_list()
                if len(list) <= 0:
                    print "There are no snapshots"
                else:
                    for snapshot_id in list:
                        print "SnapshotID: %s" % snapshot_id
            sys.exit(0)

        if arg == '--snapshots-list-path':
            if not cfg.is_configured():
                print "The application is not configured !"
            else:
                s = snapshots.Snapshots(cfg)
                list = s.get_snapshots_list()
                if len(list) <= 0:
                    print "There are no snapshots"
                else:
                    for snapshot_id in list:
                        print "SnapshotPath: %s" % s.get_snapshot_path(
                            snapshot_id)
            sys.exit(0)

        if arg == '--last-snapshot':
            if not cfg.is_configured():
                print "The application is not configured !"
            else:
                list = snapshots.Snapshots(cfg).get_snapshots_list()
                if len(list) <= 0:
                    print "There are no snapshots"
                else:
                    print "SnapshotID: %s" % list[0]
            sys.exit(0)

        if arg == '--last-snapshot-path':
            if not cfg.is_configured():
                print "The application is not configured !"
            else:
                s = snapshots.Snapshots(cfg)
                list = s.get_snapshots_list()
                if len(list) <= 0:
                    print "There are no snapshots"
                else:
                    print "SnapshotPath: %s" % s.get_snapshot_path(list[0])
            sys.exit(0)

        if arg == '--snapshots' or arg == '-s':
            continue

        if arg == '--gnome' or arg == '--kde4' or arg == '--kde3':
            continue

        if arg[0] == '-':
            print "Ignore option: %s" % arg
            continue

    return cfg
Ejemplo n.º 17
0
 def init(self, cfg):
     self.cfg = cfg
     create_gnome_app(self.cfg)
     self.snapshots = snapshots.Snapshots(self.cfg)
Ejemplo n.º 18
0
    def __init__(self, config, app_instance):
        self.config = config
        self.app_instance = app_instance
        self.snapshots = snapshots.Snapshots(config)
        self.special_background_color = 'lightblue'
        self.popup_menu = None

        self.folder_path = None
        self.snapshot_id = ''

        self.about_dialog = None
        self.settings_dialog = None
        self.snapshots_dialog = None
        self.snapshot_name_dialog = None
        self.last_take_snapshot_message = None

        self.glade = gtk.glade.XML(
            os.path.join(self.config.get_app_path(), 'gnomebackintime.glade'),
            None, 'backintime')

        signals = {
            'on_MainWindow_destroy':
            gtk.main_quit,
            'on_MainWindow_delete_event':
            self.on_close,
            'on_MainWindow_key_release_event':
            self.on_key_release_event,
            'on_btn_exit_clicked':
            self.on_close,
            'on_btn_help_clicked':
            self.on_btn_help_clicked,
            'on_btn_about_clicked':
            self.on_btn_about_clicked,
            'on_btn_settings_clicked':
            self.on_btn_settings_clicked,
            'on_btn_backup_clicked':
            self.on_btn_backup_clicked,
            'on_btn_update_snapshots_clicked':
            self.on_btn_update_snapshots_clicked,
            'on_btn_snapshot_name_clicked':
            self.on_btn_snapshot_name_clicked,
            'on_btn_remove_snapshot_clicked':
            self.on_btn_remove_snapshot_clicked,
            'on_btn_restore_clicked':
            self.on_btn_restore_clicked,
            'on_btn_copy_clicked':
            self.on_btn_copy_clicked,
            'on_btn_snapshots_clicked':
            self.on_btn_snapshots_clicked,
            'on_btn_hidden_files_toggled':
            self.on_btn_hidden_files_toggled,
            'on_list_places_cursor_changed':
            self.on_list_places_cursor_changed,
            'on_list_time_line_cursor_changed':
            self.on_list_time_line_cursor_changed,
            'on_btn_folder_up_clicked':
            self.on_btn_fodler_up_clicked,
            'on_list_folder_view_row_activated':
            self.on_list_folder_view_row_activated,
            'on_list_folder_view_popup_menu':
            self.on_list_folder_view_popup_menu,
            'on_list_folder_view_button_press_event':
            self.on_list_folder_view_button_press_event,
            'on_list_folder_view_drag_data_get':
            self.on_list_folder_view_drag_data_get
        }

        self.glade.signal_autoconnect(signals)

        self.window = self.glade.get_widget('MainWindow')
        self.window.set_title(self.config.APP_NAME)

        #icons
        self.icon_names = gnomefileicons.GnomeFileIcons()

        #fix a glade bug
        self.glade.get_widget('btn_current_path').set_expand(True)

        #lbl snapshot
        self.lbl_snapshot = self.glade.get_widget('lbl_snapshot')

        #status bar
        self.status_bar = self.glade.get_widget('status_bar')
        self.status_bar.push(0, _('Done'))

        #show hidden files
        self.show_hidden_files = self.config.get_bool_value(
            'gnome.show_hidden_files', False)
        self.btn_hidden_files = self.glade.get_widget('btn_hidden_files')
        self.btn_hidden_files.set_active(self.show_hidden_files)
        #self.btn_hidden_files.set_label( _('Hidden files') ) #!!!

        #setup places view
        self.list_places = self.glade.get_widget('list_places')

        pix_renderer = gtk.CellRendererPixbuf()
        text_renderer = gtk.CellRendererText()

        column = gtk.TreeViewColumn(_('Shortcuts'))
        column.pack_start(pix_renderer, False)
        column.pack_end(text_renderer, True)
        column.add_attribute(pix_renderer, 'icon-name', 2)
        column.add_attribute(text_renderer, 'markup', 0)
        column.set_cell_data_func(pix_renderer,
                                  self.places_pix_renderer_function, None)
        column.set_cell_data_func(text_renderer,
                                  self.places_text_renderer_function, None)
        #column.set_alignment( 0.5 )
        self.list_places.append_column(column)

        #name, icon, path
        self.store_places = gtk.ListStore(str, str, str)
        self.list_places.set_model(self.store_places)
        self.list_places.get_selection().set_select_function(
            self.places_select_function, self.store_places)

        #setup folder view
        self.list_folder_view_widget = self.glade.get_widget(
            'list_folder_view_widget')
        self.list_folder_view_shadow = self.glade.get_widget(
            'list_folder_view_shadow')
        self.list_folder_view = self.glade.get_widget('list_folder_view')

        pix_renderer = gtk.CellRendererPixbuf()
        text_renderer = gtk.CellRendererText()

        column = gtk.TreeViewColumn(_('Name'))
        column.pack_start(pix_renderer, False)
        column.pack_end(text_renderer, True)
        column.add_attribute(pix_renderer, 'icon-name', 2)
        column.add_attribute(text_renderer, 'markup', 0)
        column.set_expand(True)
        column.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
        column.set_sort_column_id(0)
        self.list_folder_view.append_column(column)

        text_renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_('Size'))
        column.pack_end(text_renderer, True)
        column.add_attribute(text_renderer, 'markup', 4)
        column.set_sort_column_id(1)
        self.list_folder_view.append_column(column)

        text_renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_('Date'))
        column.pack_end(text_renderer, True)
        column.add_attribute(text_renderer, 'markup', 5)
        column.set_sort_column_id(2)
        self.list_folder_view.append_column(column)

        # display name, relative path, icon_name, type (0 - directory, 1 - file), size (str), date, size (int)
        self.store_folder_view = gtk.ListStore(str, str, str, int, str, str,
                                               int)
        self.store_folder_view.set_sort_func(0,
                                             self.sort_folder_view_by_column,
                                             0)  #name
        self.store_folder_view.set_sort_func(1,
                                             self.sort_folder_view_by_column,
                                             6)  #size
        self.store_folder_view.set_sort_func(2,
                                             self.sort_folder_view_by_column,
                                             5)  #date
        self.store_folder_view.set_sort_column_id(0, gtk.SORT_ASCENDING)

        self.list_folder_view.set_model(self.store_folder_view)

        #setup time line view
        self.list_time_line = self.glade.get_widget('list_time_line')

        text_renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_('Snapshots'), text_renderer, markup=0)
        column.set_cell_data_func(text_renderer,
                                  self.places_text_renderer_function, None)
        self.list_time_line.append_column(column)

        #display name, id
        self.store_time_line = gtk.ListStore(str, str)
        self.list_time_line.set_model(self.store_time_line)
        self.list_time_line.get_selection().set_select_function(
            self.places_select_function, self.store_time_line)
        self.update_time_line = False

        #calculate specialBackgroundColor
        style = self.list_time_line.get_style()
        bg1 = style.bg[gtk.STATE_NORMAL]
        bg2 = style.bg[gtk.STATE_SELECTED]
        self.special_background_color = gtk.gdk.Color(
            (2 * bg1.red + bg2.red) / 3, (2 * bg1.green + bg2.green) / 3,
            (2 * bg1.blue + bg2.blue) / 3).to_string()

        #restore size & position
        main_window_x = self.config.get_int_value('gnome.main_window.x', -1)
        main_window_y = self.config.get_int_value('gnome.main_window.y', -1)
        if main_window_x >= 0 and main_window_y >= 0:
            self.window.move(main_window_x, main_window_y)

        main_window_width = self.config.get_int_value(
            'gnome.main_window.width', -1)
        main_window_height = self.config.get_int_value(
            'gnome.main_window.height', -1)
        if main_window_width > 0 and main_window_height > 0:
            self.window.resize(main_window_width, main_window_height)

        main_window_hpaned1 = self.config.get_int_value(
            'gnome.main_window.hpaned1', -1)
        main_window_hpaned2 = self.config.get_int_value(
            'gnome.main_window.hpaned2', -1)
        if main_window_hpaned1 > 0 and main_window_hpaned2 > 0:
            self.glade.get_widget('hpaned1').set_position(main_window_hpaned1)
            self.glade.get_widget('hpaned2').set_position(main_window_hpaned2)

        #prepare popup menu ids
        gtk.stock_add([
            ('backintime.open', _('Open'), 0, 0, 'backintime'),
            ('backintime.copy', _('Copy'), 0, 0, 'backintime'),
            ('backintime.snapshots', _('Snapshots'), 0, 0, 'backintime'),
            ('backintime.diff', _('Diff'), 0, 0, 'backintime'),
            ('backintime.restore', _('Restore'), 0, 0, 'backintime')
        ])

        #show main window
        self.window.show()

        gobject.timeout_add(100, self.on_init)
        gobject.timeout_add(1000, self.raise_application)
Ejemplo n.º 19
0
    def __init__(self, config, app_instance, kapp, kaboutdata):
        KMainWindow.__init__(self)

        self.config = config
        self.app_instance = app_instance
        self.kapp = kapp
        self.kaboutdata = kaboutdata
        self.snapshots = snapshots.Snapshots(config)
        self.last_take_snapshot_message = None

        #main toolbar
        self.main_toolbar = self.toolBar()
        self.main_toolbar.setFloatable(False)

        self.btn_take_snapshot = self.main_toolbar.addAction(
            KIcon('document-save'), '')
        self.btn_take_snapshot.setToolTip(QString.fromUtf8(_('Take snapshot')))

        self.btn_update_snapshots = self.main_toolbar.addAction(
            KIcon('view-refresh'), '')
        self.btn_update_snapshots.setToolTip(
            QString.fromUtf8(_('Update snapshots')))

        self.btn_name_snapshot = self.main_toolbar.addAction(
            KIcon('edit-rename'), '')
        self.btn_name_snapshot.setToolTip(QString.fromUtf8(_('Snapshot Name')))

        self.btn_remove_snapshot = self.main_toolbar.addAction(
            KIcon('edit-delete'), '')
        self.btn_remove_snapshot.setToolTip(
            QString.fromUtf8(_('Remove Snapshot')))

        self.main_toolbar.addSeparator()

        self.btn_settings = self.main_toolbar.addAction(KIcon('configure'), '')
        self.btn_settings.setToolTip(QString.fromUtf8(_('Settings')))

        self.main_toolbar.addSeparator()

        self.btn_about = self.main_toolbar.addAction(KIcon('help-about'), '')
        self.btn_about.setToolTip(QString.fromUtf8(_('About')))

        self.btn_help = self.main_toolbar.addAction(KIcon('help-contents'), '')
        self.btn_help.setToolTip(QString.fromUtf8(_('Help')))

        self.main_toolbar.addSeparator()

        self.btn_quit = self.main_toolbar.addAction(KIcon('application-exit'),
                                                    '')
        self.btn_quit.setToolTip(QString.fromUtf8(_('Exit')))

        #main splitter
        self.main_splitter = QSplitter(self)
        self.main_splitter.setOrientation(Qt.Horizontal)

        #timeline
        self.list_time_line = QTreeWidget(self)
        self.list_time_line.setRootIsDecorated(False)
        self.list_time_line.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.list_time_line.setHeaderLabel(QString.fromUtf8(_('Snapshots')))
        self.main_splitter.addWidget(self.list_time_line)

        #right widget
        self.right_widget = QGroupBox(self)
        self.main_splitter.addWidget(self.right_widget)
        right_layout = QVBoxLayout(self.right_widget)
        #left, top, right, bottom = right_layout.getContentsMargins()
        #right_layout.setContentsMargins( 0, 0, 0, right )

        #files toolbar
        self.files_view_toolbar = KToolBar(self)
        self.files_view_toolbar.setFloatable(False)

        self.btn_folder_up = self.files_view_toolbar.addAction(
            KIcon('go-up'), '')
        self.btn_folder_up.setToolTip(QString.fromUtf8(_('Up')))

        self.edit_current_path = KLineEdit(self)
        self.edit_current_path.setReadOnly(True)
        self.files_view_toolbar.addWidget(self.edit_current_path)

        #show hidden files
        self.show_hidden_files = self.config.get_bool_value(
            'kde4.show_hidden_files', False)

        self.btn_show_hidden_files = KToggleAction(KIcon('list-add'), '',
                                                   self.files_view_toolbar)
        self.files_view_toolbar.addAction(self.btn_show_hidden_files)
        self.btn_show_hidden_files.setCheckable(True)
        self.btn_show_hidden_files.setChecked(self.show_hidden_files)
        self.btn_show_hidden_files.setToolTip(
            QString.fromUtf8(_('Show hidden files')))

        self.files_view_toolbar.addSeparator()

        self.btn_restore = self.files_view_toolbar.addAction(
            KIcon('document-revert'), '')
        self.btn_restore.setToolTip(QString.fromUtf8(_('Restore')))

        self.btn_copy = self.files_view_toolbar.addAction(
            KIcon('edit-copy'), '')
        self.btn_copy.setToolTip(QString.fromUtf8(_('Copy')))

        self.btn_snapshots = self.files_view_toolbar.addAction(
            KIcon('view-list-details'), '')
        self.btn_snapshots.setToolTip(QString.fromUtf8(_('Snapshots')))

        right_layout.addWidget(self.files_view_toolbar)

        #second spliter
        self.second_splitter = QSplitter(self)
        self.second_splitter.setOrientation(Qt.Horizontal)
        right_layout.addWidget(self.second_splitter)

        #places
        self.list_places = QTreeWidget(self)
        self.list_places.setRootIsDecorated(False)
        self.list_places.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.list_places.setHeaderLabel(QString.fromUtf8(_('Shortcuts')))
        self.second_splitter.addWidget(self.list_places)

        #files view stacked layout
        widget = QWidget(self)
        self.files_view_layout = QStackedLayout(widget)
        self.second_splitter.addWidget(widget)

        #folder don't exist label
        self.lbl_folder_dont_exists = QLabel(
            QString.fromUtf8(
                _('This directory don\'t exist\nin current snapshot !')), self)
        kde4tools.set_font_bold(self.lbl_folder_dont_exists)
        self.lbl_folder_dont_exists.setFrameShadow(QFrame.Sunken)
        self.lbl_folder_dont_exists.setFrameShape(QFrame.Panel)
        self.lbl_folder_dont_exists.setAlignment(Qt.AlignHCenter
                                                 | Qt.AlignVCenter)
        self.files_view_layout.addWidget(self.lbl_folder_dont_exists)

        #list files view
        self.list_files_view = QTreeView(self)
        self.files_view_layout.addWidget(self.list_files_view)
        self.list_files_view.setRootIsDecorated(False)
        self.list_files_view.setAlternatingRowColors(True)
        self.list_files_view.setAllColumnsShowFocus(True)
        self.list_files_view.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.list_files_view.setItemsExpandable(False)
        self.list_files_view.setDragEnabled(True)
        self.list_files_view.setDragDropMode(QAbstractItemView.DragOnly)

        self.list_files_view.header().setClickable(True)
        self.list_files_view.header().setMovable(False)
        self.list_files_view.header().setSortIndicatorShown(True)

        self.list_files_view_model = KDirModel(self)
        self.list_files_view_model.removeColumns(3, 2)
        self.list_files_view_model.dirLister().setAutoErrorHandlingEnabled(
            False, self)
        self.list_files_view_model.dirLister().setAutoUpdate(False)
        self.list_files_view_model.dirLister().setDelayedMimeTypes(False)
        self.list_files_view_model.dirLister().setMainWindow(self)

        self.list_files_view_sort_filter_proxy = KDirSortFilterProxyModel(self)
        self.list_files_view_sort_filter_proxy.setSourceModel(
            self.list_files_view_model)

        self.list_files_view.setModel(self.list_files_view_sort_filter_proxy)

        self.list_files_view_delegate = KFileItemDelegate(self)
        self.list_files_view.setItemDelegate(self.list_files_view_delegate)

        for column_index in xrange(3,
                                   self.list_files_view_model.columnCount()):
            self.list_files_view.hideColumn(column_index)

        sort_column = self.config.get_int_value(
            'kde4.main_window.files_view.sort.column', 0)
        sort_order = self.config.get_bool_value(
            'kde4.main_window.files_view.sort.ascending', True)
        if sort_order:
            sort_order = Qt.AscendingOrder
        else:
            sort_order = Qt.DescendingOrder

        self.list_files_view.header().setSortIndicator(sort_column, sort_order)
        self.list_files_view_sort_filter_proxy.sort(
            self.list_files_view.header().sortIndicatorSection(),
            self.list_files_view.header().sortIndicatorOrder())
        QObject.connect(self.list_files_view.header(),
                        SIGNAL('sortIndicatorChanged(int,Qt::SortOrder)'),
                        self.list_files_view_sort_filter_proxy.sort)

        self.files_view_layout.setCurrentWidget(self.list_files_view)

        #
        self.setCentralWidget(self.main_splitter)

        self.statusBar().showMessage(QString.fromUtf8(_('Done')))

        self.snapshots_list = []
        self.snapshot_id = '/'
        self.path = self.config.get_str_value('kde4.last_path', '/')
        self.edit_current_path.setText(self.path)

        #restore size and position
        x = self.config.get_int_value('kde4.main_window.x', -1)
        y = self.config.get_int_value('kde4.main_window.y', -1)
        if x >= 0 and y >= 0:
            self.move(x, y)

        w = self.config.get_int_value('kde4.main_window.width', 800)
        h = self.config.get_int_value('kde4.main_window.height', 500)
        self.resize(w, h)

        main_splitter_left_w = self.config.get_int_value(
            'kde4.main_window.main_splitter_left_w', 150)
        main_splitter_right_w = self.config.get_int_value(
            'kde4.main_window.main_splitter_right_w', 450)
        sizes = [main_splitter_left_w, main_splitter_right_w]
        self.main_splitter.setSizes(sizes)

        second_splitter_left_w = self.config.get_int_value(
            'kde4.main_window.second_splitter_left_w', 150)
        second_splitter_right_w = self.config.get_int_value(
            'kde4.main_window.second_splitter_right_w', 300)
        sizes = [second_splitter_left_w, second_splitter_right_w]
        self.second_splitter.setSizes(sizes)

        files_view_name_width = self.config.get_int_value(
            'kde4.main_window.files_view.name_width', -1)
        files_view_size_width = self.config.get_int_value(
            'kde4.main_window.files_view.size_width', -1)
        files_view_date_width = self.config.get_int_value(
            'kde4.main_window.files_view.date_width', -1)
        if files_view_name_width > 0 and files_view_size_width > 0 and files_view_date_width > 0:
            self.list_files_view.header().resizeSection(
                0, files_view_name_width)
            self.list_files_view.header().resizeSection(
                1, files_view_size_width)
            self.list_files_view.header().resizeSection(
                2, files_view_date_width)

        self.text_validator = QRegExpValidator(QRegExp('.*'), self)

        #
        kde4tools.set_font_bold(self.right_widget)

        #force settingdialog if it is not configured
        if not cfg.is_configured():
            kde4settingsdialog.SettingsDialog(self).exec_()

        if not cfg.is_configured():
            return

        if not cfg.can_backup():
            KMessageBox.error(
                self,
                QString.fromUtf8(
                    _('Can\'t find snapshots directory.\nIf it is on a removable drive please plug it and then press OK'
                      )))

        QObject.connect(self.list_files_view_model.dirLister(),
                        SIGNAL('completed()'), self.on_dir_lister_completed)
        QObject.connect(self.list_files_view_model.dirLister(),
                        SIGNAL('canceled()'), self.on_dir_lister_completed)

        #populate lists
        self.update_time_line()
        self.update_places()
        self.update_files_view(0)

        self.list_files_view.setFocus()

        self.update_snapshot_actions()

        QObject.connect(
            self.list_time_line,
            SIGNAL('currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)'),
            self.on_list_time_line_current_item_changed)
        QObject.connect(
            self.list_places,
            SIGNAL('currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)'),
            self.on_list_places_current_item_changed)
        QObject.connect(self.list_files_view,
                        SIGNAL('activated(const QModelIndex&)'),
                        self.on_list_files_view_item_activated)

        QObject.connect(self.btn_take_snapshot, SIGNAL('triggered()'),
                        self.on_btn_take_snapshot_clicked)
        QObject.connect(self.btn_update_snapshots, SIGNAL('triggered()'),
                        self.on_btn_update_snapshots_clicked)
        QObject.connect(self.btn_name_snapshot, SIGNAL('triggered()'),
                        self.on_btn_name_snapshot_clicked)
        QObject.connect(self.btn_remove_snapshot, SIGNAL('triggered()'),
                        self.on_btn_remove_snapshot_clicked)
        QObject.connect(self.btn_settings, SIGNAL('triggered()'),
                        self.on_btn_settings_clicked)
        QObject.connect(self.btn_about, SIGNAL('triggered()'),
                        self.on_btn_about_clicked)
        QObject.connect(self.btn_help, SIGNAL('triggered()'),
                        self.on_btn_help_clicked)
        QObject.connect(self.btn_quit, SIGNAL('triggered()'), self.close)
        QObject.connect(self.btn_folder_up, SIGNAL('triggered()'),
                        self.on_btn_folder_up_clicked)
        QObject.connect(self.btn_show_hidden_files, SIGNAL('toggled(bool)'),
                        self.on_btn_show_hidden_files_toggled)
        QObject.connect(self.btn_restore, SIGNAL('triggered()'),
                        self.on_btn_restore_clicked)
        QObject.connect(self.btn_copy, SIGNAL('triggered()'),
                        self.on_btn_copy_to_clipboard_clicked)
        QObject.connect(self.btn_snapshots, SIGNAL('triggered()'),
                        self.on_btn_snapshots_clicked)

        self.force_wait_lock_counter = 0

        self.timer_raise_application = QTimer(self)
        self.timer_raise_application.setInterval(1000)
        self.timer_raise_application.setSingleShot(False)
        QObject.connect(self.timer_raise_application, SIGNAL('timeout()'),
                        self.raise_application)
        self.timer_raise_application.start()

        self.timer_update_take_snapshot = QTimer(self)
        self.timer_update_take_snapshot.setInterval(1000)
        self.timer_update_take_snapshot.setSingleShot(False)
        QObject.connect(self.timer_update_take_snapshot, SIGNAL('timeout()'),
                        self.update_take_snapshot)
        self.timer_update_take_snapshot.start()
Ejemplo n.º 20
0
 def init(self, cfg):
     self.cfg = cfg
     self.snapshots = snapshots.Snapshots(self.cfg)
Ejemplo n.º 21
0
 def run(self):
     s = snapshots.Snapshots(self.config)
     s.restore(self.sid, self.what, self.callback, self.where, **self.kwargs)
     print('\nLog saved to %s' % self.log_file)
Ejemplo n.º 22
0
def take_snapshot(cfg, callback=None, force=True):
    logger.openlog()
    snapshots.Snapshots(cfg).take_snapshot(callback, force)
    logger.closelog()