1# Copyright (c) 2017-2021 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
2# This program is free software: you can redistribute it and/or modify
3# it under the terms of the GNU General Public License as published by
4# the Free Software Foundation, either version 3 of the License, or
5# (at your option) any later version.
6# This program is distributed in the hope that it will be useful,
7# but WITHOUT ANY WARRANTY; without even the implied warranty of
8# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9# GNU General Public License for more details.
10# You should have received a copy of the GNU General Public License
11# along with this program. If not, see <http://www.gnu.org/licenses/>.
12
13from gi.repository import Gtk, GLib
14
15
16class SmoothProgressBar(Gtk.ProgressBar):
17    """
18        Gtk.ProgressBar with full progression
19        If faction is 0.1 and you set it to 0.5, it will be udpated
20        to show all steps
21    """
22
23    def __init__(self):
24        """
25            Init widget
26        """
27        Gtk.ProgressBar.__init__(self)
28        self.__timeout_id = None
29        self.set_property("valign", Gtk.Align.END)
30        self.get_style_context().add_class("progressbar")
31
32    def set_fraction(self, fraction):
33        """
34            Set fraction smoothly
35            @param fraction as float
36        """
37        if self.__timeout_id is not None:
38            GLib.source_remove(self.__timeout_id)
39        self.__set_fraction(fraction)
40
41    def hide(self):
42        """
43            Hide widget and reset fraction
44        """
45        Gtk.ProgressBar.hide(self)
46        Gtk.ProgressBar.set_fraction(self, 0)
47        if self.__timeout_id is not None:
48            GLib.source_remove(self.__timeout_id)
49            self.__timeout_id = None
50
51#######################
52# PRIVATE             #
53#######################
54    def __set_fraction(self, fraction):
55        """
56            Set fraction smoothly
57            @param fraction as float
58        """
59        Gtk.ProgressBar.show(self)
60        self.__timeout_id = None
61        current = self.get_fraction()
62        if fraction < current:
63            progress = fraction
64        else:
65            if current > 0.95:
66                delta = 1.0 - current
67            elif fraction - current > 0.5 or fraction == 1.0:
68                delta = (fraction - current) / 10
69            else:
70                delta = (fraction - current) / 100
71            progress = current + delta
72        Gtk.ProgressBar.set_fraction(self, progress)
73        if progress < 1.0:
74            self.__timeout_id = GLib.timeout_add(10,
75                                                 self.__set_fraction,
76                                                 fraction)
77        else:
78            self.__timeout_id = GLib.timeout_add(500, self.hide)
79