Full Code of egara/buttermanager for AI

master 5d83cce810a4 cached
42 files
325.7 KB
71.7k tokens
196 symbols
1 requests
Download .txt
Showing preview only (342K chars total). Download the full file or copy to clipboard to get everything.
Repository: egara/buttermanager
Branch: master
Commit: 5d83cce810a4
Files: 42
Total size: 325.7 KB

Directory structure:
gitextract_bque78re/

├── .gitignore
├── LICENSE
├── README.md
├── aur/
│   ├── PKGBUILD
│   └── README.txt
├── buttermanager/
│   ├── bm_main.py
│   ├── buttermanager/
│   │   ├── __init__.py
│   │   ├── buttermanager.py
│   │   ├── exception/
│   │   │   ├── __init__.py
│   │   │   └── exception.py
│   │   ├── filesystem/
│   │   │   ├── __init__.py
│   │   │   ├── filesystem.py
│   │   │   └── snapshot.py
│   │   ├── manager/
│   │   │   ├── __init__.py
│   │   │   └── upgrader.py
│   │   ├── ui/
│   │   │   ├── ConsolidateSnapshotWindow.ui
│   │   │   ├── GeneralInfoWindow.ui
│   │   │   ├── InfoWindow.ui
│   │   │   ├── LogViewWindow.ui
│   │   │   ├── MainWindow.ui
│   │   │   ├── PasswordWindow.ui
│   │   │   ├── ProblemsFoundWindow.ui
│   │   │   ├── SnapshotWindow.ui
│   │   │   ├── SubvolumeWindow.ui
│   │   │   └── UpdatesWindow.ui
│   │   ├── util/
│   │   │   ├── __init__.py
│   │   │   ├── settings.py
│   │   │   └── utils.py
│   │   └── window/
│   │       ├── __init__.py
│   │       └── windows.py
│   └── main.py
├── doc/
│   └── README.md
├── install/
│   ├── native_install.sh
│   ├── uninstall.sh
│   └── venv_install.sh
├── packaging/
│   ├── buttermanager.desktop
│   └── buttermanager_venv.desktop
├── requirements.txt
├── rpm/
│   ├── README.txt
│   └── buttermanager.spec
├── setup.py
└── version.txt

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
#PyCharm configuration
.idea/

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    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/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# ButterManager

## Summary
ButterManager is a BTRFS tool for managing snapshots, balancing filesystems and upgrading the system safetly.

## Version
2.5.2

## Wiki
You can find documentation and more info in the [wiki of the project](https://github.com/egara/buttermanager/wiki)

## Caveats
- For using ButterManager, it is important to have a **good BTRFS structure in your filesystem**. If you want some tips and more information, you can [read
this](https://github.com/egara/arch-btrfs-installation).

- ButterManager works with **Debian**, **Ubuntu / derivatives (Linux Mint, KDE Neon, ElementaryOS, Zorin, Deepin...)**, **OpenSUSE / SUSE**, **RHEL / Fedora** and **Arch Linux** so far.

## Main Functionalities

### Managing snapshots
You will be able to define all the subvolumes you want to create snapshots and the path for their storage. Then, using ButterManager you will create and delete snapshots of those subvolumes at your will.

### Integration with GRUB
ButterManager is integrated with [grub-btrfs](https://github.com/Antynea/grub-btrfs) and you will be able to boot your system from any snapshot directly from the GRUB menu.

### Balancing BTRFS filesystems
As new snapshots are created in the system, the free space of the filesystem decreases and it is necessary to perform a system balancing regularly. With ButterManager you can perform these balances at any time and visualize the real space that is occupied.

### Upgrading the system
You will be able to upgrade your system and create new snapshots automatically when this operation is performed. Doing so, if something goes wrong, you will have a snapshot before the upgrade you can use to go back. You will be able to set the maximum number of snapshots in your system and ButterManager will maintain this number with every upgrade.

### Saving the logs
Everytime your system is upgraded using ButterManager, you could save the log indepently. This way, you would be able to see the packages that have been updated in every snapshot if you wish.

## Installation
You can install ButterManager in different ways.

### From the source code
In order to install ButterManager manually, you have to install these packages (all the packages described below are for **Arch Linux**. Please, take into account that maybe the name is different in your distribution and you have to install them for python3 version):

- Python 3
- **python-setuptool** (f.i. the name of the package in Ubuntu is **python3-setuptools**).
- **python-virtualenv** (f.i. the name of the package in Ubuntu is **python3-venv**). This package will only be needed if you use **venv_install.sh** script (see below).
- **grub-btrfs**. Please, go to its GitHub repository [https://github.com/Antynea/grub-btrfs](https://github.com/Antynea/grub-btrfs) and follow the instructions to install it if the package is not in the official repository of your distribution.
- **libxinerama**: This depency has been reported by some users (thanks Adam!) who install ButterManager on Ubuntu 20.04 (proper) (the name of the package in Ubuntu is **libxcb-xinerama0**)
- **tk** (f.i. the name of the package in Ubuntu is **python3-tk**)

Once you meet all the requirements, follow these steps:

1. Clone the repository (install **git** if it is needed first)

  ```
    git clone https://github.com/egara/buttermanager.git

  ```

1. Install ButterManager using one of the following installation scripts:
	1. **Native Installation**: This is the preferred method. It is slimmer because no virtual environment is created in order to execute ButterManager. This installation method will install the dependencies needed in your system natively and create an executable script for running the application. You will be able to execute ButterManager from the terminal typing **buttermanager** or directly via a shortcut created. In order to install ButterManager just open a terminal and execute:

    ```
      cd buttermanager
      cd install
      ./native_install.sh

    ```

	1. **Venv Installation**: If the first method doesn't run ButterManager properly, please try this second one. The installation process will create a virtual environment with all the dependencies needed and a desktop launcher to run ButterManager directly. In order to install ButterManager just open a terminal and type:

    ```
      cd buttermanager
      cd install
      ./venv_install.sh
    ```

1. If you want to uninstall ButterManager:

  ```
    cd buttermanager
    cd install
    ./uninstall.sh
  ```

### From AUR
If you are an Arch Linux user or your distribution is a derivative (Manjaro, EndevourOS...), ButterManager is in AUR. Depending on your package manager for AUR, type:

    yaourt -S buttermanager

Or

    trizen -S buttermanager

Or

    yay -S buttermanager

Those are only examples. Use the package manager you have installed for AUR. Once ButterManager is installed, you will be able to run it using the icon created in the main menu.

### From Nix
ButterManager is packaged in Nix [and included in the official repo](https://search.nixos.org/packages?channel=24.05&from=0&size=50&sort=relevance&type=packages&query=buttermanager)

### From RPM
ButterManager is packaged in Fedora but it is outdated. [This is the official package](https://packages.fedoraproject.org/pkgs/buttermanager/buttermanager/)

## Changelog

### Version 2.5.2
- Issue #56. Cancel button has been re-implemented within the consolidation window and now it closes this window when it is clicked.
- All ButterManager windows have been renamed to ButterManager. New labels in some windows have been added.

### Version 2.5.1
- Issue #52. A bug that prevented ButterManager to start normally (reported by Fedora users) has been fixed.
- ButterManager main window title is now displayed.
- Some missing buttons and different elements from tabs have been included within enable and disable buttons methods.

### Version 2.5.0
- Flatpak support implemented.
- Windows layout reimplemented. All windows are resizeable now.
- Font size customization implemented.
- Issue #29 fixed. Now, mobile users should be able to rescale the application to fit their displays.

### Version 2.4.3
- Issue #31 fixed. Preventing errors when calculating diffs against root directly.
- Issue #33 fixed. Refreshing filesystem statistics when user changes filesystem within combobox.
- Issue #45 fixed. Changing yaml.load method to yaml.safe_load because pyyaml library requires it since version 5.4.

### Version 2.4.2
- Minor changes in order to improve the package and preparing all to publish ButterManager in Fedora. Thanks Michel Alexandre Salim!

### Version 2.4.1
- Issue #32 fixed. ButterManager crashed when it was installed for the first time.

### Version 2.4
- Delete log icon button fixed.
- Issue #28 fixed. There is an error for Plasma Desktop (and PyQT5) when the file explorer is opened and the user tries to select a directory when setting subvolumes up. Only for this case, TK will be used as workaround.
- 'Don't remove snapshots' and 'Snapshots to keep' parameters are not global anymore. The user will be able to configure them per subvolume.
- Now, when user deletes a specific snapshot, the log related to it will be removed too if it exists.

### Version 2.3
- Thanks to Fedora guys (Neal Gompa @Conan-Kudo and Michel Alexandre Salim @michel-slm) ButterManager has been restructured in order to be packaged for Fedora. Because of that, now the application won't need to be installed within a virtual environment so the package installation footprint will be very much smaller.
- Two new installation methods have been created for users who wants to install ButterManager from source code: [native and venv](https://github.com/egara/buttermanager/tree/master/install). The first one is the recommended but the second one is still supported just in case native installation doesn't work properly.
- Issue #26 fixed: Now, the **Upgrade with snapshots** button creates snapshots and removes the old ones if needed.
- All the fast action buttons are disabled when a critical operation is executing.

### Version 2.2
- More stability. Some bugs have been fixed and ButterManager should not crashed after upgrading the system.
- Other operations are now Fast actions.
- New fast actions implemented: Upgrade system with/without snapshots and Take snapshots.

### Version 2.1
- Delete icon has been redesigned.
- New button to open a file explorer within a specific snapshot has been implemented.
- New feature to calculate differences between current snapshot and a specified one has been implemented.
- User will be able to calculate full differences (it will take some time to complete) included files modified and files only present in one of the snapshots.
- User will be able to calculate partial differences that will be faster but it will only inlcude files modified.

### Version 2.0
- Now, the installer creates ~/.local/share/applications directory if it didn't exist in order to allocate the ButterManager desktop launcher.
- The method of calculating the default original subvolume to consolidate the system has been reimplemented and improved to avoid some bugs detected.
- Now, the allocation of the original snapshot is stored in fstab instead of  the mounted point for every snapshot of root created.
- grub-mkconfig will run after consolidating deafult root subvolume
- Consolidation process will check the original path of the default subvolume for root and will use it in fstab.

### Version 1.9
- Buttermanager has been integrated with **grub-btrfs** package. It means that, for all these users who use GRUB will be able to boot its system from any snapshot created with this version of the application and above. This integration will be optional and configurable from **Settings** tab.

### Version 1.8 ###
- Font autoscaling implemented in order to let the GUI adapts to the current screen resolution.
- It has been created a new tab for **Documentation** and a **Wiki** at Github repository.
- The text of some tooltips have been fixed.

### Version 1.7 ###
- Bug fixed for Arch Linux and derivatives installing the package from AUR. Now, the application will be installed and run from a virtual environmen with all the modules needed. This causes that the size of the package buttermanager has increased

### Version 1.6 ###
- Logs generated during the upgrade process can be stored
- Logs management implemented
- Version checker implemented. When a new version of ButterManagger is released, a new info window will be display to warn the user

### Version 1.5 ###
- Labels refreshing after balancing the filesystem has been fixed
- Values to show certaing labels have been recalculated

### Version 1.4 ###
- System progress bar has been removed because it doesn't provide any relevant information
- A new button has been implemented in order to upgrade the system whithout managing snapshots
- All the ButterManager windows and dialogs have been reconfigured using fixed pixels in order to avoid the resizing
- The ButterManager icon has been assigned to all windows and dialogs
- When ButterManager is installed for the first time, the updates checker is not checked by default
- A new option added to yay command to check for AUR packages only
- New messages implemented in the main window in order to warn the user about the space of the filesystem
- Internet connection will be checked during 5 minutes. If there is no Internet connection, then the updates checker process will be cancelled

### Version 1.3 ###
- The updates checker is executed in other thread, so now the GUI is not freezed during the process.

### Version 1.2 ###
- Some layouts and texts fixed to fit properly
- New window to list the packages to be updated implemented
- Fixed a problem in the snap package for Wayland environments

### Version 1.1 ###

- RHEL / Fedora, OpenSUSE / SUSE support added.
- New window implemented for displaying serious problems related to the proper functioning of ButterManager.

### Version 1.0 ###

- Initial release.
- It supports Arch Linux, Debian, Ubuntu and derivatives.
- Safely system upgrade.
- BTRFS filesystems detection and visualization.
- Snapshots management.
- BTRFS filesystems balancing.
- Application packaged in AUR.
- Ubuntu Snap Package implemented for universal use in the rest of Linux distributions.

## Contact ##
If you want to contact me, you can do it using this e-mail address <eloy.garcia.pca@gmail.com>.


================================================
FILE: aur/PKGBUILD
================================================
# Maintainer: Eloy Garcia Almaden <eloy.garcia.pca@gmail.com>
pkgname=buttermanager
pkgver=2.5.2
pkgrel=0
epoch=
pkgdesc="Graphical tool to create BTRFS snapshots, balance filesystems and upgrade the system safetly"
arch=('x86_64')
url="https://github.com/egara/buttermanager"
license=('GPL')
groups=()
depends=('btrfs-progs' 'python>=3' 'grub-btrfs' 'python-setuptools' 'python-pyaml' 'python-pyqt5' 'tk')
makedepends=('python>=3' 'git')
checkdepends=()
optdepends=()
provides=()
conflicts=()
replaces=()
backup=()
options=()
install=
changelog=
# Local source if user wants to build the package locally once the git repo has been cloned
source=('git+file:////home/egarcia/Development/git/buttermanager/')
# Remote source
# Master branch
# source=('git+https://github.com/egara/buttermanager#branch=master')
# Tagged version
# source=('https://github.com/egara/buttermanager/archive/"$pkgver".tar.gz')
noextract=()
md5sums=('SKIP')
validpgpkeys=()

build() {
	cd "$pkgname"
	python setup.py build
}

package() {
	cd "$pkgname"
        # Creating destination directory
  	install -dm755 "$pkgdir/opt/$pkgname"

        # Installing ButterManager using python-setuptools
	echo -e "\n Installing ButterManager. Please wait..."
	python setup.py install --root="$pkgdir" --optimize=1 --skip-build

  	# Copying .desktop file and icon
        echo -e "\n Creating desktop icon. Finishing the installation"
  	install -Dm644 "$srcdir/$pkgname/packaging/$pkgname.desktop" "$pkgdir/usr/share/applications/$pkgname.desktop"
	install -Dm644 "$srcdir/$pkgname/packaging/$pkgname.svg" "$pkgdir/opt/$pkgname/gui/$pkgname.svg"
}


================================================
FILE: aur/README.txt
================================================
This directory contains all the files needed to package ButterManager application for Arch Linux


================================================
FILE: buttermanager/bm_main.py
================================================
from .buttermanager.buttermanager import PasswordWindow
from PyQt5.QtWidgets import QApplication
import sys


def main():
    """Main wrapper for starting ButterManager
    
    This script is only for packaging purposes. If you are developing ButterManager, then use main.py as initial
    script. This script will be copied from setup.py using setuptools and it will be invoked from the script
    created within /usr/bin/buttermanager once the application is installed via sudo python setup.py install

    """
    # Creating application instance
    application = QApplication(sys.argv)
    # Creating main window instance
    PasswordWindow(None)
    # Launching the application
    application.exec_()


if __name__ == "__main__":
    main()


================================================
FILE: buttermanager/buttermanager/__init__.py
================================================
# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>
#
# This file is part of buttermanager.
#
# 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, version 3 of the License.
#
# 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/>.
name = "buttermanager"


================================================
FILE: buttermanager/buttermanager/buttermanager.py
================================================
# -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>
#
# This file is part of buttermanager.
#
# 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, version 3 of the License.
#
# 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/>.

from .exception import exception
from .filesystem import filesystem, snapshot
from .manager import upgrader
from .util import utils, settings
from .window import windows
import os
import subprocess
import sys
import time
from functools import partial
from PyQt5.QtWidgets import QMainWindow, QDesktopWidget
from PyQt5.QtGui import QCursor, QTextCursor, QIcon, QPixmap, QDesktopServices, QFontMetrics
from PyQt5 import uic, QtTest, QtWidgets
from PyQt5.QtCore import Qt, pyqtSignal, QObject, QSize, QUrl


# Constants
SNAP_COMMAND = "snap"
FLATPAK_COMMAND = "flatpak"


class EmittingStream(QObject):

    text_written = pyqtSignal(str)

    def write(self, text):
        self.text_written.emit(str(text))

    def flush(self):
        pass


class PasswordWindow(QMainWindow):
    """Window to let the user type his/her password.

    Class inherited from QMainWindow (Window constructor)
    """
    # Constructor
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)
        self.parent = parent
        # Configuring the application
        self.__buttermanager_configurator = utils.ConfigManager()
        self.__buttermanager_configurator.configure()
        # Locating ui and images directories
        settings.ui_dir = os.path.join(os.path.dirname(__file__), 'ui')
        settings.images_dir = os.path.join(os.path.dirname(__file__), 'images')

        # UI elements
        self.__ui_elements = []
        # Logger
        self.__logger = utils.Logger(self.__class__.__name__).get()
        # Version checker
        self.__version_checker = utils.VersionChecker(self)

        # Initializing the application
        self.init_ui()

    def init_ui(self):
        """Initializes the Graphic User Interface.

        """
        # Loading User Interface
        password_window_ui = os.path.join(settings.ui_dir, 'PasswordWindow.ui')
        uic.loadUi(password_window_ui, self)

        # Setting the window icon
        buttermanager_icon = os.path.join(settings.images_dir, 'buttermanager50.png')
        self.setWindowIcon(QIcon(buttermanager_icon))

        # Calculating the base font size for all UI elements in the application
        settings.base_font_size = self.get_base_font_size()

        # Adjusting font scale
        # UI elements
        self.__ui_elements = [self.label_password, self.button_ok, self.button_cancel, self.button_lock,
                              self.input_password]
        utils.scale_fonts(self.__ui_elements)
        # Tooltips
        self.setStyleSheet(" QToolTip{font: " + str(settings.base_font_size) + "pt}")

        # Setting size for the window
        self.resize(320, 240)

        # Setting lock icon
        lock_icon = os.path.join(settings.images_dir, 'lock_24px_icon.png')
        self.button_lock.setIcon(QIcon(lock_icon))
        self.button_lock.setIconSize(QSize(24, 24))

        # Centering the window
        qt_rectangle = self.frameGeometry()
        center_point = QDesktopWidget().availableGeometry().center()
        qt_rectangle.moveCenter(center_point)
        self.move(qt_rectangle.topLeft())

        # Events
        # OK button event
        self.button_ok.clicked.connect(self.load_main_window)

        # Cancel button event
        self.button_cancel.clicked.connect(self.exit)

        # Press enter within QLineEdit
        self.input_password.returnPressed.connect(self.load_main_window)

        # Set focus on input_password
        self.input_password.setFocusPolicy(Qt.StrongFocus)
        self.input_password.setFocus()

        # Checks for new versions of ButterManager
        self.__version_checker.check_version()

        # Showing password window
        self.show()

    def get_base_font_size(self):
        """Gets the base font size for all the UI elements.

        Returns:
            int: Base font size.

        """
        self.__logger.info("Calculating appropriated base font size for UI elements...")
        font_fits = False

        # Base font size will be calculated using self.label_password attribute
        font = self.label_password.font()
        font_size = font.pointSize()

        while not font_fits:
            fm = QFontMetrics(font)
            pixels_wide = fm.width(self.label_password.text())
            pixels_high = fm.height()

            bound = fm.boundingRect(0, 0, pixels_wide, pixels_high, Qt.TextWordWrap | Qt.AlignLeft,
                                    self.label_password.text())

            if bound.width() <= self.label_password.width() and \
                    bound.height() <= self.label_password.height():
                font_fits = True
            else:
                font.setPointSize(font.pointSize() - 1)
                font_size = font_size - 1

        self.__logger.info("Base font size = " + str(font_size))
        return font_size

    def load_main_window(self):
        # Storing user's password
        settings.user_password = self.input_password.text()

        # Exiting password window
        self.hide()

        # Creating main window
        # Main window will only be displayed if everything goes right
        ButtermanagerMainWindow(self)

    def exit(self):
        # Exits the application
        self.hide()
        sys.exit()


class ButtermanagerMainWindow(QMainWindow):
    """Main window.

    Class inherited from QMainWindow (Window constructor)
    """
    # Constructor
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)
        self.parent = parent
        # Logger
        self.__logger = utils.Logger(self.__class__.__name__).get()
        # Current filesystem (it will be initialize in initialize method)
        self.__current_filesystem = None
        # Current filesystem uuid (it will be initialize in initialize method)
        self.__current_filesystem_uuid = None
        # Balancer that will balance the current filesystem if it is needed
        self.__balancer = None
        # Differentiator that will calculate the differences between a snapshot and the current
        # subvolume
        self.__differentiator = None
        # Upgrader that will upgrade the system if it is needed
        self.__upgrader = None
        # Updates checker that will check for updates if it is needed
        self.__updates_checker = None
        # Root snapshot checker
        self.__root_snapshot_checker = snapshot.RootSnapshotChecker(self)
        # UI elements
        self.__ui_elements = []
        # Initializing the application
        self.init_ui()

        # Installing the custom output stream to write all the console content to the
        # QTextEdit component
        sys.stdout = EmittingStream(text_written=self.normal_output_written)

    def __del__(self):
        """Restores sys.stdout.

        """
        sys.stdout = sys.__stdout__

    def normal_output_written(self, text):
        """Appends text to the QTextEdit text_edit_console.

        """
        cursor = self.text_edit_console.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertText(text)
        self.text_edit_console.setTextCursor(cursor)
        self.text_edit_console.ensureCursorVisible()

    def init_ui(self):
        """Initializes the Graphic User Interface.

        """
        try:
            # Loading User Interface
            main_window_ui = os.path.join(settings.ui_dir, 'MainWindow.ui')
            uic.loadUi(main_window_ui, self)

            # Setting the window icon
            buttermanager_icon = os.path.join(settings.images_dir, 'buttermanager50.png')
            self.setWindowIcon(QIcon(buttermanager_icon))

            # Adjusting font scale
            # UI elements
            self.__ui_elements = [self.tab_buttermanager, self.label_filesystem_info, self.label_filesystem_data,
                                  self.label_filesystem_metadata, self.label_filesystem, self.label_other_operations,
                                  self.label_filesystem_size, self.label_filesystem_size_value,
                                  self.label_filesystem_allocated, self.label_filesystem_allocated_value,
                                  self.label_filesystem_lost_info, self.label_filesystem_info_more, self.label_space_ok,
                                  self.label_space_danger, self.label_space_ko, self.label_space_data_danger,
                                  self.label_settings_upgrade, self.label_settings_subvolumes,
                                  self.label_existing_subvolumes, self.label_logo,
                                  self.label_app_name, self.label_app_version, self.label_app_developer,
                                  self.label_app_email, self.label_app_developer_2, self.button_balance,
                                  self.button_upgrade_system, self.button_upgrade_system_without_snapshots,
                                  self.button_fa_take_snapshot, self.button_take_snapshot,
                                  self.button_delete_snapshot, self.button_delete_log, self.button_view_log,
                                  self.button_edit_subvolume, self.button_delete_subvolume, self.button_add_subvolume,
                                  self.button_save_subvolume, self.button_github, self.button_close_terminal,
                                  self.button_save_log, self.text_edit_console, self.progressbar_metadata,
                                  self.progressbar_data, self.combobox_filesystem, self.list_snapshots, self.list_logs,
                                  self.combobox_subvolumes, self.line_edit_snapshot_where,
                                  self.line_edit_snapshot_prefix, self.checkbox_edit_dont_remove_snapshots,
                                  self.spinbox_edit_snapshots_to_keep, self.checkbox_startup, self.checkbox_log,
                                  self.checkbox_snap, self.checkbox_flatpak, self.checkbox_aur, self.button_save_log,
                                  self.button_close_terminal, self.button_wiki, self.label_documentation,
                                  self.checkbox_grub_btrfs, self.button_regenerate_grub, self.label_settings_ui,
                                  self.label_font_size, self.spinbox_font_size_increment,
                                  self.label_settings_subvolumes_where, self.label_settings_subvolumes_prefix,
                                  self.label_settings_subvolumes_snapshots_to_keep]
            utils.scale_fonts(self.__ui_elements)

            # Tooltips
            self.setStyleSheet(" QToolTip{font: " + str(settings.base_font_size) + "pt}")

            # Setting maximum and minimum  size for the main window
            self.setMinimumHeight(300)
            self.setMinimumWidth(300)

            # Hiding terminal and buttons
            self.button_close_terminal.hide()
            self.button_save_log.hide()
            self.text_edit_console.hide()

            # Setting initial size depending on resolution
            size_object = QtWidgets.QDesktopWidget().screenGeometry(-1)

            if size_object.width() == 1920:
                self.resize(640, 520)
            elif size_object.width() > 1920:
                self.resize(1024, 832)
            else:
                self.resize(320, 260)

            # Centering the window
            qt_rectangle = self.frameGeometry()
            center_point = QDesktopWidget().availableGeometry().center()
            qt_rectangle.moveCenter(center_point)
            self.move(qt_rectangle.topLeft())

            # Retrieving BTRFS Filesystems uuid
            uuid_filesystems = filesystem.get_btrfs_filesystems()
            if len(uuid_filesystems) > 0:
                self.__current_filesystem_uuid = uuid_filesystems[0]
                self.combobox_filesystem.addItems(uuid_filesystems)
                self.__current_filesystem = filesystem.Filesystem(self.__current_filesystem_uuid)
                self.__logger.info("BTRFS filesystems found in the system:")
                self.__logger.info(str(self.__current_filesystem))

                # Space labels
                self.label_space_ok.setStyleSheet('color: green')
                self.label_space_danger.setStyleSheet('color: orange')
                self.label_space_ko.setStyleSheet('color: red')
                self.label_space_data_danger.setStyleSheet('color: orange')

                # Displaying all the info related to the filesystem selected by default
                # and labels (show_labels will be invoked within fill_filesystem_info method)
                self.fill_filesystem_info(self.__current_filesystem)

                # Displaying snapshots
                self.fill_snapshots()

                # Displaying logs
                self.fill_logs()

                # Retrieving subvolumes
                self.fill_subvolumes()

                # BEGIN -- Displaying settings options
                # Retrieving snap packages upgrade decision
                if settings.snap_packages == 0:
                    self.checkbox_snap.setChecked(False)
                else:
                    self.checkbox_snap.setChecked(True)

                if utils.exist_program(SNAP_COMMAND):
                    self.checkbox_snap.show()
                else:
                    self.checkbox_snap.hide()

                if utils.exist_program(SNAP_COMMAND):
                    self.checkbox_snap.show()
                else:
                    self.checkbox_snap.hide()

                # Retrieving Flatpak packages upgrade decision
                if settings.flatpak_packages == 0:
                    self.checkbox_flatpak.setChecked(False)
                else:
                    self.checkbox_flatpak.setChecked(True)

                if utils.exist_program(FLATPAK_COMMAND):
                    self.checkbox_flatpak.show()
                else:
                    self.checkbox_flatpak.hide()

                # Retrieving AUR packages upgrade decision
                if settings.aur_repository == 0:
                    self.checkbox_aur.setChecked(False)
                else:
                    self.checkbox_aur.setChecked(True)

                if settings.user_os == utils.OS_ARCH:
                    self.checkbox_aur.show()
                else:
                    self.checkbox_aur.hide()

                # Retrieving check for updates at startup decision
                if settings.check_at_startup == 0:
                    self.checkbox_startup.setChecked(False)
                else:
                    self.checkbox_startup.setChecked(True)

                # Retrieving boot the system from GRUB using snapshots decision
                if settings.grub_btrfs == 0:
                    self.checkbox_grub_btrfs.setChecked(False)
                    self.button_regenerate_grub.hide()
                else:
                    self.checkbox_grub_btrfs.setChecked(True)
                    self.button_regenerate_grub.show()

                if settings.user_os == utils.OS_ARCH or \
                        settings.user_os == utils.OS_DEBIAN or \
                        settings.user_os == utils.OS_SUSE or \
                        settings.user_os == utils.OS_FEDORA:
                    self.checkbox_startup.show()
                else:
                    self.checkbox_startup.hide()

                # Retrieving save log decision
                if settings.save_log == 0:
                    self.checkbox_log.setChecked(False)
                else:
                    self.checkbox_log.setChecked(True)

                # Retrieving font size increment
                self.spinbox_font_size_increment.setValue(settings.font_size_increment)

                # END -- Displaying settings options

                # Setting buttons and icons
                # Snapshot buttons
                add_icon = os.path.join(settings.images_dir, 'add_16px_icon.png')
                self.button_take_snapshot.setIcon(QIcon(add_icon))
                self.button_take_snapshot.setIconSize(QSize(16, 16))
                remove_icon = os.path.join(settings.images_dir, 'remove_16px_icon.png')
                self.button_delete_snapshot.setIcon(QIcon(remove_icon))
                self.button_delete_snapshot.setIconSize(QSize(16, 16))
                exchange_arrows_icon = os.path.join(settings.images_dir, 'exchange_arrows_16px_icon.png')
                self.button_diff.setIcon(QIcon(exchange_arrows_icon))
                self.button_diff.setIconSize(QSize(16, 16))
                folder_icon = os.path.join(settings.images_dir, 'folder_16px_icon.png')
                self.button_folder.setIcon(QIcon(folder_icon))
                self.button_folder.setIconSize(QSize(16, 16))

                # Logs buttons
                view_icon = os.path.join(settings.images_dir, 'view_24px_icon.png')
                self.button_view_log.setIcon(QIcon(view_icon))
                self.button_view_log.setIconSize(QSize(16, 16))
                self.button_delete_log.setIcon(QIcon(remove_icon))
                self.button_delete_log.setIconSize(QSize(16, 16))

                # Subvolume buttons
                accept_icon = os.path.join(settings.images_dir, 'accept_16px_icon.png')
                self.button_save_subvolume.setIcon(QIcon(accept_icon))
                self.button_save_subvolume.setIconSize(QSize(16, 16))
                edit_icon = os.path.join(settings.images_dir, 'edit_16px_icon.png')
                self.button_edit_subvolume.setIcon(QIcon(edit_icon))
                self.button_edit_subvolume.setIconSize(QSize(16, 16))
                self.button_delete_subvolume.setIcon(QIcon(remove_icon))
                self.button_delete_subvolume.setIconSize(QSize(16, 16))
                self.refresh_subvolume_buttons()

                # Displaying logo within About tab
                self.label_logo.setPixmap(QPixmap(buttermanager_icon))

                # Button events
                self.combobox_filesystem.currentTextChanged.connect(self.on_combobox_filesystem_changed)
                self.button_balance.clicked.connect(self.balance_filesystem)
                self.button_upgrade_system.clicked.connect(partial(self.upgrade_system, True))
                self.button_upgrade_system_without_snapshots.clicked.connect(partial(self.upgrade_system, False))
                self.button_fa_take_snapshot.clicked.connect(self.take_snapshot)
                self.button_close_terminal.clicked.connect(self.close_terminal)
                self.button_save_log.clicked.connect(self.save_log)
                self.button_take_snapshot.clicked.connect(self.take_snapshot)
                self.button_delete_snapshot.clicked.connect(self.delete_snapshots)
                self.button_diff.clicked.connect(self.find_diffs)
                self.button_folder.clicked.connect(self.open_file_explorer)
                self.button_delete_log.clicked.connect(self.delete_logs)
                self.button_view_log.clicked.connect(self.view_log)
                self.checkbox_edit_dont_remove_snapshots.clicked.connect(self.dont_remove_snapshots)
                self.checkbox_snap.clicked.connect(self.include_snap)
                self.checkbox_flatpak.clicked.connect(self.include_flatpak)
                self.checkbox_aur.clicked.connect(self.include_aur)
                self.checkbox_log.clicked.connect(self.include_log)
                self.checkbox_startup.clicked.connect(self.include_startup)
                self.checkbox_grub_btrfs.clicked.connect(self.include_grub_btrfs)
                self.spinbox_font_size_increment.valueChanged.connect(self.change_font_size_increment)
                self.button_add_subvolume.clicked.connect(self.add_subvolume)
                self.button_edit_subvolume.clicked.connect(self.edit_subvolume)
                self.button_save_subvolume.clicked.connect(self.save_subvolume)
                self.button_delete_subvolume.clicked.connect(self.delete_subvolume)
                self.combobox_subvolumes.currentTextChanged.connect(self.on_combobox_subvolumes_changed)
                self.button_github.clicked.connect(self.go_to_github)
                self.button_wiki.clicked.connect(self.go_to_wiki)
                self.button_regenerate_grub.clicked.connect(self.regenerate_grub)

                # If no subvolumes are defined, warning the user
                if len(settings.subvolumes) == 0:
                    info_dialog = windows.GeneralInfoWindow(self, "Warning: You don't have any subvolumes "
                                                                         "added.\n"
                                                                         "If you upgrade the filesystem, no snapshots "
                                                                         "will\n"
                                                                         "be created. If you want to create "
                                                                         "automatically\n"
                                                                         "snapshots during the upgrading process, "
                                                                         "go to\n"
                                                                         "Settings and Add a subvolume.")
                    info_dialog.show()

                # If everything goes right, the main window is displayed
                self.show()

                # Checks for root snapshot mounted
                root_snapshot_default = self.__root_snapshot_checker.check_root_snapshot()
                if root_snapshot_default:
                    # Show the updates window only if the user wants to and if there are updates
                    self.check_updates()
                else:
                    consolidate_window = self.__root_snapshot_checker.open_consolidate_snapshot_window()
                    # Hiding the main window and showing the consolidate window in order to proceed
                    self.hide()
                    consolidate_window.show()
                    consolidation = consolidate_window.exec_()
                    if consolidation == 1:
                        # User chose Ok button to consolidate root snapshot and the process finished successfully
                        info_dialog = windows.ProblemsFoundWindow(self,
                                                                         "The snapshot you choose to boot the system \n"
                                                                         "has been consolidated as the default root \n"
                                                                         "snapshot. Please, reboot the system now.")
                        info_dialog.show()
                    elif consolidation == 2:
                        # User chose Ok button to consolidate root snapshot and the process didn't finish
                        # successfully
                        info_dialog = windows.ProblemsFoundWindow(self,
                                                                         "Error trying to substitute the root's path \n"
                                                                         "in fstab with the path of the new snapshot \n"
                                                                         "created")
                        info_dialog.show()
                    elif consolidation == 3:
                        # User chose Ok button to consolidate root snapshot and the process didn't finish
                        # successfully
                        info_dialog = windows.ProblemsFoundWindow(self,
                                                                         "Error removing root snapshot because it is \n"
                                                                         "not empty and there are subvolumes \n"
                                                                         "within it. The consolidation process \n"
                                                                         "couldn't be done.")
                        info_dialog.show()
                    else:
                        # User chose Cancel button so the application must be closed
                        info_dialog = windows.ProblemsFoundWindow(self,
                                                                         "In order to avoid problems, ButterManager \n"
                                                                         "cannot execute any operations under \n"
                                                                         "a non default root snapshot so it will be "
                                                                         "closed.")
                        self.close()
                        info_dialog.show()
            else:
                self.__logger.info("The application couldn't start normally. No BTRFS file system found.")

                info_dialog = windows.ProblemsFoundWindow(self, "No BTRFS file system found. \n"
                                                                       "The application will be closed.")
                info_dialog.show()

        except exception.NoCommandFound:
            self.__logger.info("The application couldn't start normally. There are some programs needed that are not "
                               "installed.")
            self.__logger.info("Please, install these programs and start ButterManager again.")

            info_dialog = windows.ProblemsFoundWindow(self, "These programs need to be installed for \n"
                                                                   "the proper functioning of ButterManager:\n"
                                                                   "btrfs, findmnt.\n")
            info_dialog.show()

    def check_updates(self):
        """Creates the updates checker that will start in another thread and check system updates.

        """
        self.__updates_checker = upgrader.UpdatesChecker()
        self.__updates_checker.show_updates_window.connect(self.show_updates_window)
        self.__updates_checker.start()

    def show_updates_window(self, command_line_output):
        """ Shows a new window with all the packages to  be updated.

        Once the updates_checker knows all the packages that need to be updated, a new
        UpdatesWindow will be opened from the main GUI thread.

        Arguments:
            command_line_output (list(:obj:`str`)): Packages to be updated. One per line.
        """
        updates_window = windows.UpdatesWindow(self, command_line_output)
        updates_window.upgrade_system.connect(self.upgrade_system)
        updates_window.upgrade_system_without_snanpshots.connect(partial(self.upgrade_system, False))
        updates_window.show()

    def balance_filesystem(self):
        """Runs the balance method.

        """
        self.__balancer = filesystem.BalanceManager(self.__current_filesystem.data_percentage,
                                                               self.__current_filesystem.metadata_percentage,
                                                               self.__current_filesystem.mounted_points[0])
        self.__balancer.show_one_window.connect(self.manage_window)
        # Connecting the signal emitted by the balancer with this slot
        self.__balancer.refresh_filesystem_statistics.connect(self.refresh_filesystem_statistics)
        self.__balancer.start()

    def manage_window(self, hide):
        """Shows or hide the main window

        If some important operation (like, f.e. balancing the current filesystem) is being done, then
        the main window should be hidden in order to avoid the user click on any other button and run
        another operation until the current is finished.

        Arguments:
            hide (boolean): Hide or show the main window.
        """
        if hide:
            self.hide()
        else:
            self.show()

    def refresh_filesystem_statistics(self):
        """Refresh current filesystem statistics in the GUI.

        """
        # Calculating new values for the current filesystem
        self.__current_filesystem = filesystem.Filesystem(self.__current_filesystem_uuid)
        # Displaying all the info related to the current filesystem
        self.fill_filesystem_info(self.__current_filesystem)

    def fill_filesystem_info(self, filesystem):
        """Fills filesystem information in the GUI.

        Arguments:
            filesystem (obj: Filesystem): Filesystem.
        """
        tooltip = "More info about the filesystem: \n \n" \
                  "Devices: {devices} \n" \
                  "Mounted points: {mounted_points}".format(devices=filesystem.devices,
                                                            mounted_points=filesystem.mounted_points)
        self.label_filesystem_info_more.setToolTip(tooltip)
        self.label_filesystem_info_more.setCursor(QCursor(Qt.WhatsThisCursor))
        self.label_filesystem_size_value.setText(filesystem.total_size)
        self.label_filesystem_allocated_value.setText(filesystem.total_allocated)
        self.progressbar_data.setValue(filesystem.data_percentage)
        self.progressbar_metadata.setValue(filesystem.metadata_percentage)
        # self.progressbar_system.setValue(filesystem.system_percentage)

        # Showing labels
        self.show_space_labels()

    def upgrade_system(self, snapshots=True):
        """Runs the system upgrade operation.

        Arguments:
            snapshots (boolean): Create and delete snapshots when the upgrading process is executed.
        """
        # Showing terminal and buttons
        self.button_close_terminal.show()
        # Save log button will only be displayed when the logs are
        # not saved automatically
        if settings.save_log == 0:
            self.button_save_log.show()
        else:
            self.button_save_log.hide()
        self.text_edit_console.show()

        # Checking if there is any subvolume defined by the user
        if len(settings.subvolumes) == 0:
            snapshots = False

        # Gathering user settings
        include_aur = False
        if settings.user_os == utils.OS_ARCH:
            include_aur = self.checkbox_aur.isChecked()
        include_snap = False
        if utils.exist_program(SNAP_COMMAND):
            include_snap = self.checkbox_snap.isChecked()
        include_flatpak = False
        if utils.exist_program(FLATPAK_COMMAND):
            include_flatpak = self.checkbox_flatpak.isChecked()

        # Upgrading the system
        self.__upgrader = upgrader.Upgrader(include_aur, include_snap, include_flatpak, snapshots)
        # Connecting the signal emitted by the upgrader with this slot
        self.__upgrader.disable_buttons.connect(self.__disable_buttons)
        # Connecting the signal emitted by the upgrader with this slot
        self.__upgrader.enable_buttons.connect(self.__enable_buttons)
        # Connecting the signal emitted by the upgrader with this slot
        # Depending on the decision to save or not the logs, the signal
        # will be connected to a different slot
        save_log = self.checkbox_log.isChecked()
        if save_log:
            # Saving log if it is needed
            self.__upgrader.refresh_gui.connect(self.save_log_refresh_gui)
        else:
            self.__upgrader.refresh_gui.connect(self.refresh_gui)

        self.__upgrader.start()

    def close_terminal(self):
        """Closes terminal.

        It will restore the proper windows size

        """
        # Hiding terminal and buttons
        self.button_close_terminal.hide()
        self.button_save_log.hide()
        self.text_edit_console.hide()

    def save_log(self):
        """Saves the current content of the terminal into a file.

        """
        try:
            current_date = time.strftime('%Y%m%d')
            index = 0
            log_name = "{current_date}-{index}.txt".format(current_date=current_date, index=str(index))
            log_path = os.path.join(settings.logs_path, log_name)
            while os.path.exists(log_path):
                index += 1
                log_name = "{current_date}-{index}.txt".format(current_date=current_date, index=str(index))
                log_path = os.path.join(settings.logs_path, log_name)

            # Gets the content and saves it
            log = self.text_edit_console.toPlainText()
            with open(log_path, 'a') as file:
                file.write(log)
        except Exception as exception:
            self.__logger.info("Error saving the log: " + str(exception))

    def __disable_buttons(self):
        """Disables all the buttons of the GUI.

        """
        self.combobox_filesystem.setEnabled(False)
        self.button_balance.setEnabled(False)
        self.button_upgrade_system.setEnabled(False)
        self.button_upgrade_system_without_snapshots.setEnabled(False)
        self.button_fa_take_snapshot.setEnabled(False)
        self.button_close_terminal.setEnabled(False)
        self.list_snapshots.setEnabled(False)
        self.list_logs.setEnabled(False)
        self.combobox_subvolumes.setEnabled(False)
        self.checkbox_startup.setEnabled(False)
        self.checkbox_log.setEnabled(False)
        self.checkbox_snap.setEnabled(False)
        self.checkbox_aur.setEnabled(False)
        self.checkbox_grub_btrfs.setEnabled(False)
        self.checkbox_flatpak.setEnabled(False)
        self.spinbox_font_size_increment.setEnabled(False)
        self.button_take_snapshot.setEnabled(False)
        self.button_delete_snapshot.setEnabled(False)
        self.button_diff.setEnabled(False)
        self.button_folder.setEnabled(False)
        self.button_add_subvolume.setEnabled(False)
        self.button_delete_subvolume.setEnabled(False)
        self.button_edit_subvolume.setEnabled(False)
        self.button_save_subvolume.setEnabled(False)
        self.button_view_log.setEnabled(False)
        self.button_delete_log.setEnabled(False)
        self.button_regenerate_grub.setEnabled(False)

    def __enable_buttons(self):
        """Enable all the buttons of the GUI.

        """
        self.combobox_filesystem.setEnabled(True)
        self.button_balance.setEnabled(True)
        self.button_upgrade_system.setEnabled(True)
        self.button_upgrade_system_without_snapshots.setEnabled(True)
        self.button_fa_take_snapshot.setEnabled(True)
        self.button_close_terminal.setEnabled(True)
        self.list_snapshots.setEnabled(True)
        self.list_logs.setEnabled(True)
        self.combobox_subvolumes.setEnabled(True)
        self.checkbox_startup.setEnabled(True)
        self.checkbox_log.setEnabled(True)
        self.checkbox_snap.setEnabled(True)
        self.checkbox_aur.setEnabled(True)
        self.checkbox_grub_btrfs.setEnabled(True)
        self.checkbox_flatpak.setEnabled(True)
        self.spinbox_font_size_increment.setEnabled(True)
        self.button_take_snapshot.setEnabled(True)
        self.button_delete_snapshot.setEnabled(True)
        self.button_diff.setEnabled(True)
        self.button_folder.setEnabled(True)
        self.button_add_subvolume.setEnabled(True)
        self.button_delete_subvolume.setEnabled(True)
        self.button_edit_subvolume.setEnabled(True)
        self.button_save_subvolume.setEnabled(True)
        self.button_view_log.setEnabled(True)
        self.button_delete_log.setEnabled(True)
        self.button_regenerate_grub.setEnabled(True)

    def take_snapshot(self):
        """Takes a BTRFS subvolume snapshot.

        """
        snapshot_window = windows.SnapshotWindow(self)
        # Connecting the signals emitted by the snapshot window with this slot
        snapshot_window.refresh_gui.connect(self.refresh_gui)
        snapshot_window.enable_buttons.connect(self.__enable_buttons)
        # Disabling buttons
        self.__disable_buttons()
        # Displaying snapshot window
        snapshot_window.show()
        # Enabling buttons
        self.__disable_buttons()

    def delete_snapshots(self):
        """Deletes one or several BTRFS subvolume snapshots.

        """
        # Disabling buttons
        self.__disable_buttons()

        # Waiting 10 msec in order to let self.__disable_buttons to take effect
        QtTest.QTest.qWait(10)

        snapshots_to_delete = self.list_snapshots.selectedItems()
        for snap in snapshots_to_delete:
            snapshot.delete_specific_snapshot(snap.text())

        # Refreshing GUI
        self.refresh_gui()

        # Enabling buttons
        self.__enable_buttons()

    def find_diffs(self):
        """Find differences between the snapshot selected and the current state of the subvolume related to it.

        """
        snapshot_to_diff = self.list_snapshots.selectedItems()
        if len(snapshot_to_diff) != 1:
            # Only one snapshot can be selected
            info_dialog = windows.GeneralInfoWindow(self, "Please, select one (and only one) snapshot\n"
                                                                 "in order to find the differences between\n"
                                                                 "it and the current subvolume.")
            info_dialog.show()
        else:
            # Disabling buttons
            self.__disable_buttons()

            # Waiting 10 msec in order to let self.__disable_buttons to take effect
            QtTest.QTest.qWait(10)

            # The user has to select the kind of operation
            diff_window = windows.DiffWindow()

            # Hidding the main window and showing the diff window in order to proceed
            self.hide()

            diff_window.show()
            diff_process = diff_window.exec_()
            if diff_process == 1:
                # A full operation will be done
                self.__differentiator = snapshot.Differentiator(
                    snapshot_to_diff[0].text(),
                    snapshot.Differentiator.OPERATION_FULL)
            elif diff_process == 2:
                # A partial operation will be done
                self.__differentiator = snapshot.Differentiator(
                    snapshot_to_diff[0].text(),
                    snapshot.Differentiator.OPERATION_PARTIAL)

            self.__differentiator.show_one_window.connect(self.manage_window)
            self.__differentiator.start()

            # Refreshing GUI
            self.refresh_gui()

            # Enabling buttons
            self.__enable_buttons()

            # Showing main window again
            self.show()

    def open_file_explorer(self):
        """Opens a file explorer to see all the files within a snapshot.

        """
        snapshots_selected = self.list_snapshots.selectedItems()
        if len(snapshots_selected) != 1:
            # Only one snapshot can be selected
            info_dialog = windows.GeneralInfoWindow(self, "Please, select one (and only one) snapshot \n"
                                                                 "in order to open the file explorer.")
            info_dialog.show()
        else:
            subprocess.call(['xdg-open', snapshots_selected[0].text()])

    def delete_logs(self):
        """Deletes one or several logs.

        """
        logs_to_delete = self.list_logs.selectedItems()
        for log in logs_to_delete:
            os.remove(os.path.join(settings.logs_path, log.text()))

        # Refreshing GUI
        self.refresh_gui()

    def view_log(self):
        """Opens the log in a new window to display it.

        """
        logs_to_view = self.list_logs.selectedItems()
        for log in logs_to_view:
            log_window = windows.LogViewWindow(self, os.path.join(settings.logs_path, log.text()))
            log_window.show()

    def add_subvolume(self):
        """Adds a new subvolume to be managed by the application.

        """
        subvolume_window = windows.SubvolumeWindow(self)
        # Connecting the signal emitted by the subvolume window with this slot
        subvolume_window.refresh_gui.connect(self.refresh_gui)
        # Displaying snapshot window
        subvolume_window.show()

    def dont_remove_snapshots(self):
        """Actions when user checks don't remove snapshots.
        """
        if self.checkbox_edit_dont_remove_snapshots.isChecked():
            self.spinbox_edit_snapshots_to_keep.hide()
        else:
            self.spinbox_edit_snapshots_to_keep.show()
            self.spinbox_edit_snapshots_to_keep.setValue(1)

    def include_snap(self):
        """Actions when user checks include snap packages.

        """
        # Storing value in settings
        if self.checkbox_snap.isChecked():
            settings.properties_manager.set_property('snap_packages', 1)
        else:
            settings.properties_manager.set_property('snap_packages', 0)

    def include_flatpak(self):
        """Actions when user checks include flatpak packages.

        """
        # Storing value in settings
        if self.checkbox_flatpak.isChecked():
            settings.properties_manager.set_property('flatpak_packages', 1)
        else:
            settings.properties_manager.set_property('flatpak_packages', 0)

    def include_aur(self):
        """Actions when user checks include AUR packages.

        """
        # Storing value in settings
        if self.checkbox_aur.isChecked():
            settings.properties_manager.set_property('aur_repository', 1)
        else:
            settings.properties_manager.set_property('aur_repository', 0)

    def include_log(self):
        """Actions when user checks include log.

        """
        # Storing value in settings
        if self.checkbox_log.isChecked():
            settings.properties_manager.set_property('save_log', 1)
        else:
            settings.properties_manager.set_property('save_log', 0)

    def include_startup(self):
        """Actions when user checks check updates at startup.

        """
        # Storing value in settings
        if self.checkbox_startup.isChecked():
            settings.properties_manager.set_property('check_at_startup', 1)
        else:
            settings.properties_manager.set_property('check_at_startup', 0)

    def include_grub_btrfs(self):
        """Actions when user checks boot the system from GRUB using snapshots.

        """
        # Storing value in settings
        if self.checkbox_grub_btrfs.isChecked():
            settings.properties_manager.set_property('grub_btrfs', 1)
            self.button_regenerate_grub.show()
        else:
            settings.properties_manager.set_property('grub_btrfs', 0)
            self.button_regenerate_grub.hide()

    def change_font_size_increment(self):
        """Actions when user increases or decreases the UI font size.

        """
        # Storing value in settings
        settings.properties_manager.set_property('font_size_increment', self.spinbox_font_size_increment.value())

        # Changing UI font size dynamically
        utils.scale_fonts(self.__ui_elements)

    def on_combobox_filesystem_changed(self):
        self.__current_filesystem_uuid = self.combobox_filesystem.currentText()
        self.refresh_filesystem_statistics()

    def on_combobox_subvolumes_changed(self):
        current_subvolume = self.combobox_subvolumes.currentText()
        if current_subvolume:
            self.line_edit_snapshot_where.setText(settings.subvolumes[current_subvolume].subvolume_dest)
            self.line_edit_snapshot_prefix.setText(settings.subvolumes[current_subvolume].snapshot_name)

            snapshots_to_keep = int(settings.subvolumes[current_subvolume].snapshots_to_keep)

            if snapshots_to_keep == -1:
                # Enable Don't remove snapshots
                self.checkbox_edit_dont_remove_snapshots.show()
                self.checkbox_edit_dont_remove_snapshots.setChecked(True)
                self.checkbox_edit_dont_remove_snapshots.setDisabled(True)
                # Hide snapshots to keep
                self.spinbox_edit_snapshots_to_keep.hide()
            else:
                # Enable snapshots to keep
                self.spinbox_edit_snapshots_to_keep.show()
                self.spinbox_edit_snapshots_to_keep.setDisabled(True)
                self.spinbox_edit_snapshots_to_keep.setValue(snapshots_to_keep)
                # Show Don't remove snapshots and disable it
                self.checkbox_edit_dont_remove_snapshots.show()
                self.checkbox_edit_dont_remove_snapshots.setDisabled(True)

    def edit_subvolume(self):
        """Actions when user wants to edit a defined subvolume.

        """
        # Buttons management
        self.button_save_subvolume.show()
        self.button_edit_subvolume.hide()
        self.button_delete_subvolume.hide()
        self.line_edit_snapshot_where.setDisabled(False)
        self.line_edit_snapshot_prefix.setDisabled(False)
        self.spinbox_edit_snapshots_to_keep.setDisabled(False)
        self.checkbox_edit_dont_remove_snapshots.setDisabled(False)

    def save_subvolume(self):
        """Actions when user finishes to edit a subvolume.

        """
        # Buttons management
        self.button_save_subvolume.hide()
        self.button_edit_subvolume.show()
        self.button_delete_subvolume.show()
        self.line_edit_snapshot_where.setDisabled(True)
        self.line_edit_snapshot_prefix.setDisabled(True)
        self.spinbox_edit_snapshots_to_keep.setDisabled(True)
        self.checkbox_edit_dont_remove_snapshots.setDisabled(True)

        # Storing the modified values
        new_snapshot_where = self.line_edit_snapshot_where.text()
        new_snapshot_prefix = self.line_edit_snapshot_prefix.text()
        subvolume_selected = self.combobox_subvolumes.currentText()
        snapshots_to_keep = -1
        if not self.checkbox_edit_dont_remove_snapshots.isChecked():
            snapshots_to_keep = self.spinbox_edit_snapshots_to_keep.value()

        settings.properties_manager.set_subvolume(subvolume_selected, new_snapshot_where, new_snapshot_prefix,
                                                  snapshots_to_keep)

        # Refreshing components
        self.refresh_gui()

    def delete_subvolume(self):
        """Actions when user wants to delete a subvolume.

        """
        # Storing the modified values
        subvolume_selected = self.combobox_subvolumes.currentText()
        settings.properties_manager.set_subvolume(subvolume_selected, None, None, None)

        # Refreshing components
        self.refresh_gui()

    def go_to_github(self):
        """Actions when user clicks on github button.

        """
        url = QUrl('https://github.com/egara/buttermanager')
        QDesktopServices.openUrl(url)

    def go_to_wiki(self):
        """Actions when user clicks on github button.

        """
        url = QUrl('https://github.com/egara/buttermanager/wiki')
        QDesktopServices.openUrl(url)

    def fill_snapshots(self):
        """Fills snapshots information in the GUI.

        """
        # Resetting snapshots in the GUI
        # Clearing the list
        self.list_snapshots.clear()

        # Adding the snapshots to the list
        snapshots = []
        self.list_snapshots.addItems(snapshots)
        # Loading the snapshots detected
        for subvolume in settings.subvolumes:
            snapshots.extend(settings.subvolumes[subvolume].get_all_snapshots_with_the_same_name())
        self.list_snapshots.addItems(snapshots)

    def fill_logs(self):
        """Fills logs in the GUI.

        """
        # Resetting logs in the GUI
        # Clearing the list
        self.list_logs.clear()

        # Adding the logs to the list
        logs = os.listdir(settings.logs_path)
        self.list_logs.addItems(logs)

    def fill_subvolumes(self):
        """Fills subvolumes in the GUI.

        """
        # Resetting combo
        self.combobox_subvolumes.clear()
        # Adding the new subvolumes to the combobox
        list_subvolumes = []
        if len(settings.subvolumes) > 0:
            for subvolume in settings.subvolumes:
                list_subvolumes.append(subvolume)
            self.combobox_subvolumes.addItems(list_subvolumes)
            self.line_edit_snapshot_where.setDisabled(True)
            self.line_edit_snapshot_where.setText(settings.subvolumes[list_subvolumes[0]].subvolume_dest)
            self.line_edit_snapshot_prefix.setDisabled(True)
            self.line_edit_snapshot_prefix.setText(settings.subvolumes[list_subvolumes[0]].snapshot_name)

            snapshots_to_keep = int(settings.subvolumes[list_subvolumes[0]].snapshots_to_keep)

            if snapshots_to_keep == -1:
                # Enable Don't remove snapshots
                self.checkbox_edit_dont_remove_snapshots.show()
                self.checkbox_edit_dont_remove_snapshots.setChecked(True)
                self.checkbox_edit_dont_remove_snapshots.setDisabled(True)
                # Hide snapshots to keep
                self.spinbox_edit_snapshots_to_keep.hide()
            else:
                # Enable snapshots to keep
                self.spinbox_edit_snapshots_to_keep.show()
                self.spinbox_edit_snapshots_to_keep.setDisabled(True)
                self.spinbox_edit_snapshots_to_keep.setValue(snapshots_to_keep)
                # Show Don't remove snapshots and disable it
                self.checkbox_edit_dont_remove_snapshots.show()
                self.checkbox_edit_dont_remove_snapshots.setDisabled(True)

    def refresh_subvolume_buttons(self):
        """Shows or hide subvolume buttons in the GUI.

        """
        # They will be shown only if some subvolume is defined by the user
        if len(settings.subvolumes) > 0:
            self.button_save_subvolume.hide()
            self.button_edit_subvolume.show()
            self.button_delete_subvolume.show()
            self.combobox_subvolumes.show()
            self.line_edit_snapshot_where.show()
            self.label_settings_subvolumes_where.show()
            self.line_edit_snapshot_prefix.show()
            self.label_settings_subvolumes_prefix.show()
        else:
            self.label_existing_subvolumes.hide()
            self.button_save_subvolume.hide()
            self.button_edit_subvolume.hide()
            self.button_delete_subvolume.hide()
            self.combobox_subvolumes.hide()
            self.line_edit_snapshot_where.hide()
            self.label_settings_subvolumes_where.hide()
            self.line_edit_snapshot_prefix.hide()
            self.label_settings_subvolumes_prefix.hide()

    def refresh_gui(self):
        """Refresh all the GUI elements.

        """
        self.refresh_filesystem_statistics()
        self.fill_snapshots()
        self.fill_logs()
        self.fill_subvolumes()
        self.refresh_subvolume_buttons()
        self.show_space_labels()

    def save_log_refresh_gui(self):
        """Save log and refresh all the GUI elements.

        """
        self.save_log()
        self.refresh_gui()

    def show_space_labels(self):
        """Shows the appropiate labels related to the space left of the system.

        """
        filesystem_space_pertentage = utils.get_percentage(self.__current_filesystem.total_size,
                                                                self.__current_filesystem.total_allocated)
        if filesystem_space_pertentage <= 70:
            self.label_space_ok.show()
            self.label_space_danger.hide()
            self.label_space_ko.hide()
        elif filesystem_space_pertentage > 70 & filesystem_space_pertentage <= 85:
            self.label_space_ok.hide()
            self.label_space_danger.show()
            self.label_space_ko.hide()
        else:
            self.label_space_ok.hide()
            self.label_space_danger.hide()
            self.label_space_ko.show()

        if self.__current_filesystem.data_percentage <= 85:
            self.label_space_data_danger.show()
        else:
            self.label_space_data_danger.hide()

    def regenerate_grub(self):
        """Regenerates GRUB menu to include the snapshots taken as bootable entries.

        """
        # Disabling buttons
        self.__disable_buttons()

        # Waiting 100 msec in order to let self.__disable_buttons to take effect
        QtTest.QTest.qWait(100)

        # Run grub-btrfs in order to regenerate GRUB entries
        utils.execute_command(snapshot.GRUB_BTRFS_COMMAND, console=True, root=True)

        # Refreshing GUI
        self.refresh_gui()

        # Enabling buttons
        self.__enable_buttons()

        # Displaying info
        info_dialog = windows.GeneralInfoWindow(self, "GRUB menu has been regenerated.")
        info_dialog.show()


================================================
FILE: buttermanager/buttermanager/exception/__init__.py
================================================
#Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>
#
# This file is part of buttermanager.
#
# 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, version 3 of the License.
#
# 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/>.

================================================
FILE: buttermanager/buttermanager/exception/exception.py
================================================
# -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>
#
# This file is part of buttermanager.
#
# 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, version 3 of the License.
#
# 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/>.

"""This module gathers all the custom exceptions rised in buttermanager application.

"""


# Classes
class NoCommandFound(Exception):
    """Exception raised when a needed program is not installed in the system.

    """
    pass


class BtrfsSnapshotDeletion(Exception):
    """Exception raised when a subvolume can't be deleted because it is not empty.
    A subvolume is not empty when there are other subvolumes within it

    """
    def __init__(self, *args):
        if args:
            self.message = args[0]
        else:
            self.message = None

    def __str__(self):
        print('calling str')
        if self.message:
            return 'MyCustomError, {0} '.format(self.message)
        else:
            return 'MyCustomError has been raised'


================================================
FILE: buttermanager/buttermanager/filesystem/__init__.py
================================================
# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>
#
# This file is part of buttermanager.
#
# 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, version 3 of the License.
#
# 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/>.


================================================
FILE: buttermanager/buttermanager/filesystem/filesystem.py
================================================
# -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>
#
# This file is part of buttermanager.
#
# 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, version 3 of the License.
#
# 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/>.

"""This module gathers all the operations related to BTRFS filesystems.

It provides also Filesystem class.
"""
from ..exception import exception
from ..window import windows
import sys
from ..util import utils
from PyQt5.QtCore import QThread, pyqtSignal

# Constants
DEVID = "devid"
LABEL = "Label"
UUID = "uuid:"
DEVICE_SIZE = "Device size:"
DEVICE_ALLOCATED = "Device allocated:"
DATA = "Data,"
METADATA = "Metadata,"
SYSTEM = "System,"
SIZE = "Size:"
USED = "Used:"
BTRFS_SHOW_COMMAND = "sudo -S btrfs filesystem show"
FINDMT_COMMAND = "sudo -S findmnt -nt btrfs"
BTRFS_USAGE_COMMAND = "sudo -S btrfs filesystem usage"
BTRFS_BALANCE_COMMAND = "sudo -S btrfs balance start"
BTRFS_BALANCE_DATA_USAGE_FILTER = "dusage"
BTRFS_BALANCE_METADATA_USAGE_FILTER = "musage"


# Classes
class Filesystem:
    """BTRFS Filesystem.

    """
    # Constructor
    def __init__(self, uuid):

        self.__uuid = uuid
        self.__devices = self.__get_devices()
        self.__mounted_points = self.__get_mounted_points()
        filesystem_info = self.__get_filesystem_info(self.mounted_points[0])
        self.__total_size = filesystem_info['total_size']
        self.__total_allocated = filesystem_info['total_allocated']
        self.__data_size = filesystem_info['data_size']
        self.__data_used = filesystem_info['data_used']
        self.__data_percentage = filesystem_info['data_percentage']
        self.__metadata_size = filesystem_info['metadata_size']
        self.__metadata_used = filesystem_info['metadata_used']
        self.__metadata_percentage = filesystem_info['metadata_percentage']
        self.__system_size = filesystem_info['system_size']
        self.__system_used = filesystem_info['system_used']
        self.__system_percentage = filesystem_info['system_percentage']

    # Private attributes
    # UUID
    @property
    def uuid(self):
        return self.__uuid

    # Devices
    @property
    def devices(self):
        return self.__devices

    # Mounted points
    @property
    def mounted_points(self):
        return self.__mounted_points

    # Total size
    @property
    def total_size(self):
        return self.__total_size

    # Total allocated
    @property
    def total_allocated(self):
        return self.__total_allocated

    # Data size
    @property
    def data_size(self):
        return self.__data_size

    # Data used
    @property
    def data_used(self):
        return self.__data_used

    # Data percentage
    @property
    def data_percentage(self):
        return self.__data_percentage

    # Metadata size
    @property
    def metadata_size(self):
        return self.__metadata_size

    # Metadata used
    @property
    def metadata_used(self):
        return self.__metadata_used

    # Metadata percentage
    @property
    def metadata_percentage(self):
        return self.__metadata_percentage

    # System size
    @property
    def system_size(self):
        return self.__system_size

    # System used
    @property
    def system_used(self):
        return self.__system_used

    # System percentage
    @property
    def system_percentage(self):
        return self.__system_percentage

    # Methods
    # Private methods
    def __get_devices(self):
        """Retrieves all the devices which the BTRFS filesystem is composed.

        Returns:
            list (:obj:`list` of :obj:`str`): devices.
        """
        try:
            devices = []
            commandline_output = utils.execute_command(BTRFS_SHOW_COMMAND, root=True)
            filesystem_found = False

            for line in commandline_output.split("\n"):
                if UUID in line:
                    if filesystem_found:
                        break
                    else:
                        if self.uuid in line:
                            filesystem_found = True
                            continue

                if filesystem_found:
                    # The loop is inside the chosen BTRFS filesystem
                    # It is necessary to find devid to retrieve all the filesystem paths
                    if DEVID in line:
                        path_init = line.find('/')
                        # The device path is appended to the list
                        devices.append(line[path_init:len(line)])

            return devices

        except exception.NoCommandFound as no_command_found_exception:
            raise no_command_found_exception

    def __get_mounted_device(self):
        """Retrieves the device tha contains the BTRFS filesystem and it is mounted.

        Returns:
            string: device path.
        """
        try:
            mounted_device = ''
            commandline_output = utils.execute_command(FINDMT_COMMAND)
            for device in self.devices:
                if device in commandline_output:
                    mounted_device = device
                    break

            return mounted_device

        except exception.NoCommandFound as no_command_found_exception:
            raise no_command_found_exception

    def __get_mounted_points(self):
        """Retrieves all the mounted points of the BTRFS filesystem.

        Returns:
            list (:obj:`list` of :obj:`str`): mounted points.
        """
        try:
            mounted_points = []
            device = self.__get_mounted_device()
            command = "{command} {device}".format(command=FINDMT_COMMAND, device=device)
            commandline_output = utils.execute_command(command)

            for line in commandline_output.split("\n"):
                if len(line) > 0:
                    mounted_points.append(line.split(" ")[0].strip())

            return mounted_points

        except exception.NoCommandFound as no_command_found_exception:
            raise no_command_found_exception

    def __get_filesystem_info(self, mounted_point):
        """Retrieves all the information of the BTRFS filesystem.

        Returns:
            dictionary (key=:obj:'string', value=:obj:'str' or obj:'int'): all the info. The keys of the dictionary
            will be:
                - total_size: Device size
                - total_allocated: Device allocated
                - data_size: Data size
                - data_used: Data used
                - data_percentage: Percentage of data used
                - metadata_size: Metadata size
                - metadata_used: Metadata used
                - metadata_percentage: Percentage of metadata used
                - system_size: System size
                - system_used: System used
                - system_percentage: Percentage of system used
        """
        filesystem_info = {'total_size': '0', 'total_allocated': '0',
                           'data_size': '0', 'data_used': '0', 'data_percentage': 0,
                           'metadata_size': '0', 'metadata_used': '0', 'metadata_percentage': 0,
                           'system_size': '0', 'system_used': '0', 'system_percentage': 0}
        command = "{command} {point}".format(command=BTRFS_USAGE_COMMAND, point=mounted_point)
        commandline_output = utils.execute_command(command, root=True)

        for line in commandline_output.split("\n"):
            if DEVICE_SIZE in line:
                filesystem_info['total_size'] = line.split(DEVICE_SIZE)[1].strip()
            elif DEVICE_ALLOCATED in line:
                filesystem_info['total_allocated'] = line.split(DEVICE_ALLOCATED)[1].strip()
            elif DATA in line:
                data_size = line.split(SIZE)[1].split(',')[0].strip()
                filesystem_info['data_size'] = data_size
                data_used = line.split(USED)[1].strip()
                if '(' in data_used:
                    # New versions of btrfs-progs already include the percentage
                    data_used = data_used.split()[0].strip()
                filesystem_info['data_used'] = data_used
                filesystem_info['data_percentage'] = utils.get_percentage(filesystem_info['data_size'],
                                                                               filesystem_info['data_used'])
            elif METADATA in line:
                metadata_size = line.split(SIZE)[1].split(',')[0].strip()
                filesystem_info['metadata_size'] = metadata_size
                metadata_used = line.split(USED)[1].strip()
                if '(' in metadata_used:
                    # New versions of btrfs-progs already include the percentage
                    metadata_used = metadata_used.split()[0].strip()
                filesystem_info['metadata_used'] = metadata_used
                filesystem_info['metadata_percentage'] = utils.get_percentage(filesystem_info['metadata_size'],
                                                                                   filesystem_info['metadata_used'])
            elif SYSTEM in line:
                system_size = line.split(SIZE)[1].split(',')[0].strip()
                filesystem_info['system_size'] = system_size
                filesystem_info['system_used'] = line.split(USED)[1].strip()
                filesystem_info['system_percentage'] = utils.get_percentage(filesystem_info['system_size'],
                                                                                 filesystem_info['system_used'])

        return filesystem_info

    # Public methods
    def __str__(self):
        """Reimplementation of the str method inherited from object class.

        Returns:
            string: String representation of the Filesystem object.
        """
        return "BTRFS Filesystem -> UUID: {0}; Devices: {1}; Mounted Points: {2}".format(self.uuid, self.devices,
                                                                                         self.mounted_points)


# Module's methods
def get_btrfs_filesystems(mounted=True):
    """Retrieves all the BTRFS filesystems.

    Keyword arguments:
        mounted (bool): Only mounted filesystems will be retrieved (default True).

    Returns:
        list (:obj:`list` of :obj:`str`): filesystems UUID.
    """

    filesystems = []
    command = BTRFS_SHOW_COMMAND

    if mounted:
        command += " --mounted"

    commandline_output = utils.execute_command(command, root=True)

    for line in commandline_output.split("\n"):
        if UUID in line:
            # The uuid is appended to the list
            filesystems.append(line.split(UUID)[1].strip())

    return filesystems


def balance_filesystem(filter, percentage, mounted_point):
    """Balances a specific filesystem.

    Arguments:
        filter (string): filter.
        percentage (int): usage filter.
        mounted_point: path to balance.
    """
    # Logger
    logger = utils.Logger(sys.modules['__main__'].__file__).get()
    logger.info("Balancing {mounted_point} using filter {filter} and "
                "percentage {percentage}".format(mounted_point=mounted_point,
                                                 filter=filter,
                                                 percentage=percentage))

    command = "{command} -{filter}={percentage} {mounted_point}".format(command=BTRFS_BALANCE_COMMAND,
                                                                        filter=filter,
                                                                        percentage=percentage,
                                                                        mounted_point=mounted_point)
    logger.info("Command executed {command}".format(command=command))
    commandline_output = utils.execute_command(command, root=True)
    for line in commandline_output.split("\n"):
        logger.info(line)


class BalanceManager(QThread):
    """Independent thread that will run the filesystem balancing process.

    """
    # Attributes
    # pyqtSignal that will be emitted when this class requires to display
    # a single information window on the screen
    show_one_window = pyqtSignal('bool')

    # pyqtSignal that will be emitted when this class requires that main
    # window refreshes current filesystem statistics
    refresh_filesystem_statistics = pyqtSignal()

    # Constructor
    def __init__(self, data_percentage, metadata_percentage, mounted_point):
        QThread.__init__(self)
        self.__data_percentage = data_percentage
        self.__metadata_percentage = metadata_percentage
        self.__mounted_point = mounted_point

    # Methods
    def run(self):
        # Main window will be hidden
        self.on_show_one_window(True)
        info_dialog = windows.InfoWindow(None, "Balancing '{mounted_point}' mounted point. \n"
                                                      "This window will be closed automatically \n"
                                                      "when the operation is done. \n \n"
                                                      "Please wait...".format(mounted_point=self.__mounted_point))
        # Displaying info window
        info_dialog.show()

        # Balances the filesystem
        self.__balance_filesystem()

        # Hiding info window
        info_dialog.hide()

        # Main window will be shown again
        self.on_show_one_window(False)

        # Refreshing current filesystem statistics
        self.on_refresh_filesystem_statistics()

    def __balance_filesystem(self):
        """Wraps all the operations to balance the filesystem.

        """
        # Balancing data
        balance_filesystem(
            BTRFS_BALANCE_DATA_USAGE_FILTER,
            self.__data_percentage,
            self.__mounted_point)
        # Balancing metadata
        balance_filesystem(
            BTRFS_BALANCE_METADATA_USAGE_FILTER,
            self.__metadata_percentage,
            self.__mounted_point)

    def on_show_one_window(self, one_window):
        """Emits a QT Signal to hide or show the rest of application windows.

        Arguments:
            one_window (boolean): Information window should be unique?.
        """
        self.show_one_window.emit(one_window)

    def on_refresh_filesystem_statistics(self):
        """Emits a QT Signal to refresh filesystem statistics in main window.

        """
        self.refresh_filesystem_statistics.emit()


================================================
FILE: buttermanager/buttermanager/filesystem/snapshot.py
================================================
# -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>
#
# This file is part of buttermanager.
#
# 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, version 3 of the License.
#
# 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/>.

"""This module gathers all the operations related to BTRFS snapshots.

It provides also Snapshot class.
"""
from ..exception import exception
from ..util import settings, utils
from ..window import windows
import glob
import os
import shutil
import sys
import subprocess
import time
from PyQt5.QtCore import QThread, pyqtSignal


# Constants
BTRFS_CREATE_SNAPSHOT_R_COMMAND = "sudo -S btrfs subvolume snapshot -r"
BTRFS_CREATE_SNAPSHOT_RW_COMMAND = "sudo -S btrfs subvolume snapshot"
BTRFS_DELETE_SNAPSHOT_COMMAND = "sudo -S btrfs subvolume delete"
BTRFS_FIND_NEW_COMMAND = "sudo -S btrfs subvolume find-new"
GRUB_BTRFS_COMMAND = "sudo -S grub-mkconfig -o /boot/grub/grub.cfg"


# Classes
class Subvolume:
    """BTRFS Snapshot.

    """
    # Constructor
    def __init__(self, subvolume_origin, subvolume_dest, snapshot_name, snapshots_to_keep):
        """ Constructor.

        Arguments:
            subvolume_origin (str): Full path to the subvolume.
            subvolume_dest (str): Full path to the subvolume where all of the subvolumes created from origin are going
            to be stored.
            snapshot_name (str): Prefix for all the subvolumes created from origin
            snapshots_to_keep (str): Number of snapshots to keep for this subvolume
        """
        # Logger
        self.__logger = utils.Logger(self.__class__.__name__).get()
        self.subvolume_origin = subvolume_origin if subvolume_origin[-1] == '/' else subvolume_origin + '/'
        self.subvolume_dest = subvolume_dest if subvolume_dest[-1] == '/' else subvolume_dest + '/'
        self.snapshot_name = snapshot_name
        self.snapshots_to_keep = int(snapshots_to_keep)
        self.__current_date = time.strftime('%Y%m%d')

    # Methods
    # Private methods

    # Public methods
    def create_snapshot(self):
        """Creates a snapshot.

        """
        info_message = "Creating a read-only snapshot of {subvolume_origin} in {subvolume_dest}. " \
                       "Please wait...".format(subvolume_origin=self.subvolume_origin,
                                               subvolume_dest=self.subvolume_dest)
        self.__logger.info(info_message)

        # Checking how many snapshots are with the same name
        snapshot_full_name = "{snapshot_name}-{current_date}".format(snapshot_name=self.snapshot_name,
                                                                     current_date=self.__current_date)
        snapshots_with_same_name = [file for file in os.listdir(self.subvolume_dest) if snapshot_full_name in file]

        # Adding number to the full name
        snapshot_full_name = "{snapshot_full_name}-{number}".format(snapshot_full_name=snapshot_full_name,
                                                                    number=len(snapshots_with_same_name))
        # Checks if grub-btrfs integration is enabled
        if settings.properties_manager.get_property("grub_btrfs"):
            # Checks if /etc/fstab is in subvolume_origin
            fstab_path = self.subvolume_origin + 'etc/fstab'
            if os.path.isfile(fstab_path):
                everything_ok = True
                # /etc/fstab is in the subvolume, so it is necessary to
                # modify it and add the snapshot's name
                # grep -rnw '/etc/fstab' -e "/_active/rootvol"
                # First, it is necessary to obtain the original subvolume
                # for / which is mounted in the system (subvolume_origin_real)
                subvolume_origin_real = None
                command_string = """sudo btrfs subvolume show /"""
                command = [command_string]
                commandline_output = None
                try:
                    commandline_output = subprocess.check_output(command, shell=True)
                except subprocess.CalledProcessError as called_process_error_exception:
                    self.__logger.error("Error retrieving the real and mounted subvolume for / . Reason: " +
                                        str(called_process_error_exception.reason))
                    everything_ok = False
                if everything_ok:
                    commandline_output = commandline_output.decode('utf-8')
                    for line_output in commandline_output.split("\n"):
                        # The original subvolume mounted for / will be always the first line
                        # of the output
                        subvolume_origin_real = line_output
                        break

                    # Creating the snapshot in rw mode
                    command = "{command} {subvolume_origin} {subvolume_dest}{snapshot_full_name}".format(
                        command=BTRFS_CREATE_SNAPSHOT_RW_COMMAND,
                        subvolume_origin=self.subvolume_origin,
                        subvolume_dest=self.subvolume_dest,
                        snapshot_full_name=snapshot_full_name
                    )
                    utils.execute_command(command, console=True, root=True)

                    # Obtaining the real subvolume for the new snapshot created
                    subvolume_snapshot_created_real = None
                    command_string = """sudo btrfs subvolume show {subvolume_dest}{snapshot_full_name}""".format(
                        subvolume_dest=self.subvolume_dest,
                        snapshot_full_name=snapshot_full_name
                    )
                    command = [command_string]
                    commandline_output = None
                    try:
                        commandline_output = subprocess.check_output(command, shell=True)
                    except subprocess.CalledProcessError as called_process_error_exception:
                        self.__logger.error("Error retrieving the real subvolume for snapshot created. Reason: " +
                                            str(called_process_error_exception.reason))

                    commandline_output = commandline_output.decode('utf-8')
                    for line_output in commandline_output.split("\n"):
                        # The original subvolume mounted for / will be always the first line
                        # of the output
                        subvolume_snapshot_created_real = line_output
                        break

                    # Getting the line in fstab where it is necessary to substitute the subvolume which is going to be
                    # mounted as root. It is necessary to discard all the lines with comments in fstab starting with '#'
                    command_string = """grep -rnw '{fstab_path}' -e '{subvolume_origin_real}'""".format(
                        fstab_path=fstab_path, subvolume_origin_real=subvolume_origin_real)
                    command = [command_string]
                    commandline_output = None
                    try:
                        commandline_output = subprocess.check_output(command, shell=True)
                    except subprocess.CalledProcessError:
                        pass
                    commandline_output = commandline_output.decode('utf-8')
                    # line will be the line where grep has matched subvolume_origin_real. All lines commented with '#'
                    # will be discarded
                    line = "0"
                    for line_output in commandline_output.split("\n"):
                        line_splitted = line_output.split(':')
                        # First element of the list will be the line where subvolume_origin_real has been matched by
                        # grep command. If the second element is '#', this line is commented in fstab and it won't be
                        # taken into account
                        if not line_splitted[1].startswith('#'):
                            line = line_splitted[0]
                            break

                    command_string = """sudo -S sed -i '{line}s|{subvolume_origin_real}|{subvolume_snapshot_created_real}|g' {subvolume_dest}{snapshot_full_name}/etc/fstab""".format(
                        line=line,
                        subvolume_origin_real=subvolume_origin_real,
                        subvolume_snapshot_created_real=subvolume_snapshot_created_real,
                        subvolume_dest=self.subvolume_dest,
                        snapshot_full_name=snapshot_full_name
                    )
                    command = [command_string]
                    try:
                        subprocess.check_output(command, shell=True)
                    except subprocess.CalledProcessError as called_process_error_exception:
                        self.__logger.error("Error trying to substitute the root's path in fstab with the "
                                            "path of the new snapshot created. Reason: " +
                                            str(called_process_error_exception.reason))
                        everything_ok = False
                    if everything_ok:
                        # subvolume_origin_real will be stored in configuration file in order to let the
                        # user to consolidate the system's rollback to any snapshot different from the main one
                        settings.properties_manager.set_property('path_to_consolidate_root_snapshot',
                                                                      subvolume_origin_real)

                        # Run grub-btrfs in order to regenerate GRUB entries
                        self.__logger.info("Regenerating GRUB entries. Please wait...")
                        utils.execute_command(GRUB_BTRFS_COMMAND, console=True, root=True)

                else:
                    # The original subvolume mounted for / couldn't be found
                    # Snapshot won't be created
                    self.__logger.error("The original subvolume mounted for / couldn't be found. "
                                        "Snapshot won't be created: ")
                    pass

            else:
                command = "{command} {subvolume_origin} {subvolume_dest}{snapshot_full_name}".format(
                    command=BTRFS_CREATE_SNAPSHOT_R_COMMAND,
                    subvolume_origin=self.subvolume_origin,
                    subvolume_dest=self.subvolume_dest,
                    snapshot_full_name=snapshot_full_name
                )
                utils.execute_command(command, console=True, root=True)
        else:
            command = "{command} {subvolume_origin} {subvolume_dest}{snapshot_full_name}".format(
                command=BTRFS_CREATE_SNAPSHOT_R_COMMAND,
                subvolume_origin=self.subvolume_origin,
                subvolume_dest=self.subvolume_dest,
                snapshot_full_name=snapshot_full_name
            )
            utils.execute_command(command, console=True, root=True)

    def delete_snapshots(self):
        """Deletes (or not if user has defined it) all the snapshots needed to keep the desired number set by the user.
        It will delete the related logs if they exist

        """
        info_message = "Deleting snapshot of {subvolume_origin} in {subvolume_dest}. " \
                       "Please wait...".format(subvolume_origin=self.subvolume_origin,
                                               subvolume_dest=self.subvolume_dest)
        self.__logger.info(info_message)

        # If user has selected not delete any snapshot, this operation won't be done
        if self.snapshots_to_keep > -1:
            # Checking how many snapshots are with the same name ordered by date
            snapshots = self.get_all_snapshots_with_the_same_name()

            # Removing all the snapshots needed starting with the oldest one until reach
            # the limit defined by the user
            snapshots_to_delete = len(snapshots) - self.snapshots_to_keep
            index = 0
            while snapshots_to_delete > 0:
                # Deletes the snapshot
                command = "{command} {snapshot}".format(command=BTRFS_DELETE_SNAPSHOT_COMMAND,
                                                        snapshot=snapshots[index])
                utils.execute_command(command, console=True, root=True)
                info_message = "Snapshot {snapshot} deleted.\n".format(snapshot=snapshots[index])
                self.__logger.info(info_message)
                # Deletes the log if it exists
                snapshot_name = snapshots[index].split("/")[-1]
                log = "{snapshot_name}-{index}.txt".format(snapshot_name=snapshot_name.split("-")[-2],
                                                           index=snapshot_name.split("-")[-1])
                log_path = os.path.join(settings.logs_path, log)
                if os.path.exists(log_path):
                    try:
                        os.remove(log_path)
                        info_message = "Log {log} deleted.\n".format(log=log)
                        self.__logger.info(info_message)
                    except OSError as os_error_exception:
                        info_message = "Error deleting log {log}. Error {exception}\n".format(log=log,
                                                                                              exception=str(
                                                                                                  os_error_exception))
                        self.__logger.info(info_message)
                else:
                    info_message = "Log {log} doesn't exist. Skipping...deleted.\n".format(log=log)
                    self.__logger.info(info_message)

                snapshots_to_delete -= 1
                index += 1

            # Checks if grub-btrfs integration is enabled
            if settings.properties_manager.get_property("grub_btrfs"):
                # Run grub-btrfs in order to regenerate GRUB entries
                utils.execute_command(GRUB_BTRFS_COMMAND, console=True, root=True)

    def delete_origin(self):
        """Deletes the original subvolume, i.e. the subvolume in subvolume_origin

        """
        info_message = "Deleting subvolume from origin {subvolume_origin}. " \
                       "Please wait...".format(subvolume_origin=self.subvolume_origin)
        self.__logger.info(info_message)
        errors = False

        # Deletes the subvolume
        command_string = "{command} {snapshot}".format(command=BTRFS_DELETE_SNAPSHOT_COMMAND,
                                                       snapshot=self.subvolume_origin)
        command = [command_string]
        commandline_output = None
        try:
            # This is a special way for executing a command using Python:
            # shell=True allows the execution of complex shell commands
            # stdout=subprocess.PIPE captures the output generated by the command
            # stderr=subprocess.STDOUT captures the errors generated by the command and redirects them to stdout
            commandline_output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            commandline_output = commandline_output.stdout.decode('utf-8')
        except subprocess.CalledProcessError:
            pass

        for line in commandline_output.split("\n"):
            if 'Directory not empty' in line:
                errors = True
                break
        if errors:
            # Subvolume is not empty so it can't be deleted. Exception is thrown
            raise exception.BtrfsSnapshotDeletion("Error: {snapshot} is not empty.\n".
                                                            format(snapshot=self.subvolume_origin))
        else:
            info_message = "Snapshot {snapshot} deleted.\n".format(snapshot=self.subvolume_origin)
            self.__logger.info(info_message)

    def get_all_snapshots_with_the_same_name(self):
        """Retrieves all the snapshots with name self.snapshot_name stored within self.subvolume_dest.

        Returns:
            list (:obj:`list` of :obj:`str`): paths to the snapshots.
        """
        # Checking how many snapshots are with the same name ordered by date
        snapshots = glob.glob("{snapshot_directory}/*".format(snapshot_directory=self.subvolume_dest))
        snapshots.sort(key=os.path.getmtime)
        snapshots_whit_same_name = [file for file in snapshots if self.snapshot_name in file]

        return snapshots_whit_same_name


class RootSnapshotChecker:
    """Checks if the current snapshot used for root is the default or the user has booted the system from
    an alternate snapshot.

    """
    def __init__(self, parent_window):
        # Attributes
        self.__snapshot_to_clone_in_root_full_path = None
        self.__root_subvolume = None
        # Logger
        self.__logger = utils.Logger(self.__class__.__name__).get()
        self.__logger.info("Checking if the current snapshot used for root is the default. Please wait...")
        self.__parent_window = parent_window

    def check_root_snapshot(self):
        """Checks if the current snapshot used for root is the default or the user has booted the system from
        an alternate snapshot.

        Returns:
            boolean: true if current snapshot used for root is the default or this paramenter has not been stored yet;
                     false otherwise.
        """
        # First, it is necessary to check if path_to_consolidate_root_snapshot is defined
        if settings.properties_manager.get_property("path_to_consolidate_root_snapshot") != 0:
            # Obtaining the mounted subvolume for root partition
            # mount | grep 'on / ' | grep -o 'subvol=/.*' | cut -f2- -d=
            command_string = """mount | grep 'on / ' | grep -o 'subvol=/.*' | cut -f2- -d="""
            command = [command_string]
            mounted_snapshot_raw = None
            try:
                mounted_snapshot_raw = subprocess.check_output(command, shell=True)
            except subprocess.CalledProcessError:
                pass
            if mounted_snapshot_raw:
                # Removing the last two characters (a /n and a ")")
                mounted_snapshot_raw = mounted_snapshot_raw[:-2]
                # Converting bytes into string
                mounted_snapshot_raw = mounted_snapshot_raw.decode("utf-8")
                # Removing first / if path_to_consolidate_root_snapshot doesn't start with /
                if not settings.properties_manager.get_property("path_to_consolidate_root_snapshot")\
                        .startswith("/"):
                    mounted_snapshot_raw = mounted_snapshot_raw[1:]
            if mounted_snapshot_raw != settings.properties_manager. \
                    get_property("path_to_consolidate_root_snapshot"):
                # If mounted snapshot is different from the supposed default root subvolume
                # it means that user has booted the system using an alternate snapshot from GRUB.
                # ButterManager will ask to consolidate the current snapshot as the default root
                # subvolume

                # Obtaining the snapshot mounted
                mounted_snapshot_full_path = None
                while mounted_snapshot_full_path is None:
                    for subvolume in settings.subvolumes:
                        snapshots = settings.subvolumes[subvolume].get_all_snapshots_with_the_same_name()
                        for snapshot in snapshots:
                            if mounted_snapshot_raw in snapshot:
                                mounted_snapshot_full_path = snapshot
                                break
                        if mounted_snapshot_full_path is not None:
                            break

                self.__snapshot_to_clone_in_root_full_path = mounted_snapshot_full_path
                self.__root_subvolume = settings.subvolumes[subvolume]
                return False
            else:
                return True
        else:
            # Path to consolidate root snapshot hasn't been defined yet so this check is skipped
            return True

    def open_consolidate_snapshot_window(self):
        """Checks if the current snapshot used for root is the default or the user has booted the system from
        an alternate snapshot.

        Returns:
            QDialog: The dialog window to consolidate the root snapshot.
        """
        info_window = windows.ConsolidateSnapshotWindow(self.__parent_window,
                                                               self.__snapshot_to_clone_in_root_full_path,
                                                               self.__root_subvolume)
        return info_window


class Differentiator(QThread):
    """Independent thread that will calculate the differences between a snapshot and its current state.

    """
    # Constants
    DIFFS_DIR = "diffs"
    DIFF_COMMAND = "sudo -S diff -qr"
    MODIFIED_FILE = "modified.txt"
    OPERATION_FULL = "full_operation"
    OPERATION_PARTIAL = "partial_operation"

    # Attributes
    # pyqtSignal that will be emitted when this class requires to display
    # a single information window on the screen
    show_one_window = pyqtSignal('bool')

    # Constructor
    def __init__(self, snapshot_full_path, operation_type):
        QThread.__init__(self)
        self.__snapshot_full_path = snapshot_full_path
        self.__snapshot_name = snapshot_full_path.split("/")[-1]
        self.__operation_type = operation_type

    # Methods
    def run(self):
        # Main window will be hidden
        self.on_show_one_window(True)
        info_dialog = windows.InfoWindow(None, "Calculating differences in\n"
                                                      "'{snapshot_name}'.\n"
                                                      "Please, be patient. This process\n"
                                                      "can take several minutes. This\n"
                                                      "window will be closed when the\n"
                                                      "operation is done. Calculating..."
                                                      .format(snapshot_name=self.__snapshot_full_path))
        # Displaying info window
        info_dialog.show()

        # Calculates differences
        self.__calculate_differences()

        # Hiding info window
        info_dialog.hide()

        # Main window will be shown again
        self.on_show_one_window(False)

    def __calculate_differences(self):
        """Wraps all the operations to calculate differences.

        """
        # Gets the subvolume of the snapshot
        subvolume = get_subvolume_by_snapshot_name(self.__snapshot_full_path)

        if subvolume:
            # Creating a directory to store all the diff files generated if it doesn't exist
            # or removing and creating it if it existed
            diffs_path = os.path.join(settings.application_path, self.DIFFS_DIR, self.__snapshot_name)

            if os.path.exists(diffs_path):
                shutil.rmtree(diffs_path)

            os.makedirs(diffs_path)

            # Getting the current subvolune name. This subvolume is the current one which is going to be
            # used for the comparison. It is needed to remove all the empty strings within the list
            subvolume_name_list = subvolume.subvolume_origin.split("/")
            cleaned_subvolume_name_list = list(filter(None, subvolume_name_list))
            if not cleaned_subvolume_name_list:
                subvolume_name = "original"
            else:
                subvolume_name = cleaned_subvolume_name_list[-1]

            if self.__operation_type == self.OPERATION_FULL:
                # Full operation
                # Creating 3 different files to store differences
                files_only_in_dir1_path = os.path.join(diffs_path, "{file_name}.txt".format(file_name=subvolume_name))
                files_only_in_dir2_path = os.path.join(diffs_path, "{file_name}.txt".format(
                    file_name=self.__snapshot_name))
                files_in_both_modified_path = os.path.join(diffs_path, self.MODIFIED_FILE)
                files_only_in_dir1 = open(files_only_in_dir1_path, "w+")
                files_only_in_dir2 = open(files_only_in_dir2_path, "w+")
                files_in_both_modified = open(files_in_both_modified_path, "w+")

                files_in_both_modified.write("Files in both snapshots that have been modified" + "\r\n\r\n")
                files_only_in_dir1.write("Files only in ${dir}".format(dir=subvolume.subvolume_origin) + "\r\n\r\n")
                files_only_in_dir2.write("Files only in ${dir}".format(dir=self.__snapshot_full_path) + "\r\n\r\n")

                # Calculating differences
                command = "{command} {dir1} {dir2}".format(command=self.DIFF_COMMAND, dir1=subvolume.subvolume_origin,
                                                           dir2=self.__snapshot_full_path)
                echo = subprocess.Popen(['echo', settings.user_password], stdout=subprocess.PIPE)
                result = subprocess.Popen(command.split(), stdin=echo.stdout, stdout=subprocess.PIPE)

                for line in iter(result.stdout.readline, b''):
                    line_decoded = line.decode('utf-8')
                    if " differ" in line_decoded:
                        file_modified_splitted = line_decoded.split(
                            "Files {path}".format(path=subvolume.subvolume_origin))
                        file_modified = "/" + file_modified_splitted[1].split(" ")[0]
                        files_in_both_modified.write(file_modified + "\r\n")
                    elif "Only in {dir1}".format(dir1=subvolume.subvolume_origin) in line_decoded:
                        file_only_in_dir1_splitted = line_decoded.split("Only in {path}".format(
                            path=subvolume.subvolume_origin))
                        file_only_in_dir1_splitted = file_only_in_dir1_splitted[1].split(":")
                        file_name = file_only_in_dir1_splitted[1].strip()
                        file_only_in_dir1 = "/" + file_only_in_dir1_splitted[0] + "/" + file_name
                        files_only_in_dir1.write(file_only_in_dir1 + "\r\n")
                    elif "Only in {dir2}".format(dir2=self.__snapshot_full_path) in line_decoded:
                        file_only_in_dir2_splitted = line_decoded.split("Only in {path}".format(
                            path=self.__snapshot_full_path))
                        file_only_in_dir2_splitted = file_only_in_dir2_splitted[1].split(":")
                        file_name = file_only_in_dir2_splitted[1].strip()
                        file_only_in_dir2 = file_only_in_dir2_splitted[0] + "/" + file_name
                        files_only_in_dir2.write(file_only_in_dir2 + "\r\n")
                # Closing files
                files_only_in_dir1.close()
                files_only_in_dir2.close()
                files_in_both_modified.close()

                # Opening the file with the default application installed in the OS
                # Warning, xdg-open is not working executing the code from PyCharm so
                # it seems it doesn't work but it is really working
                subprocess.call(['xdg-open', files_only_in_dir1_path])
                subprocess.call(['xdg-open', files_only_in_dir2_path])
                subprocess.call(['xdg-open', files_in_both_modified_path])

            else:
                # Partial operation
                # Creating only one file to store differences
                temp_sorted_modified_path = os.path.join(diffs_path, "tmp.txt")
                temp_sorted_modified = open(temp_sorted_modified_path, "w+")

                # Calculating differences
                # sudo btrfs subvolume find-new /mnt/defvol/_snapshots/root-20201021-0/  '9999999'
                # sudo btrfs subvolume find-new /mnt/defvol/_active/rootvol/ 463579 | sed '$d' | cut -f17- -d' ' |
                # sort | uniq

                # First, old transid is calculated. This ID will be used as a reference for the comparison
                transid = "9999999"
                command = "{command} {dir1} {transid}".format(command=BTRFS_FIND_NEW_COMMAND,
                                                              dir1=self.__snapshot_full_path, transid=transid)
                echo = subprocess.Popen(['echo', settings.user_password], stdout=subprocess.PIPE)
                result = subprocess.Popen(command.split(), stdin=echo.stdout, stdout=subprocess.PIPE)

                for line in iter(result.stdout.readline, b''):
                    line_decoded = line.decode('utf-8')
                    line_splitted = line_decoded.split(" ")
                    transid = line_splitted[-1].strip()

                # Then, the differences are obtained using transid
                command = "{command} {dir1} {transid}".format(
                    command=BTRFS_FIND_NEW_COMMAND,
                    dir1=subvolume.subvolume_origin,
                    transid=transid)
                echo = subprocess.Popen(['echo', settings.user_password], stdout=subprocess.PIPE)
                result = subprocess.Popen(command.split(), stdin=echo.stdout, stdout=subprocess.PIPE)

                temp_sorted_modified.write("- Files in both snapshots that have been modified" + "\r\n")

                for line in iter(result.stdout.readline, b''):
                    line_decoded = line.decode('utf-8')
                    line_splitted = line_decoded.split(" ")
                    file_modified = "/" + line_splitted[-1].strip()
                    temp_sorted_modified.write(file_modified + "\r\n")

                # Closing file
                temp_sorted_modified.close()

                # Sorting file
                files_in_both_modified_path = os.path.join(diffs_path, self.MODIFIED_FILE)
                files_in_both_modified = open(files_in_both_modified_path, "w+")
                command = "sort {file}".format(file=temp_sorted_modified_path)
                subprocess.Popen(command.split(), stdout=files_in_both_modified)

                # Opening the file with the default application installed in the OS
                # Warning, xdg-open is not working executing the code from PyCharm so
                # it seems it doesn't work but it is really working
                subprocess.call(['xdg-open', files_in_both_modified_path])

    def on_show_one_window(self, one_window):
        """Emits a QT Signal to hide or show the rest of application windows.

        Arguments:
            one_window (boolean): Information window should be unique?.
        """
        self.show_one_window.emit(one_window)


# Module's methods
def delete_specific_snapshot(snapshot_full_path):
    """Deletes a specific snapshot.
    It will delete the specific log related if it exists too.

    Arguments:
        snapshot_full_path (string): path to the snapshot that user wants to delete.

    """
    # Logger
    logger = utils.Logger(sys.modules['__main__'].__file__).get()
    info_message = "Deleting snapshot {snapshot}".format(snapshot=snapshot_full_path)
    logger.info(info_message)

    command = "{command} {snapshot}".format(command=BTRFS_DELETE_SNAPSHOT_COMMAND, snapshot=snapshot_full_path)
    utils.execute_command(command, root=True)
    info_message = "Snapshot {snapshot} deleted.\n".format(snapshot=snapshot_full_path)
    logger.info(info_message)

    # Checks if grub-btrfs integration is enabled
    if settings.properties_manager.get_property("grub_btrfs"):
        # Run grub-btrfs in order to regenerate GRUB entries
        utils.execute_command(GRUB_BTRFS_COMMAND, console=True, root=True)
        info_message = "Regenerating GRUB entries. Please wait..."
        logger.info(info_message)

    # Deletes the log if it exists
    snapshot_name = snapshot_full_path.split("/")[-1]
    log = "{snapshot_name}-{index}.txt".format(snapshot_name=snapshot_name.split("-")[-2],
                                               index=snapshot_name.split("-")[-1])
    log_path = os.path.join(settings.logs_path, log)
    if os.path.exists(log_path):
        try:
            os.remove(log_path)
            info_message = "Log {log} deleted.\n".format(log=log)
            logger.info(info_message)
        except OSError as os_error_exception:
            info_message = "Error deleting log {log}. Error {exception}\n".format(log=log,
                                                                                  exception=str(os_error_exception))
            logger.info(info_message)
    else:
        info_message = "Log {log} doesn't exist. Skipping...deleted.\n".format(log=log)
        logger.info(info_message)


def get_subvolume_by_snapshot_name(snapshot_name):
    """Gets a subvolume object using the name of the snapshot.

    Arguments:
        snapshot_name (string): name of the snapshot.

        Returns:
            Subvolume: The subvolume which belongs the snapshot. None if subvolume was not found.
    """
    # Logger
    logger = utils.Logger(sys.modules['__main__'].__file__).get()
    info_message = "Getting subvolume from snapshot's name {snapshot_name}".format(snapshot_name=snapshot_name)
    logger.info(info_message)

    subvolume_found = None

    for subvolume_key in settings.subvolumes:
        subvolume = settings.subvolumes[subvolume_key]
        subvolume_snapshots_prefix = "{subvolume_dest}{subvolume_prefix}".format(
            subvolume_dest=subvolume.subvolume_dest,
            subvolume_prefix=subvolume.snapshot_name)
        if snapshot_name.startswith(subvolume_snapshots_prefix):
            info_message = "Found subvolume {subvolume}".format(subvolume=subvolume.subvolume_origin)
            logger.info(info_message)
            subvolume_found = subvolume
    return subvolume_found


================================================
FILE: buttermanager/buttermanager/manager/__init__.py
================================================


================================================
FILE: buttermanager/buttermanager/manager/upgrader.py
================================================
# -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>
#
# This file is part of buttermanager.
#
# 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, version 3 of the License.
#
# 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/>.

"""This module gathers all the managers built for the application.

"""
from .. import manager
from ..util import settings, utils
import sys
import urllib.request
from PyQt5.QtCore import QThread, pyqtSignal
from urllib.error import URLError

# Constants
ARCH_PACMAN_REFRESH_REPOSITORIES = "sudo -S pacman -Sy"
ARCH_PACMAN_CHECK_UPDATES = "sudo -S pacman -Qu"
ARCH_PACMAN_UPGRADE_COMMAND = "sudo -S pacman -Syu --noconfirm"
DEBIAN_APT_UPDATE_COMMAND = "sudo -S apt update"
DEBIAN_APT_UPGRADE_COMMAND = "sudo -S apt upgrade -y"
DEBIAN_APT_CHECK_UPDATES = "sudo -S apt list --upgradable"
ARCH_YAOURT_UPGRADE_COMMAND = "yaourt -Syua --noconfirm"
ARCH_YAOURT_COMMAND = "yaourt"
ARCH_YAY_UPGRADE_COMMAND = "yay -Syua --noconfirm"
ARCH_YAY_COMMAND = "yay"
ARCH_TRIZEN_UPGRADE_COMMAND = "trizen -Syua --noconfirm"
ARCH_TRIZEN_COMMAND = "trizen"
SNAP_COMMAND = "snap"
FLATPAK_COMMAND = "flatpak"
SNAP_UPGRADE_COMMAND = "sudo -S snap refresh"
FLATPAK_UPGRADE_COMMAND = "flatpak update -y"
SUSE_ZYPPER_UPGRADE_COMMAND = "sudo -S zypper -n update"
SUSE_ZYPPER_CHECK_UPDATES = "sudo -S zypper list-updates"
FEDORA_DNF_UPGRADE_COMMAND = "sudo -S dnf upgrade --refresh --assumeyes"
FEDORA_DNF_CHECK_UPDATES = "sudo -S dnf check-update"


class Upgrader(QThread):
    """Independent thread that will run the system upgrading process.

    """
    # Attributes

    # pyqtSignal that will be emitted when this class requires that main
    # window disables all the buttons
    disable_buttons = pyqtSignal()

    # pyqtSignal that will be emitted when this class requires that main
    # window enables all the buttons
    enable_buttons = pyqtSignal()

    # pyqtSignal that will be emitted when this class requires that main
    # window refreshes GUI
    refresh_gui = pyqtSignal()

    # Constructor
    def __init__(self, include_aur, include_snap, include_flatpak, snapshots):
        QThread.__init__(self)
        # Logger
        self.__logger = utils.Logger(self.__class__.__name__).get()
        # Include AUR packages upgrade
        self.__include_aur = include_aur
        # Include snap packages upgrade
        self.__include_snap = include_snap
        # Include flatpak packages upgrade
        self.__include_flatpak = include_flatpak
        # Create and delete snapshots
        self.__snapshots = snapshots

    # Methods
    def run(self):
        # Upgrading the system
        self.__upgrade_system()

    def __upgrade_system(self):
        """Wraps all the operations to upgrade the system.

        """
        # Check for updates
        if check_updates():
            # There are system updates
            # Starting the upgrading process. Disabling all the buttons.
            self.on_disable_gui_buttons()

            sys.stdout.write("\n")
            sys.stdout.write("--------")
            sys.stdout.write("\n")
            self.__logger.info("Starting system upgrading process.")
            sys.stdout.write("Starting system upgrading process. Please wait...")
            sys.stdout.write("\n")

            # Creates all the snapshots needed before upgrading the system
            # only if it is needed
            if self.__snapshots:
                sys.stdout.write("\n")
                sys.stdout.write("--------")
                sys.stdout.write("\n")
                sys.stdout.write("Creating snapshots and updating GRUB entries if it is necessary...")
                sys.stdout.write("\n")
                sys.stdout.write("--------")
                sys.stdout.write("\n")
                for snapshot in settings.subvolumes:
                    try:
                        settings.subvolumes[snapshot].create_snapshot()
                    except Exception as exception:
                        sys.stdout.write("\n")
                        sys.stdout.write("--------")
                        sys.stdout.write("\n")
                        sys.stdout.write("Error creating the snapshot " +
                                         settings.subvolumes[snapshot].subvolume_origin)
                        sys.stdout.write("\n")
                        sys.stdout.write("Error: " + str(exception))
                        sys.stdout.write("\n")
                        sys.stdout.write("--------")
                        sys.stdout.write("\n")

            # Upgrades the system
            upgrading_command = ""
            if settings.user_os == utils.OS_ARCH:
                upgrading_command = ARCH_PACMAN_UPGRADE_COMMAND
            elif settings.user_os == utils.OS_DEBIAN:
                # First, it is necessary to update the system
                sys.stdout.write("\n")
                sys.stdout.write("--------")
                sys.stdout.write("\n")
                sys.stdout.write("Updating the system. Please wait...")
                sys.stdout.write("\n")
                utils.execute_command(DEBIAN_APT_UPDATE_COMMAND, console=True)
                sys.stdout.write("\n")
                upgrading_command = DEBIAN_APT_UPGRADE_COMMAND
            elif settings.user_os == utils.OS_SUSE:
                upgrading_command = SUSE_ZYPPER_UPGRADE_COMMAND
            elif settings.user_os == utils.OS_FEDORA:
                upgrading_command = FEDORA_DNF_UPGRADE_COMMAND

            if upgrading_command:
                try:
                    sys.stdout.write("Upgrading the system. Please wait...")
                    sys.stdout.write("\n")
                    utils.execute_command(upgrading_command, console=True)
                except Exception as exception:
                    sys.stdout.write("\n")
                    sys.stdout.write("--------")
                    sys.stdout.write("\n")
                    sys.stdout.write("Error upgrading the system")
                    sys.stdout.write("\n")
                    sys.stdout.write("Error: " + str(exception))
                    sys.stdout.write("\n")
                    sys.stdout.write("--------")
                    sys.stdout.write("\n")

            # Upgrades AUR if distro is ArchLinux or derivatives
            if settings.user_os == utils.OS_ARCH:
                if self.__include_aur:
                    try:
                        sys.stdout.write("\n")
                        sys.stdout.write("--------")
                        sys.stdout.write("\n")
                        sys.stdout.write("Updating AUR packages if it is needed. Please wait...")
                        sys.stdout.write("\n")
                        if utils.exist_program(ARCH_YAY_COMMAND):
                            utils.execute_command(ARCH_YAY_UPGRADE_COMMAND, console=True)
                        elif utils.exist_program(ARCH_TRIZEN_COMMAND):
                            utils.execute_command(ARCH_TRIZEN_UPGRADE_COMMAND, console=True)
                        elif utils.exist_program(ARCH_YAOURT_COMMAND):
                            utils.execute_command(ARCH_YAOURT_UPGRADE_COMMAND, console=True)
                    except Exception as exception:
                        sys.stdout.write("\n")
                        sys.stdout.write("--------")
                        sys.stdout.write("\n")
                        sys.stdout.write("Error upgrading AUR packages")
                        sys.stdout.write("\n")
                        sys.stdout.write("Error: " + str(exception))
                        sys.stdout.write("\n")
                        sys.stdout.write("--------")
                        sys.stdout.write("\n")

            # Upgrades snap packages
            if self.__include_snap:
                if utils.exist_program(SNAP_COMMAND):
                    try:
                        sys.stdout.write("\n")
                        sys.stdout.write("--------")
                        sys.stdout.write("\n")
                        sys.stdout.write("Updating snap applications. Please wait...")
                        sys.stdout.write("\n")
                        utils.execute_command(SNAP_UPGRADE_COMMAND, console=True)
                    except Exception as exception:
                        sys.stdout.write("\n")
                        sys.stdout.write("--------")
                        sys.stdout.write("\n")
                        sys.stdout.write("Error upgrading snap packages")
                        sys.stdout.write("\n")
                        sys.stdout.write("Error: " + str(exception))
                        sys.stdout.write("\n")
                        sys.stdout.write("--------")
                        sys.stdout.write("\n")

            # Upgrades flatpak packages
            if self.__include_flatpak:
                if utils.exist_program(FLATPAK_COMMAND):
                    try:
                        sys.stdout.write("\n")
                        sys.stdout.write("--------")
                        sys.stdout.write("\n")
                        sys.stdout.write("Updating flatpak applications. Please wait...")
                        sys.stdout.write("\n")
                        utils.execute_command(FLATPAK_UPGRADE_COMMAND, console=True)
                    except Exception as exception:
                        sys.stdout.write("\n")
                        sys.stdout.write("--------")
                        sys.stdout.write("\n")
                        sys.stdout.write("Error upgrading flatpak packages")
                        sys.stdout.write("\n")
                        sys.stdout.write("Error: " + str(exception))
                        sys.stdout.write("\n")
                        sys.stdout.write("--------")
                        sys.stdout.write("\n")

            # Removes all the snapshots not needed any more it is needed
            if self.__snapshots:
                sys.stdout.write("\n")
                sys.stdout.write("--------")
                sys.stdout.write("\n")
                sys.stdout.write("Removing old snapshots if it is needed and updating GRUB entries. Please wait...")
                sys.stdout.write("\n")
                for snapshot in settings.subvolumes:
                    try:
                        settings.subvolumes[snapshot].delete_snapshots()
                    except Exception as exception:
                        sys.stdout.write("\n")
                        sys.stdout.write("--------")
                        sys.stdout.write("\n")
                        sys.stdout.write("Error deleting the snapshot " +
                                         settings.subvolumes[snapshot].subvolume_origin)
                        sys.stdout.write("\n")
                        sys.stdout.write("Error: " + str(exception))
                        sys.stdout.write("\n")
                        sys.stdout.write("--------")
                        sys.stdout.write("\n")

            sys.stdout.write("\n")
            sys.stdout.write("--------")
            sys.stdout.write("\n")
            self.__logger.info("System upgrading process finished.")
            sys.stdout.write("System upgrading process finished. You can close the terminal output now.")
            sys.stdout.write("\n")
            sys.stdout.write("\n")

            # Refreshing GUI
            self.on_refresh_gui()
        else:
            # There are not system updates
            self.__logger.info("Your system is up to date.")
            sys.stdout.write("Your system is up to date. You can close the terminal output now.")
            sys.stdout.write("\n")
            sys.stdout.write("\n")

        # Finishing the upgrading process. Enabling all the buttons.
        self.on_enable_gui_buttons()

    def on_disable_gui_buttons(self):
        """Emits a QT Signal to disable all the buttons in main window.

        """
        self.disable_buttons.emit()

    def on_enable_gui_buttons(self):
        """Emits a QT Signal to enable all the buttons in main window.

        """
        self.enable_buttons.emit()

    def on_refresh_gui(self):
        """Emits a QT Signal to refresh filesystem statistics in main window.

        """
        self.refresh_gui.emit()


class UpdatesChecker(QThread):
    """Independent thread that will run the system checking for updates.

    """
    # Attributes

    # pyqtSignal that will be emitted when this class requires that main
    # window shows the updates window. The signal will emit an 'object' that,
    # in hits case, will be a list of strings.
    show_updates_window = pyqtSignal(object)

    # Constructor
    def __init__(self):
        QThread.__init__(self)
        # Logger
        self.__logger = utils.Logger(self.__class__.__name__).get()

    # Methods
    def run(self):
        # Checks for updates
        self.__check_updates()

    def __check_updates(self):
        """Wraps all the operations to check updates.

        First, it will check Internet connectivity for doing the operation.
        Emits a signal with the packages found. Otherwise, it won't emit this signal and
        nothing will happen.

        """
        # Checking Internet connection for 5 minutes
        tries = 0
        internet_available = self.__internet_available()

        while (not internet_available) & (tries < 60):
            self.__logger.info("Trying to reach Internet again. If there is no Internet connection in 5 minutes, this"
                               "operation will be canceled")
            self.sleep(5)
            internet_available = self.__internet_available()
            tries += 1

        # Checking updates only if Internet connection is available
        if internet_available:
            # Checking updates only if the user selected the option
            if settings.check_at_startup == 1:
                # Emmiting the signal only if there are updates
                if manager.upgrader.check_updates():
                    commandline_output = []
                    if settings.user_os == utils.OS_ARCH:
                        refresh_repositories_command = manager.upgrader.ARCH_PACMAN_REFRESH_REPOSITORIES
                        utils.execute_command(refresh_repositories_command)
                        check_for_updates_command = manager.upgrader.ARCH_PACMAN_CHECK_UPDATES
                        commandline_output = utils.execute_command(check_for_updates_command)

                    elif settings.user_os == utils.OS_DEBIAN:
                        check_for_updates_command = manager.upgrader.DEBIAN_APT_CHECK_UPDATES
                        commandline_output = utils.execute_command(check_for_updates_command)

                    elif settings.user_os == utils.OS_SUSE:
                        check_for_updates_command = manager.upgrader.SUSE_ZYPPER_CHECK_UPDATES
                        commandline_output = utils.execute_command(check_for_updates_command)

                    elif settings.user_os == utils.OS_FEDORA:
                        check_for_updates_command = manager.upgrader.FEDORA_DNF_CHECK_UPDATES
                        commandline_output = utils.execute_command(check_for_updates_command)

                    # If there are updates, emits the signal thta will be captured in buttermanager.py
                    self.show_updates_window.emit(commandline_output)
        else:
            self.__logger.error("Timeout. Checking updates process has been cancelled because there is no Intenert"
                                " connection")

    def __internet_available(self):
        """Checks Internet connection.

        Returns:
            boolean: true if there is Internet connection available; false otherwise.
        """
        self.__logger.info("Checking Internet connection. Please wait...")
        try:
            urllib.request.urlopen('https://www.google.com', timeout=20)
            self.__logger.info("Internet connection is available!")
            return True
        except urllib.error.URLError as error:
            self.__logger.error("Internet connection is not available... Error: {error}".format(error=error))
            return False


# Module's methods
def check_updates():
    """Checks for updates.

    Returns:
        boolean: true if there are updates; false otherwise.
    """
    # Logger
    logger = utils.Logger(sys.modules['__main__'].__file__).get()
    logger.info("Checking for system updates.")
    sys.stdout.write("Checking for system updates.")
    sys.stdout.write("\n")
    sys.stdout.write("--------")
    sys.stdout.write("\n")

    updates = False
    if settings.user_os == utils.OS_ARCH:
        refresh_repositories_command = ARCH_PACMAN_REFRESH_REPOSITORIES
        utils.execute_command(refresh_repositories_command)
        check_for_updates_command = ARCH_PACMAN_CHECK_UPDATES
        commandline_output = utils.execute_command(check_for_updates_command)

        for line in commandline_output.split("\n"):
            if line:
                updates = True

    elif settings.user_os == utils.OS_DEBIAN:
        check_for_updates_command = DEBIAN_APT_CHECK_UPDATES
        commandline_output = utils.execute_command(check_for_updates_command)
        lines = commandline_output.split("\n")
        if len(lines) > 2:
            updates = True

    elif settings.user_os == utils.OS_SUSE:
        check_for_updates_command = SUSE_ZYPPER_CHECK_UPDATES
        commandline_output = utils.execute_command(check_for_updates_command)
        lines = commandline_output.split("\n")
        if len(lines) > 4:
            updates = True

    elif settings.user_os == utils.OS_FEDORA:
        check_for_updates_command = FEDORA_DNF_CHECK_UPDATES
        commandline_output = utils.execute_command(check_for_updates_command)
        lines = commandline_output.split("\n")
        if len(lines) > 2:
            updates = True

    else:
        updates = True

    return updates


================================================
FILE: buttermanager/buttermanager/ui/ConsolidateSnapshotWindow.ui
================================================
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>424</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>ButterManager</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout_2">
   <item>
    <layout class="QVBoxLayout" name="verticalLayout">
     <property name="leftMargin">
      <number>10</number>
     </property>
     <property name="topMargin">
      <number>10</number>
     </property>
     <property name="rightMargin">
      <number>10</number>
     </property>
     <property name="bottomMargin">
      <number>10</number>
     </property>
     <item>
      <widget class="QLabel" name="label_info">
       <property name="text">
        <string/>
       </property>
       <property name="alignment">
        <set>Qt::AlignCenter</set>
       </property>
      </widget>
     </item>
     <item>
      <widget class="QDialogButtonBox" name="button_box">
       <property name="orientation">
        <enum>Qt::Horizontal</enum>
       </property>
       <property name="standardButtons">
        <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
       </property>
      </widget>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>


================================================
FILE: buttermanager/buttermanager/ui/GeneralInfoWindow.ui
================================================
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>420</width>
    <height>285</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>ButterManager</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout_2">
   <item>
    <layout class="QVBoxLayout" name="verticalLayout">
     <property name="leftMargin">
      <number>10</number>
     </property>
     <property name="topMargin">
      <number>10</number>
     </property>
     <property name="rightMargin">
      <number>10</number>
     </property>
     <property name="bottomMargin">
      <number>10</number>
     </property>
     <item>
      <widget class="QLabel" name="label_info">
       <property name="text">
        <string/>
       </property>
       <property name="alignment">
        <set>Qt::AlignCenter</set>
       </property>
      </widget>
     </item>
     <item>
      <widget class="QDialogButtonBox" name="button_box">
       <property name="orientation">
        <enum>Qt::Horizontal</enum>
       </property>
       <property name="standardButtons">
        <set>QDialogButtonBox::Close</set>
       </property>
      </widget>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>


================================================
FILE: buttermanager/buttermanager/ui/InfoWindow.ui
================================================
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>320</width>
    <height>240</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>ButterManager</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout_2">
   <item>
    <layout class="QVBoxLayout" name="verticalLayout">
     <property name="leftMargin">
      <number>10</number>
     </property>
     <property name="topMargin">
      <number>10</number>
     </property>
     <property name="rightMargin">
      <number>10</number>
     </property>
     <property name="bottomMargin">
      <number>10</number>
     </property>
     <item>
      <widget class="QLabel" name="label_info">
       <property name="layoutDirection">
        <enum>Qt::LeftToRight</enum>
       </property>
       <property name="autoFillBackground">
        <bool>false</bool>
       </property>
       <property name="text">
        <string>TextLabel</string>
       </property>
       <property name="alignment">
        <set>Qt::AlignCenter</set>
       </property>
      </widget>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>


================================================
FILE: buttermanager/buttermanager/ui/LogViewWindow.ui
================================================
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>LogViewWindow</class>
 <widget class="QMainWindow" name="LogViewWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>767</width>
    <height>442</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>ButterManager</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QVBoxLayout" name="verticalLayout_2">
    <item>
     <layout class="QVBoxLayout" name="verticalLayout">
      <property name="leftMargin">
       <number>10</number>
      </property>
      <property name="topMargin">
       <number>10</number>
      </property>
      <property name="rightMargin">
       <number>10</number>
      </property>
      <property name="bottomMargin">
       <number>10</number>
      </property>
      <item>
       <widget class="QLabel" name="label_log">
        <property name="text">
         <string>Log details</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QTextEdit" name="text_log"/>
      </item>
     </layout>
    </item>
   </layout>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>


================================================
FILE: buttermanager/buttermanager/ui/MainWindow.ui
================================================
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>756</width>
    <height>746</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>ButterManager</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QVBoxLayout" name="verticalLayout_10">
    <item>
     <widget class="QTabWidget" name="tab_buttermanager">
      <property name="currentIndex">
       <number>0</number>
      </property>
      <widget class="QWidget" name="tab_main">
       <attribute name="title">
        <string>Main</string>
       </attribute>
       <layout class="QVBoxLayout" name="verticalLayout_3">
        <item>
         <layout class="QVBoxLayout" name="verticalLayout_4"/>
        </item>
        <item>
         <layout class="QHBoxLayout" name="horizontalLayout_2">
          <property name="leftMargin">
           <number>10</number>
          </property>
          <property name="rightMargin">
           <number>10</number>
          </property>
          <item>
           <widget class="QLabel" name="label_filesystem_info">
            <property name="font">
             <font>
              <weight>75</weight>
              <bold>true</bold>
              <underline>true</underline>
             </font>
            </property>
            <property name="text">
             <string>Filesystem Information</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QLabel" name="label_filesystem_info_more">
            <property name="font">
             <font>
              <pointsize>15</pointsize>
             </font>
            </property>
            <property name="text">
             <string>?</string>
            </property>
           </widget>
          </item>
          <item>
           <layout class="QVBoxLayout" name="verticalLayout_5">
            <item>
             <spacer name="verticalSpacer_20">
              <property name="orientation">
               <enum>Qt::Vertical</enum>
              </property>
              <property name="sizeHint" stdset="0">
               <size>
                <width>20</width>
                <height>40</height>
               </size>
              </property>
             </spacer>
            </item>
            <item>
             <widget class="QLabel" name="label_filesystem">
              <property name="text">
               <string>Filesystem</string>
              </property>
             </widget>
            </item>
            <item>
             <widget class="QComboBox" name="combobox_filesystem"/>
            </item>
           </layout>
          </item>
         </layout>
        </item>
        <item>
         <layout class="QGridLayout" name="gridLayout">
          <property name="leftMargin">
           <number>10</number>
          </property>
          <property name="topMargin">
           <number>0</number>
          </property>
          <property name="rightMargin">
           <number>10</number>
          </property>
          <property name="bottomMargin">
           <number>10</number>
          </property>
          <item row="0" column="0">
           <widget class="QLabel" name="label_filesystem_size">
            <property name="text">
             <string>Size:</string>
            </property>
           </widget>
          </item>
          <item row="0" column="1">
           <widget class="QLabel" name="label_filesystem_size_value">
            <property name="text">
             <string>30 GB</string>
            </property>
           </widget>
          </item>
          <item row="1" column="1">
           <widget class="QLabel" name="label_filesystem_allocated_value">
            <property name="text">
             <string>19.77 GB</string>
            </property>
           </widget>
          </item>
          <item row="1" column="0">
           <widget class="QLabel" name="label_filesystem_allocated">
            <property name="text">
             <string>Allocated:</string>
            </property>
           </widget>
          </item>
          <item row="0" column="2">
           <spacer name="horizontalSpacer_6">
            <property name="orientation">
             <enum>Qt::Horizontal</enum>
            </property>
            <property name="sizeHint" stdset="0">
             <size>
              <width>40</width>
              <height>20</height>
             </size>
            </property>
           </spacer>
          </item>
         </layout>
        </item>
        <item>
         <layout class="QVBoxLayout" name="verticalLayout_9">
          <property name="leftMargin">
           <number>10</number>
          </property>
          <property name="rightMargin">
           <number>10</number>
          </property>
          <item>
           <widget class="QLabel" name="label_space_danger">
            <property name="font">
             <font>
              <weight>75</weight>
              <italic>true</italic>
              <bold>true</bold>
             </font>
            </property>
            <property name="text">
             <string>Keep calm and clean a little bit your filesystem</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QLabel" name="label_space_ok">
            <property name="font">
             <font>
              <weight>75</weight>
              <italic>true</italic>
              <bold>true</bold>
             </font>
            </property>
            <property name="text">
             <string>No problem, you have enough free space in your filesystem</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QLabel" name="label_space_ko">
            <property name="font">
             <font>
              <weight>75</weight>
              <italic>true</italic>
              <bold>true</bold>
             </font>
            </property>
            <property name="text">
             <string>Low space svailable. Remove old snapshots, clean the filesystem and balance it</string>
            </property>
           </widget>
          </item>
          <item>
           <spacer name="verticalSpacer">
            <property name="orientation">
             <enum>Qt::Vertical</enum>
            </property>
            <property name="sizeHint" stdset="0">
             <size>
              <width>20</width>
              <height>40</height>
             </size>
            </property>
           </spacer>
          </item>
         </layout>
        </item>
        <item>
         <layout class="QHBoxLayout" name="horizontalLayout_7">
          <property name="leftMargin">
           <number>10</number>
          </property>
          <property name="topMargin">
           <number>10</number>
          </property>
          <property name="rightMargin">
           <number>10</number>
          </property>
          <property name="bottomMargin">
           <number>10</number>
          </property>
          <item>
           <layout class="QVBoxLayout" name="verticalLayout_8">
            <item>
             <widget class="QLabel" name="label_filesystem_lost_info">
              <property name="font">
               <font>
                <weight>75</weight>
                <bold>true</bold>
                <underline>true</underline>
               </font>
              </property>
              <property name="text">
               <string>Used space of total allocated</string>
              </property>
             </widget>
            </item>
            <item>
             <spacer name="verticalSpacer_3">
              <property name="orientation">
               <enum>Qt::Vertical</enum>
              </property>
              <property name="sizeType">
               <enum>QSizePolicy::Fixed</enum>
              </property>
              <property name="sizeHint" stdset="0">
               <size>
                <width>20</width>
                <height>10</height>
               </size>
              </property>
             </spacer>
            </item>
            <item>
             <layout class="QHBoxLayout" name="horizontalLayout_8" stretch="0,0,0,0">
              <property name="spacing">
               <number>6</number>
              </property>
              <item>
               <widget class="QLabel" name="label_filesystem_data">
                <property name="text">
                 <string>Data</string>
                </property>
               </widget>
              </item>
              <item>
               <spacer name="horizontalSpacer_2">
                <property name="orientation">
                 <enum>Qt::Horizontal</enum>
                </property>
                <property name="sizeType">
                 <enum>QSizePolicy::Fixed</enum>
                </property>
                <property name="sizeHint" stdset="0">
                 <size>
                  <width>65</width>
                  <height>20</height>
                 </size>
                </property>
               </spacer>
              </item>
              <item>
               <widget class="QProgressBar" name="progressbar_data">
                <property name="value">
                 <number>85</number>
                </property>
               </widget>
              </item>
              <item>
               <spacer name="horizontalSpacer_4">
                <property name="orientation">
                 <enum>Qt::Horizontal</enum>
                </property>
                <property name="sizeType">
                 <enum>QSizePolicy::Fixed</enum>
                </property>
                <property name="sizeHint" stdset="0">
                 <size>
                  <width>40</width>
                  <height>20</height>
                 </size>
                </property>
               </spacer>
              </item>
             </layout>
            </item>
            <item>
             <layout class="QHBoxLayout" name="horizontalLayout_9" stretch="0,0,0,0">
              <item>
               <widget class="QLabel" name="label_filesystem_metadata">
                <property name="text">
                 <string>Metadata</string>
                </property>
               </widget>
              </item>
              <item>
               <spacer name="horizontalSpacer_3">
                <property name="orientation">
                 <enum>Qt::Horizontal</enum>
                </property>
                <property name="sizeType">
                 <enum>QSizePolicy::Fixed</enum>
                </property>
                <property name="sizeHint" stdset="0">
                 <size>
                  <width>40</width>
                  <height>20</height>
                 </size>
                </property>
               </spacer>
              </item>
              <item>
               <widget class="QProgressBar" name="progressbar_metadata">
                <property name="value">
                 <number>50</number>
                </property>
               </widget>
              </item>
              <item>
               <spacer name="horizontalSpacer_5">
                <property name="orientation">
                 <enum>Qt::Horizontal</enum>
                </property>
                <property name="sizeType">
                 <enum>QSizePolicy::Fixed</enum>
                </property>
                <property name="sizeHint" stdset="0">
                 <size>
                  <width>40</width>
                  <height>20</height>
                 </size>
                </property>
               </spacer>
              </item>
             </layout>
            </item>
            <item>
             <layout class="QHBoxLayout" name="horizontalLayout_4">
              <item>
               <widget class="QLabel" name="label_space_data_danger">
                <property name="font">
                 <font>
                  <weight>75</weight>
                  <italic>true</italic>
                  <bold>true</bold>
                 </font>
                </property>
                <property name="text">
                 <string>It is a perfect time to balance the filesystem. Click on Balance button to free some unused space</string>
                </property>
               </widget>
              </item>
             </layout>
            </item>
           </layout>
          </item>
          <item>
           <widget class="QPushButton" name="button_balance">
            <property name="toolTip">
             <string>Balance the selected filesystem</string>
            </property>
            <property name="text">
             <string>Balance</string>
            </property>
           </widget>
          </item>
         </layout>
        </item>
        <item>
         <spacer name="verticalSpacer_19">
          <property name="orientation">
           <enum>Qt::Vertical</enum>
          </property>
          <property name="sizeHint" stdset="0">
           <size>
            <width>20</width>
            <height>40</height>
           </size>
          </property>
         </spacer>
        </item>
        <item>
         <widget class="Line" name="line_2">
          <property name="orientation">
           <enum>Qt::Horizontal</enum>
          </property>
         </widget>
        </item>
        <item>
         <layout class="QVBoxLayout" name="verticalLayout_6">
          <item>
           <layout class="QVBoxLayout" name="verticalLayout_7">
            <property name="spacing">
             <number>0</number>
            </property>
            <property name="leftMargin">
             <number>10</number>
            </property>
            <property name="topMargin">
             <number>10</number>
            </property>
            <property name="rightMargin">
             <number>10</number>
            </property>
            <property name="bottomMargin">
             <number>10</number>
            </property>
            <item>
             <widget class="QLabel" name="label_other_operations">
              <property name="text">
               <string>Fast actions</string>
              </property>
             </widget>
            </item>
            <item>
             <spacer name="verticalSpacer_2">
              <property name="orientation">
               <enum>Qt::Vertical</enum>
              </property>
              <property name="sizeType">
               <enum>QSizePolicy::Fixed</enum>
              </property>
              <property name="sizeHint" stdset="0">
               <size>
                <width>20</width>
                <height>10</height>
               </size>
              </property>
             </spacer>
            </item>
            <item>
             <layout class="QHBoxLayout" name="horizontalLayout_3">
              <item>
               <widget class="QPushButton" name="button_upgrade_system">
                <property name="toolTip">
                 <string>Upgrade the system creating a previous snapshot and removing old snapshots according to configuration</string>
                </property>
Download .txt
gitextract_bque78re/

├── .gitignore
├── LICENSE
├── README.md
├── aur/
│   ├── PKGBUILD
│   └── README.txt
├── buttermanager/
│   ├── bm_main.py
│   ├── buttermanager/
│   │   ├── __init__.py
│   │   ├── buttermanager.py
│   │   ├── exception/
│   │   │   ├── __init__.py
│   │   │   └── exception.py
│   │   ├── filesystem/
│   │   │   ├── __init__.py
│   │   │   ├── filesystem.py
│   │   │   └── snapshot.py
│   │   ├── manager/
│   │   │   ├── __init__.py
│   │   │   └── upgrader.py
│   │   ├── ui/
│   │   │   ├── ConsolidateSnapshotWindow.ui
│   │   │   ├── GeneralInfoWindow.ui
│   │   │   ├── InfoWindow.ui
│   │   │   ├── LogViewWindow.ui
│   │   │   ├── MainWindow.ui
│   │   │   ├── PasswordWindow.ui
│   │   │   ├── ProblemsFoundWindow.ui
│   │   │   ├── SnapshotWindow.ui
│   │   │   ├── SubvolumeWindow.ui
│   │   │   └── UpdatesWindow.ui
│   │   ├── util/
│   │   │   ├── __init__.py
│   │   │   ├── settings.py
│   │   │   └── utils.py
│   │   └── window/
│   │       ├── __init__.py
│   │       └── windows.py
│   └── main.py
├── doc/
│   └── README.md
├── install/
│   ├── native_install.sh
│   ├── uninstall.sh
│   └── venv_install.sh
├── packaging/
│   ├── buttermanager.desktop
│   └── buttermanager_venv.desktop
├── requirements.txt
├── rpm/
│   ├── README.txt
│   └── buttermanager.spec
├── setup.py
└── version.txt
Download .txt
SYMBOL INDEX (196 symbols across 10 files)

FILE: buttermanager/bm_main.py
  function main (line 6) | def main():

FILE: buttermanager/buttermanager/buttermanager.py
  class EmittingStream (line 40) | class EmittingStream(QObject):
    method write (line 44) | def write(self, text):
    method flush (line 47) | def flush(self):
  class PasswordWindow (line 51) | class PasswordWindow(QMainWindow):
    method __init__ (line 57) | def __init__(self, parent):
    method init_ui (line 77) | def init_ui(self):
    method get_base_font_size (line 134) | def get_base_font_size(self):
    method load_main_window (line 166) | def load_main_window(self):
    method exit (line 177) | def exit(self):
  class ButtermanagerMainWindow (line 183) | class ButtermanagerMainWindow(QMainWindow):
    method __init__ (line 189) | def __init__(self, parent):
    method __del__ (line 218) | def __del__(self):
    method normal_output_written (line 224) | def normal_output_written(self, text):
    method init_ui (line 234) | def init_ui(self):
    method check_updates (line 549) | def check_updates(self):
    method show_updates_window (line 557) | def show_updates_window(self, command_line_output):
    method balance_filesystem (line 571) | def balance_filesystem(self):
    method manage_window (line 583) | def manage_window(self, hide):
    method refresh_filesystem_statistics (line 598) | def refresh_filesystem_statistics(self):
    method fill_filesystem_info (line 607) | def fill_filesystem_info(self, filesystem):
    method upgrade_system (line 628) | def upgrade_system(self, snapshots=True):
    method close_terminal (line 677) | def close_terminal(self):
    method save_log (line 688) | def save_log(self):
    method __disable_buttons (line 709) | def __disable_buttons(self):
    method __enable_buttons (line 741) | def __enable_buttons(self):
    method take_snapshot (line 773) | def take_snapshot(self):
    method delete_snapshots (line 788) | def delete_snapshots(self):
    method find_diffs (line 808) | def find_diffs(self):
    method open_file_explorer (line 857) | def open_file_explorer(self):
    method delete_logs (line 870) | def delete_logs(self):
    method view_log (line 881) | def view_log(self):
    method add_subvolume (line 890) | def add_subvolume(self):
    method dont_remove_snapshots (line 900) | def dont_remove_snapshots(self):
    method include_snap (line 909) | def include_snap(self):
    method include_flatpak (line 919) | def include_flatpak(self):
    method include_aur (line 929) | def include_aur(self):
    method include_log (line 939) | def include_log(self):
    method include_startup (line 949) | def include_startup(self):
    method include_grub_btrfs (line 959) | def include_grub_btrfs(self):
    method change_font_size_increment (line 971) | def change_font_size_increment(self):
    method on_combobox_filesystem_changed (line 981) | def on_combobox_filesystem_changed(self):
    method on_combobox_subvolumes_changed (line 985) | def on_combobox_subvolumes_changed(self):
    method edit_subvolume (line 1009) | def edit_subvolume(self):
    method save_subvolume (line 1022) | def save_subvolume(self):
    method delete_subvolume (line 1049) | def delete_subvolume(self):
    method go_to_github (line 1060) | def go_to_github(self):
    method go_to_wiki (line 1067) | def go_to_wiki(self):
    method fill_snapshots (line 1074) | def fill_snapshots(self):
    method fill_logs (line 1090) | def fill_logs(self):
    method fill_subvolumes (line 1102) | def fill_subvolumes(self):
    method refresh_subvolume_buttons (line 1137) | def refresh_subvolume_buttons(self):
    method refresh_gui (line 1162) | def refresh_gui(self):
    method save_log_refresh_gui (line 1173) | def save_log_refresh_gui(self):
    method show_space_labels (line 1180) | def show_space_labels(self):
    method regenerate_grub (line 1204) | def regenerate_grub(self):

FILE: buttermanager/buttermanager/exception/exception.py
  class NoCommandFound (line 25) | class NoCommandFound(Exception):
  class BtrfsSnapshotDeletion (line 32) | class BtrfsSnapshotDeletion(Exception):
    method __init__ (line 37) | def __init__(self, *args):
    method __str__ (line 43) | def __str__(self):

FILE: buttermanager/buttermanager/filesystem/filesystem.py
  class Filesystem (line 49) | class Filesystem:
    method __init__ (line 54) | def __init__(self, uuid):
    method uuid (line 75) | def uuid(self):
    method devices (line 80) | def devices(self):
    method mounted_points (line 85) | def mounted_points(self):
    method total_size (line 90) | def total_size(self):
    method total_allocated (line 95) | def total_allocated(self):
    method data_size (line 100) | def data_size(self):
    method data_used (line 105) | def data_used(self):
    method data_percentage (line 110) | def data_percentage(self):
    method metadata_size (line 115) | def metadata_size(self):
    method metadata_used (line 120) | def metadata_used(self):
    method metadata_percentage (line 125) | def metadata_percentage(self):
    method system_size (line 130) | def system_size(self):
    method system_used (line 135) | def system_used(self):
    method system_percentage (line 140) | def system_percentage(self):
    method __get_devices (line 145) | def __get_devices(self):
    method __get_mounted_device (line 178) | def __get_mounted_device(self):
    method __get_mounted_points (line 197) | def __get_mounted_points(self):
    method __get_filesystem_info (line 218) | def __get_filesystem_info(self, mounted_point):
    method __str__ (line 278) | def __str__(self):
  function get_btrfs_filesystems (line 289) | def get_btrfs_filesystems(mounted=True):
  function balance_filesystem (line 315) | def balance_filesystem(filter, percentage, mounted_point):
  class BalanceManager (line 340) | class BalanceManager(QThread):
    method __init__ (line 354) | def __init__(self, data_percentage, metadata_percentage, mounted_point):
    method run (line 361) | def run(self):
    method __balance_filesystem (line 383) | def __balance_filesystem(self):
    method on_show_one_window (line 398) | def on_show_one_window(self, one_window):
    method on_refresh_filesystem_statistics (line 406) | def on_refresh_filesystem_statistics(self):

FILE: buttermanager/buttermanager/filesystem/snapshot.py
  class Subvolume (line 44) | class Subvolume:
    method __init__ (line 49) | def __init__(self, subvolume_origin, subvolume_dest, snapshot_name, sn...
    method create_snapshot (line 71) | def create_snapshot(self):
    method delete_snapshots (line 219) | def delete_snapshots(self):
    method delete_origin (line 272) | def delete_origin(self):
    method get_all_snapshots_with_the_same_name (line 308) | def get_all_snapshots_with_the_same_name(self):
  class RootSnapshotChecker (line 322) | class RootSnapshotChecker:
    method __init__ (line 327) | def __init__(self, parent_window):
    method check_root_snapshot (line 336) | def check_root_snapshot(self):
    method open_consolidate_snapshot_window (line 392) | def open_consolidate_snapshot_window(self):
  class Differentiator (line 405) | class Differentiator(QThread):
    method __init__ (line 422) | def __init__(self, snapshot_full_path, operation_type):
    method run (line 429) | def run(self):
    method __calculate_differences (line 451) | def __calculate_differences(self):
    method on_show_one_window (line 584) | def on_show_one_window(self, one_window):
  function delete_specific_snapshot (line 594) | def delete_specific_snapshot(snapshot_full_path):
  function get_subvolume_by_snapshot_name (line 638) | def get_subvolume_by_snapshot_name(snapshot_name):

FILE: buttermanager/buttermanager/manager/upgrader.py
  class Upgrader (line 52) | class Upgrader(QThread):
    method __init__ (line 71) | def __init__(self, include_aur, include_snap, include_flatpak, snapsho...
    method run (line 85) | def run(self):
    method __upgrade_system (line 89) | def __upgrade_system(self):
    method on_disable_gui_buttons (line 276) | def on_disable_gui_buttons(self):
    method on_enable_gui_buttons (line 282) | def on_enable_gui_buttons(self):
    method on_refresh_gui (line 288) | def on_refresh_gui(self):
  class UpdatesChecker (line 295) | class UpdatesChecker(QThread):
    method __init__ (line 307) | def __init__(self):
    method run (line 313) | def run(self):
    method __check_updates (line 317) | def __check_updates(self):
    method __internet_available (line 367) | def __internet_available(self):
  function check_updates (line 384) | def check_updates():

FILE: buttermanager/buttermanager/util/settings.py
  class PropertiesManager (line 80) | class PropertiesManager:
    method __init__ (line 90) | def __init__(self):
    method get_property (line 105) | def get_property(self, property):
    method set_property (line 119) | def set_property(self, property, value):
    method remove_property (line 133) | def remove_property(self, property):
    method set_subvolume (line 145) | def set_subvolume(self, subvolume_selected, snapshot_where, snapshot_p...
    method __store_configuration (line 203) | def __store_configuration(self):

FILE: buttermanager/buttermanager/util/utils.py
  class ConfigManager (line 58) | class ConfigManager:
    method __init__ (line 67) | def __init__(self):
    method configure (line 116) | def configure(self):
    method migrate_properties (line 189) | def migrate_properties(self):
  class Logger (line 233) | class Logger(object):
    method __init__ (line 237) | def __init__(self, class_name):
    method get (line 249) | def get(self):
  class VersionChecker (line 253) | class VersionChecker:
    method __init__ (line 257) | def __init__(self, parent_window):
    method check_version (line 264) | def check_version(self):
  function execute_command (line 297) | def execute_command(command, console=False, root=False):
  function get_percentage (line 340) | def get_percentage(total, parcial):
  function get_number_unit (line 361) | def get_number_unit(number_unit_string):
  function convert_to_bytes (line 384) | def convert_to_bytes(number_unit):
  function exist_program (line 410) | def exist_program(program, root=False):
  function get_subvolumes (line 447) | def get_subvolumes():
  function scale_fonts (line 471) | def scale_fonts(ui_elements):
  function get_desktop_environment (line 485) | def get_desktop_environment():
  function open_file_browser_directory (line 503) | def open_file_browser_directory(parent_window):

FILE: buttermanager/buttermanager/window/windows.py
  class InfoWindow (line 34) | class InfoWindow(QDialog):
    method __init__ (line 39) | def __init__(self, parent, information):
    method init_ui (line 57) | def init_ui(self, information):
  class GeneralInfoWindow (line 89) | class GeneralInfoWindow(QDialog):
    method __init__ (line 94) | def __init__(self, parent, information):
    method init_ui (line 111) | def init_ui(self, information):
  class ConsolidateSnapshotWindow (line 146) | class ConsolidateSnapshotWindow(QDialog):
    method __init__ (line 155) | def __init__(self, parent, snapshot_to_clone_in_root_full_path, root_s...
    method init_ui (line 186) | def init_ui(self):
    method consolidate (line 223) | def consolidate(self):
    method cancel (line 308) | def cancel(self):
  class SnapshotWindow (line 316) | class SnapshotWindow(QMainWindow):
    method __init__ (line 328) | def __init__(self, parent):
    method init_ui (line 341) | def init_ui(self):
    method enable_all_subvolumes (line 386) | def enable_all_subvolumes(self):
    method enable_one_subvolume (line 396) | def enable_one_subvolume(self):
    method take_snapshot (line 406) | def take_snapshot(self):
    method cancel (line 432) | def cancel(self):
    method on_refresh_gui (line 444) | def on_refresh_gui(self):
    method on_enable_buttons (line 450) | def on_enable_buttons(self):
    method on_disable_buttons (line 456) | def on_disable_buttons(self):
    method __disable_buttons (line 462) | def __disable_buttons(self):
    method __enable_buttons (line 472) | def __enable_buttons(self):
  class SubvolumeWindow (line 483) | class SubvolumeWindow(QMainWindow):
    method __init__ (line 492) | def __init__(self, parent):
    method init_ui (line 505) | def init_ui(self):
    method add_subvolume_orig (line 555) | def add_subvolume_orig(self):
    method add_subvolume_dest (line 562) | def add_subvolume_dest(self):
    method add_subvolume (line 569) | def add_subvolume(self):
    method dont_remove_snapshots (line 594) | def dont_remove_snapshots(self):
    method cancel (line 605) | def cancel(self):
    method on_refresh_gui (line 611) | def on_refresh_gui(self):
  class UpdatesWindow (line 618) | class UpdatesWindow(QMainWindow):
    method __init__ (line 631) | def __init__(self, parent, command_line_text):
    method init_ui (line 652) | def init_ui(self):
    method full_system_upgrade (line 696) | def full_system_upgrade(self):
    method full_system_upgrade_without_snapshots (line 706) | def full_system_upgrade_without_snapshots(self):
    method cancel (line 716) | def cancel(self):
  class ProblemsFoundWindow (line 723) | class ProblemsFoundWindow(QMainWindow):
    method __init__ (line 730) | def __init__(self, parent, information):
    method init_ui (line 746) | def init_ui(self, information):
    method exit (line 780) | def exit(self):
  class LogViewWindow (line 788) | class LogViewWindow(QMainWindow):
    method __init__ (line 793) | def __init__(self, parent, log_path):
    method init_ui (line 812) | def init_ui(self):
  class DiffWindow (line 849) | class DiffWindow(QDialog):
    method __init__ (line 860) | def __init__(self):
    method init_ui (line 894) | def init_ui(self):
    method full_operation (line 933) | def full_operation(self):
    method partial_operation (line 940) | def partial_operation(self):

FILE: buttermanager/main.py
  function main (line 6) | def main():
Condensed preview — 42 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (349K chars).
[
  {
    "path": ".gitignore",
    "chars": 1051,
    "preview": "#PyCharm configuration\n.idea/\n\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions"
  },
  {
    "path": "LICENSE",
    "chars": 35147,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 12470,
    "preview": "# ButterManager\n\n## Summary\nButterManager is a BTRFS tool for managing snapshots, balancing filesystems and upgrading th"
  },
  {
    "path": "aur/PKGBUILD",
    "chars": 1615,
    "preview": "# Maintainer: Eloy Garcia Almaden <eloy.garcia.pca@gmail.com>\npkgname=buttermanager\npkgver=2.5.2\npkgrel=0\nepoch=\npkgdesc"
  },
  {
    "path": "aur/README.txt",
    "chars": 97,
    "preview": "This directory contains all the files needed to package ButterManager application for Arch Linux\n"
  },
  {
    "path": "buttermanager/bm_main.py",
    "chars": 748,
    "preview": "from .buttermanager.buttermanager import PasswordWindow\nfrom PyQt5.QtWidgets import QApplication\nimport sys\n\n\ndef main()"
  },
  {
    "path": "buttermanager/buttermanager/__init__.py",
    "chars": 723,
    "preview": "# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>\n#\n# This file is part of buttermanager.\n#\n# This p"
  },
  {
    "path": "buttermanager/buttermanager/buttermanager.py",
    "chars": 53604,
    "preview": "# -*- coding: utf-8 -*-\n#\n# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>\n#\n# This file is part of"
  },
  {
    "path": "buttermanager/buttermanager/exception/__init__.py",
    "chars": 698,
    "preview": "#Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>\n#\n# This file is part of buttermanager.\n#\n# This pr"
  },
  {
    "path": "buttermanager/buttermanager/exception/exception.py",
    "chars": 1497,
    "preview": "# -*- coding: utf-8 -*-\n#\n# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>\n#\n# This file is part of"
  },
  {
    "path": "buttermanager/buttermanager/filesystem/__init__.py",
    "chars": 700,
    "preview": "# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>\n#\n# This file is part of buttermanager.\n#\n# This p"
  },
  {
    "path": "buttermanager/buttermanager/filesystem/filesystem.py",
    "chars": 14934,
    "preview": "# -*- coding: utf-8 -*-\n#\n# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>\n#\n# This file is part of"
  },
  {
    "path": "buttermanager/buttermanager/filesystem/snapshot.py",
    "chars": 34637,
    "preview": "# -*- coding: utf-8 -*-\n#\n# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>\n#\n# This file is part of"
  },
  {
    "path": "buttermanager/buttermanager/manager/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "buttermanager/buttermanager/manager/upgrader.py",
    "chars": 18468,
    "preview": "# -*- coding: utf-8 -*-\n#\n# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>\n#\n# This file is part of"
  },
  {
    "path": "buttermanager/buttermanager/ui/ConsolidateSnapshotWindow.ui",
    "chars": 1414,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>Dialog</class>\n <widget class=\"QDialog\" name=\"Dialog\">"
  },
  {
    "path": "buttermanager/buttermanager/ui/GeneralInfoWindow.ui",
    "chars": 1392,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>Dialog</class>\n <widget class=\"QDialog\" name=\"Dialog\">"
  },
  {
    "path": "buttermanager/buttermanager/ui/InfoWindow.ui",
    "chars": 1302,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>Dialog</class>\n <widget class=\"QDialog\" name=\"Dialog\">"
  },
  {
    "path": "buttermanager/buttermanager/ui/LogViewWindow.ui",
    "chars": 1208,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>LogViewWindow</class>\n <widget class=\"QMainWindow\" nam"
  },
  {
    "path": "buttermanager/buttermanager/ui/MainWindow.ui",
    "chars": 46362,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>MainWindow</class>\n <widget class=\"QMainWindow\" name=\""
  },
  {
    "path": "buttermanager/buttermanager/ui/PasswordWindow.ui",
    "chars": 4683,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>PasswordWindow</class>\n <widget class=\"QMainWindow\" na"
  },
  {
    "path": "buttermanager/buttermanager/ui/ProblemsFoundWindow.ui",
    "chars": 1878,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>SnapshotWindow</class>\n <widget class=\"QMainWindow\" na"
  },
  {
    "path": "buttermanager/buttermanager/ui/SnapshotWindow.ui",
    "chars": 3862,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>SnapshotWindow</class>\n <widget class=\"QMainWindow\" na"
  },
  {
    "path": "buttermanager/buttermanager/ui/SubvolumeWindow.ui",
    "chars": 5852,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>SubvolumeWindow</class>\n <widget class=\"QMainWindow\" n"
  },
  {
    "path": "buttermanager/buttermanager/ui/UpdatesWindow.ui",
    "chars": 2891,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>UpdatesWindow</class>\n <widget class=\"QMainWindow\" nam"
  },
  {
    "path": "buttermanager/buttermanager/util/__init__.py",
    "chars": 698,
    "preview": "#Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>\n#\n# This file is part of buttermanager.\n#\n# This pr"
  },
  {
    "path": "buttermanager/buttermanager/util/settings.py",
    "chars": 8806,
    "preview": "# -*- coding: utf-8 -*-\n#\n# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>\n#\n# This file is part of"
  },
  {
    "path": "buttermanager/buttermanager/util/utils.py",
    "chars": 22055,
    "preview": "# -*- coding: utf-8 -*-\n#\n# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>\n#\n# This file is part of"
  },
  {
    "path": "buttermanager/buttermanager/window/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "buttermanager/buttermanager/window/windows.py",
    "chars": 33755,
    "preview": "# -*- coding: utf-8 -*-\n#\n# Copyright 2018-2019 Eloy García Almadén <eloy.garcia.pca@gmail.com>\n#\n# This file is part of"
  },
  {
    "path": "buttermanager/main.py",
    "chars": 409,
    "preview": "from buttermanager.buttermanager import PasswordWindow\nfrom PyQt5.QtWidgets import QApplication\nimport sys\n\n\ndef main():"
  },
  {
    "path": "doc/README.md",
    "chars": 7545,
    "preview": "# Documentation\nThis is the documentation related to [Buttermanager](https://github.com/egara/buttermanager) GUI tool fo"
  },
  {
    "path": "install/native_install.sh",
    "chars": 3712,
    "preview": "#!/bin/bash\n\n# Script for installing ButterManager\n# -----------------------------------\n#\n# @author: Eloy García Almadé"
  },
  {
    "path": "install/uninstall.sh",
    "chars": 656,
    "preview": "#!/bin/bash\n\n# Script for uninstalling ButterManager\n# -------------------------------------\n#\n# @author: Eloy García Al"
  },
  {
    "path": "install/venv_install.sh",
    "chars": 3979,
    "preview": "#!/bin/bash\n\n# Script for installing ButterManager\n# -----------------------------------\n#\n# @author: Eloy García Almadé"
  },
  {
    "path": "packaging/buttermanager.desktop",
    "chars": 348,
    "preview": "[Desktop Entry]\nName=ButterManager\nGenericName=ButterManager\nComment=ButterManager, a BTRFS tool for snapshoting, balanc"
  },
  {
    "path": "packaging/buttermanager_venv.desktop",
    "chars": 448,
    "preview": "[Desktop Entry]\nName=ButterManager\nGenericName=ButterManager\nComment=ButterManager, a BTRFS tool for snapshoting, balanc"
  },
  {
    "path": "requirements.txt",
    "chars": 58,
    "preview": "PyQt5>=5.10.1\nPyQt5-sip>=12.7.0\nPyYAML>=4.2b1\nsip>=4.19.8\n"
  },
  {
    "path": "rpm/README.txt",
    "chars": 227,
    "preview": "This directory contains all the files needed to package ButterManager application for RPM based distributions.\n\nThis pac"
  },
  {
    "path": "rpm/buttermanager.spec",
    "chars": 2126,
    "preview": "Name:           buttermanager\nVersion:        2.5.2\nRelease:        0%{?dist}\nSummary:        Tool for managing Btrfs sn"
  },
  {
    "path": "setup.py",
    "chars": 1435,
    "preview": "import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n    long_description = fh.read()\n\nsetuptools.setup(\n    name=\"butt"
  },
  {
    "path": "version.txt",
    "chars": 6,
    "preview": "2.5.2\n"
  }
]

About this extraction

This page contains the full source code of the egara/buttermanager GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 42 files (325.7 KB), approximately 71.7k tokens, and a symbol index with 196 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!