From dc63e9b7d9e57e5b1df9bc878fa011a1e87e5585 Mon Sep 17 00:00:00 2001 From: Tony George Date: Sat, 18 Nov 2017 11:17:49 +0530 Subject: [PATCH] Initial commit --- .bzrignore | 15 + .gitignore | 15 + AUTHORS | 3 + BUILD_CONFIG | 6 + COPYING | 674 +++++ INSTALL | 6 + LICENSE.md | 166 ++ MANUAL.md | 379 +++ NOTES | 0 build-deb.sh | 48 + build-installers.sh | 49 + build-source.sh | 46 + build.sh | 2 + debian/changelog | 25 + debian/compat | 1 + debian/control | 17 + debian/copyright | 23 + debian/docs | 0 debian/rules | 15 + debian/source/format | 1 + makefile | 14 + release/sanity.config | 7 + src/.ee.swp | Bin 0 -> 1024 bytes src/.uu.swp | Bin 0 -> 1024 bytes src/Gtk/AptikGtk.vala | 154 + src/Gtk/MainWindow.vala | 793 +++++ src/Gtk/RepoWindow.vala | 378 +++ src/Gtk/TermBox.vala | 301 ++ src/Gtk/TerminalWindow.vala | 136 + src/Messages.vala | 77 + src/README | 7 + src/Utility/Console/AppLock.vala | 106 + src/Utility/Console/AsyncTask.vala | 570 ++++ src/Utility/Console/Device.vala | 2586 +++++++++++++++++ src/Utility/Console/MountEntry.vala | 46 + src/Utility/Console/TeeJee.FileSystem.vala | 1095 +++++++ src/Utility/Console/TeeJee.Logging.vala | 192 ++ src/Utility/Console/TeeJee.Misc.vala | 349 +++ src/Utility/Console/TeeJee.Process.vala | 542 ++++ src/Utility/Console/TeeJee.System.vala | 561 ++++ src/Utility/Console/TimeoutCounter.vala | 96 + src/Utility/Console/Version.vala | 94 + src/Utility/Gtk/AboutWindow.vala | 526 ++++ src/Utility/Gtk/CellRendererProgress2.vala | 18 + src/Utility/Gtk/CustomMessageDialog.vala | 185 ++ src/Utility/Gtk/DonationWindow.vala | 145 + src/Utility/Gtk/ExtendedTreeView.vala | 128 + src/Utility/Gtk/GtkHelper.vala | 1270 ++++++++ src/Utility/Gtk/IconCache.vala | 103 + src/Utility/Gtk/IconManager.vala | 392 +++ src/Utility/Gtk/LoadingWindow.vala | 120 + src/Utility/LicenseText.vala | 342 +++ src/Utility/TeeJee.JsonHelper.vala | 103 + src/aptik-gtk-uninstall | 125 + src/aptik-gtk.desktop | 12 + src/makefile | 70 + src/share/aptik-gtk/images/backup.svg | 84 + src/share/aptik-gtk/images/clock.png | Bin 0 -> 3062 bytes src/share/aptik-gtk/images/config-users.svg | 307 ++ src/share/aptik-gtk/images/config.svg | 117 + src/share/aptik-gtk/images/donate.svg | 458 +++ src/share/aptik-gtk/images/download.svg | 368 +++ src/share/aptik-gtk/images/drive-harddisk.png | Bin 0 -> 2640 bytes .../aptik-gtk/images/edit-select-all.png | Bin 0 -> 479 bytes src/share/aptik-gtk/images/help-info.svg | 291 ++ src/share/aptik-gtk/images/item-blue.png | Bin 0 -> 594 bytes src/share/aptik-gtk/images/item-gray.png | Bin 0 -> 589 bytes src/share/aptik-gtk/images/item-green.png | Bin 0 -> 617 bytes src/share/aptik-gtk/images/item-pink.png | Bin 0 -> 598 bytes src/share/aptik-gtk/images/item-red.png | Bin 0 -> 613 bytes src/share/aptik-gtk/images/item-yellow.png | Bin 0 -> 593 bytes src/share/aptik-gtk/images/lock.svg | 93 + .../aptik-gtk/images/package-x-generic.png | Bin 0 -> 976 bytes .../aptik-gtk/images/preferences-system.png | Bin 0 -> 6561 bytes .../aptik-gtk/images/preferences-theme.svg | 382 +++ src/share/aptik-gtk/images/restore.svg | 61 + src/share/aptik-gtk/images/user-home.svg | 193 ++ .../images/x-system-software-sources.svg | 331 +++ src/share/pixmaps/aptik-gtk.svg | 51 + 79 files changed, 15870 insertions(+) create mode 100644 .bzrignore create mode 100644 .gitignore create mode 100644 AUTHORS create mode 100644 BUILD_CONFIG create mode 100644 COPYING create mode 100644 INSTALL create mode 100644 LICENSE.md create mode 100644 MANUAL.md create mode 100644 NOTES create mode 100755 build-deb.sh create mode 100755 build-installers.sh create mode 100755 build-source.sh create mode 100644 build.sh create mode 100644 debian/changelog create mode 100644 debian/compat create mode 100644 debian/control create mode 100644 debian/copyright create mode 100644 debian/docs create mode 100755 debian/rules create mode 100644 debian/source/format create mode 100644 makefile create mode 100644 release/sanity.config create mode 100644 src/.ee.swp create mode 100644 src/.uu.swp create mode 100644 src/Gtk/AptikGtk.vala create mode 100644 src/Gtk/MainWindow.vala create mode 100644 src/Gtk/RepoWindow.vala create mode 100644 src/Gtk/TermBox.vala create mode 100644 src/Gtk/TerminalWindow.vala create mode 100644 src/Messages.vala create mode 100644 src/README create mode 100644 src/Utility/Console/AppLock.vala create mode 100644 src/Utility/Console/AsyncTask.vala create mode 100644 src/Utility/Console/Device.vala create mode 100644 src/Utility/Console/MountEntry.vala create mode 100644 src/Utility/Console/TeeJee.FileSystem.vala create mode 100644 src/Utility/Console/TeeJee.Logging.vala create mode 100644 src/Utility/Console/TeeJee.Misc.vala create mode 100644 src/Utility/Console/TeeJee.Process.vala create mode 100644 src/Utility/Console/TeeJee.System.vala create mode 100644 src/Utility/Console/TimeoutCounter.vala create mode 100644 src/Utility/Console/Version.vala create mode 100644 src/Utility/Gtk/AboutWindow.vala create mode 100644 src/Utility/Gtk/CellRendererProgress2.vala create mode 100644 src/Utility/Gtk/CustomMessageDialog.vala create mode 100644 src/Utility/Gtk/DonationWindow.vala create mode 100644 src/Utility/Gtk/ExtendedTreeView.vala create mode 100644 src/Utility/Gtk/GtkHelper.vala create mode 100644 src/Utility/Gtk/IconCache.vala create mode 100644 src/Utility/Gtk/IconManager.vala create mode 100644 src/Utility/Gtk/LoadingWindow.vala create mode 100644 src/Utility/LicenseText.vala create mode 100644 src/Utility/TeeJee.JsonHelper.vala create mode 100755 src/aptik-gtk-uninstall create mode 100644 src/aptik-gtk.desktop create mode 100644 src/makefile create mode 100644 src/share/aptik-gtk/images/backup.svg create mode 100755 src/share/aptik-gtk/images/clock.png create mode 100644 src/share/aptik-gtk/images/config-users.svg create mode 100644 src/share/aptik-gtk/images/config.svg create mode 100755 src/share/aptik-gtk/images/donate.svg create mode 100644 src/share/aptik-gtk/images/download.svg create mode 100755 src/share/aptik-gtk/images/drive-harddisk.png create mode 100755 src/share/aptik-gtk/images/edit-select-all.png create mode 100644 src/share/aptik-gtk/images/help-info.svg create mode 100644 src/share/aptik-gtk/images/item-blue.png create mode 100644 src/share/aptik-gtk/images/item-gray.png create mode 100644 src/share/aptik-gtk/images/item-green.png create mode 100644 src/share/aptik-gtk/images/item-pink.png create mode 100644 src/share/aptik-gtk/images/item-red.png create mode 100644 src/share/aptik-gtk/images/item-yellow.png create mode 100644 src/share/aptik-gtk/images/lock.svg create mode 100644 src/share/aptik-gtk/images/package-x-generic.png create mode 100755 src/share/aptik-gtk/images/preferences-system.png create mode 100644 src/share/aptik-gtk/images/preferences-theme.svg create mode 100644 src/share/aptik-gtk/images/restore.svg create mode 100644 src/share/aptik-gtk/images/user-home.svg create mode 100644 src/share/aptik-gtk/images/x-system-software-sources.svg create mode 100644 src/share/pixmaps/aptik-gtk.svg diff --git a/.bzrignore b/.bzrignore new file mode 100644 index 0000000..ce3ae56 --- /dev/null +++ b/.bzrignore @@ -0,0 +1,15 @@ +src/aptik +src/aptik-gtk +designs/ +release/source +release/amd64 +release/i386 +release/armel +release/armhf +release/*.deb +release/*.run +*.geany +.git +*.c +*.o +*~ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..956bf3d --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +src/aptik +src/aptik-gtk +designs/ +release/source +release/amd64 +release/i386 +release/armel +release/armhf +release/*.deb +release/*.run +*.geany +.bzr +*.c +*.o +*~ diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..fc2c1ac --- /dev/null +++ b/AUTHORS @@ -0,0 +1,3 @@ + +Copyright (C) 2017 Tony George (teejeetech@gmail.com) + diff --git a/BUILD_CONFIG b/BUILD_CONFIG new file mode 100644 index 0000000..b5ea60d --- /dev/null +++ b/BUILD_CONFIG @@ -0,0 +1,6 @@ + +app_fullname="Aptik NG GTK" +app_name="aptik-gtk" +pkg_name="aptik-ng-gtk" +pkg_version=$(dpkg-parsechangelog --show-field Version) +git_origin="" diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff --git a/INSTALL b/INSTALL new file mode 100644 index 0000000..d13eccb --- /dev/null +++ b/INSTALL @@ -0,0 +1,6 @@ + +# build +make all + +# install +sudo make install diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..5f5ff16 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,166 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/MANUAL.md b/MANUAL.md new file mode 100644 index 0000000..ad60b07 --- /dev/null +++ b/MANUAL.md @@ -0,0 +1,379 @@ +## User Manual + +``` +Usage: aptik [options] + +▰▰▰ Software Repositories ▰▰▰ + +Commands: + --backup-repos Save list of software repositories + --restore-repos Add missing software repositories from backup + --import-missing-keys Find and import missing keys for apt repos + +Supports: apt (Debian & Derivatives), pacman (Arch & Derivatives), +dnf/yum (Fedora & Derivatives) + +▰▰▰ Downloaded Packages ▰▰▰ + +Commands: + --backup-cache Copy downloaded packages from system cache + --restore-cache Copy packages to system cache from backup + --clear-cache Remove downloaded packages from system cache + +Supports: apt (Debian & Derivatives), pacman (Arch & Derivatives) + +▰▰▰ Installed Software ▰▰▰ + +Commands: + --list-installed List installed packages + --list-available List available packages + --list-foreign List non-native packages + --list-extra List extra packages installed by user + --list-{default|dist|base} List default packages for linux distribution + --backup-packages Save list of installed packages + --restore-packages Install missing packages from backup + +Supports: apt (Debian & Derivatives), pacman (Arch & Derivatives), +dnf/yum (Fedora & Derivatives) + +▰▰▰ User Accounts ▰▰▰ + +Commands: + --list-users List users + --list-users-all List all users (including system user accounts) + --backup-users Backup users + --restore-users Restore users from backup + +▰▰▰ Groups ▰▰▰ + +Commands: + --list-groups List groups + --list-groups-all List all groups (including system groups) + --backup-groups Backup groups + --restore-groups Restore groups from backup + +▰▰▰ Home Directory Data ▰▰▰ + +Commands: + --backup-home Backup data in users' home directories + --restore-home Restore data in users' home directories from backup + --fix-ownership Updates ownership for users' home directory contents + +Options: + --users Users to backup and restore + default: all users + + --duplicity Use duplicity for backup instead of TAR + default: TAR + + --password Password for encryption/decryption with duplicity + default: 'aptik' + + --full Do full backup with duplicity + default: incremental if backup exists, else full + + --exclude-hidden Exclude hidden files and directories (app configs) + default: include + +▰▰▰ Filesystem Mounts ▰▰▰ + +Commands: + --list-mounts List /etc/fstab and /etc/crypttab entries + --backup-mounts Backup /etc/fstab and /etc/crypttab entries + --restore-mounts Restore /etc/fstab and /etc/crypttab entries from backup + +▰▰▰ Dconf Settings ▰▰▰ + +Commands: + --list-dconf List dconf settings changed by user + --backup-dconf Backup dconf settings changed by user + --restore-dconf Restore dconf settings from backup + +Options: + --users Users to backup and restore + default: all users + +▰▰▰ Scheduled Tasks ▰▰▰ + +Commands: + --list-cron List cron tasks + --backup-cron Backup cron tasks + --restore-cron Restore cron tasks + +Options: + --users Users to backup and restore + default: all users + +▰▰▰ All Items ▰▰▰ + +Commands: + --backup-all Backup all items + --restore-all Restore all items from backup + +▰▰▰ Common ▰▰▰ + +Options: + --basepath Backup directory (default: current directory) + --scripted Run in non-interactive mode + --dry-run Show actions for restore without making changes to system + --help Show all options +``` + +### Software Repositories + +#### Backup + +Usage: `aptik --backup-repos` + +Following actions are executed for backup: + +1. Debian-based distros + + 1. Launchpad PPA names are read from files in `/etc/apt/sources.list.d`. Names are saved to file `/repos/launchpad-ppas.list`. This file can be edited to comment-out or remove lines for unwanted repos. + 2. Third party PPAs are determined by reading list files in `/etc/apt/sources.list.d`. Source lines are saved to file `/repos/.list`. Files can be deleted from the backup folder for unwanted repos. + 3. Apt keys are exported to file `/repos/apt.keys` + +2. Fedora-based distros - Not supported + +3. Arch-based distros + 1. Custom repos are read from file `/etc/pacman.conf`. Source lines are saved to file `/repos/.list`. Files can be deleted from the backup folder for unwanted repos. + 2. Pacman keys are exported to file `/repos/pacman.keys` + +#### Restore + +Usage: `aptik --restore-repos` + +Following actions are executed for restore: + +1. Debian-based distros + 1. Missing Launchpad PPAs are added using command `add-apt-repository` + 2. Third party PPAs are installed by copying list file from backup folder to `/etc/apt/sources.list.d`. If the repo source lines contain release codename (trusty, xenial, etc), and codename does not match current system, then it will be skipped. + 3. Apt keys are imported from file `/repos/pacman.keys` + 4. Package information is updated by running `apt update` +2. Fedora-based distros + 1. Restoring repos is not supported. + 2. Package information is updated by running `dnf check-update` +3. Arch-based distros + 1. Custom repos are installed by appending the source lines to `/etc/pacman.conf` + 2. Pacman keys are imported from file `/repos/pacman.keys` + 3. Package information is updated by running `pacman -Sy` + +### Downloaded Packages + +#### Backup + +Usage: `aptik --backup-cache` + +Following actions are executed for backup: + +1. Downloaded packages are copied from system cache to backup location `/cache` using `rsync` command + * Debian-based distros - Copied from `/var/cache/apt/archives` + * Fedora-based distros - Not supported + * Arch-based distros - Copied from `/var/cache/pacman/pkg` + + +#### Restore + +Usage: `aptik --restore-cache` + +Following actions are executed for restore: + +1. Packages are copied from backup location to system cache using `rsync` + +### Installed Packages + +#### Backup + +Usage: `aptik --backup-packages` + +Following actions are executed for backup: + +1. List of installed packages are saved to `/packages/installed.list`. This file is saved only for reference and is not used during restore. + +2. List of installed packages are filtered to **remove** the following: + + * Kernel packages - `linux-headers*`, `linux-signed*`, `linux-tools*` + * Packages that were auto-installed as dependencies for other packages. + * Debian-based distros - Determined using `aptitude` and will be filtered out + * Other distros - Cannot be determined and will not be filtered out + * Packages that are part of the Linux distribution base. + * Debian-based - Determined by reading `/var/log/installer/initial-status.gz` and will be filtered out. Cannot be determined if this file is missing on the system. + * Other distros - Cannot be determined and will not be filtered out + +3. List of filtered packages are saved to `/packages/selected.list`. This file can be edited to comment-out or remove lines for unwanted packages. + +#### Restore + +Usage: `aptik --restore-packages` + +Following actions are executed for restore: + 1. List of packages are read from `/packages/selected.list`. Packages that are not installed, but available in repositories, will be installed using the package manager. + * Debian-based distros - Installed using `aptitude`, `apt-fast`, `apt-get` or `apt` in order of preference + * Fedora-based distros - Installed using `dnf` or `yum` in order of preference + * Arch-based distros - Installed using `pacman` + + 2. Debian-based distros - Any deb files in backup folder `/debs` will be installed using `apt` or `gdebi` in order of preference. + + +### Users + +#### Backup + +Usage: `aptik --backup-users` + +Following actions are executed for backup: + +1. Entries in `/etc/passwd` and `/etc/shadow` are saved to backup folder `/users` for human users (UID = 0 or UID >= 1000 and UID != 65534). User's line in both files are saved as `.passwd` and `.shadow` in the backup folder. You can delete the files for any users that you do not wish to restore. + +#### Restore + +Usage: `aptik --restore-users` + +Following actions are executed for restore: + +1. *Missing users* are added from backup folder `/users` + 1. Missing users are added using `useradd` command + 2. User's full name, home directory path, and other fields are updated in `/etc/passwd`. User's UID will not be updated and remains same as the value generated by `useradd` command. + 3. User's password field and password expiry rules are updated in `/etc/shadow` + + + +### Groups + +#### Backup + +Usage: `aptik --backup-groups` + +Following actions are executed for backup: + +1. Entries in `/etc/group` and `/etc/gshadow` are saved to backup folder `/groups` for non-system groups (GID >= 1000 and GID != 65534). Group's line in both files are saved as `.group` and `.gshadow` in the backup folder. You can delete the files for any groups that you do not wish to restore. +2. For all groups, the list of users in the group are saved in file `/groups/memberships.list`. + +#### Restore + +Usage: `aptik --restore-groups` + +Following actions are executed for restore: + +1. *Missing groups* are added from backup folder `/groups` + 1. Missing users are added using `groupadd` command + 2. Group's password and users field are updated in `/etc/group`. Group's GID will not be updated and remains same as the value generated by `groupadd` command. + 3. Group's password, admin and member fields are updated in `/etc/gshadow` +2. *Missing members* are added to groups + 1. Missing members are added to groups by reading the file `/groups/memberships.list`. Members are added directly by updating `/etc/group` + +### Home Data + +#### Backup + +Usage: `aptik --backup-home` + +Following actions are executed for backup: + +1. For each user, the contents of home directory are archived using TAR + GZIP and saved to file `/home//data.tar.gz`. Full backup is created every time a backup is taken. + +2. When creating backups using **duplicity** (option `--duplicity`), data is saved to folder `/home/`. + + - Incremental backups are created if an existing backup is found. Full backups are created if there is no existing backup, or if full backup was specified by user (option `--full`). + - Backups are encrypted with specified password (option `--password `). A default password `aptik` is used if none is specified. + +3. Backups can be created for specific users with option `--users `. Specify a comma-separated list of user names without space. + +4. Some directories are excluded by default to save space and avoid issues after restore. + + ``` + ~/.thumbnails + ~/.cache + ~/.dbus + ~/.gvfs + ~/.config/dconf/user + ~/.local/share/Trash + ~/.local/share/trash + ~/.mozilla/firefox/*.default/Cache + ~/.mozilla/firefox/*.default/OfflineCache + ~/.opera/cache + ~/.kde/share/apps/kio_http/cache + ~/.kde/share/cache/http + ``` + +5. Hidden files and folders in home directories can be excluded with option `--exclude-hidden` . These files and folders contain *user-specific application and system settings*. These can be excluded if you wish to only migrate your data, without migrating your application settings. + +#### Restore + +Usage: `aptik --restore-home` + +Following actions are executed for restore: + +1. For each user, the TAR file backup `/home//data.tar.gz` is extracted to the user's home directory. Files are restored to original locations along with original permissions and timestamps. +2. For each user, the ownership is updated for file and folders in user's home directory. This ensures that all files in home directory are owned by the user. +3. When restoring a duplicity backup, the steps are similar. Data is restored from backup files created by duplicity in `/home/`. + {0}. The password should be specified during restore if it was specified during backup (option `--password `). A default password `aptik` is used if none is specified. +4. Backups can be restored for specific users with option `--users `. Specify a comma-separated list of user names without space. + +### DConf Settings + +dconf database stores application settings for users. Aptik can backup and restore any changes that were made to the default settings. The binary database file for dconf `~/.config/dconf/user` will be excluded while taking backup of user's home directories. + +#### Backup + +Usage: `aptik --backup-dconf` + +Following actions are executed for backup: + +1. For each user, dconf settings that are different from defaults are dumped to backup file `/dconf//dconf.settings` + +#### Restore + +Usage: `aptik --restore-dconf` + +Following actions are executed for restore: + +1. For each user, dconf settings are imported from backup file `/dconf//dconf.settings` + +### Scheduled Tasks + +#### Backup + +Usage: `aptik --backup-cron` + +Following actions are executed for backup: + +1. For each user, crontab entries are dumped to backup file `/cron/.crontab` +2. Script files in system directories `/etc/cron.*` are saved to backup folders `/cron/cron.*` + +#### Restore + +Usage: `aptik --restore-cron` + +Following actions are executed for restore: + +1. For each user, crontab file is replaced from backup file `/cron/.crontab`. +2. Script files are copied from backup folders `/cron/cron.*` to system directories `/etc/cron.*` +3. Permissions are updated to 644 for files in folder `/etc/cron.d` +4. Permissions are updated to 755 for files in folder `/etc/cron.{daily,hourly,monthly,weekly}` + +### Mount Entries + +#### Backup + +Usage: `aptik --backup-mounts` + +Following actions are executed for backup: + +1. Entries in `/etc/fstab` and `/etc/crypttab` are saved to backup folder `/mounts` . Entries are saved individually as `_.fstab` and `_.crypttab` in the backup folder. You can delete the files for any mount entries that you do not wish to restore. +2. Device names like `/dev/sda1` and `/dev/mapper/sd2_crypt` will be replaced by UUIDs like `UUID=576be21b-3c3a-4287-b971-40b8e8b39823` while saving backup files. This makes the entries portable so that they can be used on other systems where the device names may be different. + +#### Restore + +Usage: `aptik --restore-mounts` + +Following actions are executed for restore: + +1. Backups are created for `/etc/fstab` and `/etc/crypttab` by moving existing files to `/etc/fstab.bkup.` and `/etc/crypttab.bkup.` +2. Extra entries in the backup folder are added to `/etc/fstab` and `/etc/crypttab` . Existing entries in `/etc/fstab` and `/etc/crypttab` will be preserved. Extra entries are determined by checking if the mount point is used by an existing entry. + +**Notes:** +* All entries are sorted on mount point field before the fstab file is written to disk. This ensures that base mount points are mounted before mounting subdirectories. +* Backup entry for `/boot/efi` will not be added, if not already existing in `/etc/fstab` +* It is recommended to review changes after restore completes. Run `sudo aptik --list-mounts` or `cat /etc/fstab; cat /etc/crypttab;` to view the updated entries. + diff --git a/NOTES b/NOTES new file mode 100644 index 0000000..e69de29 diff --git a/build-deb.sh b/build-deb.sh new file mode 100755 index 0000000..d7d24a6 --- /dev/null +++ b/build-deb.sh @@ -0,0 +1,48 @@ +#!/bin/bash + +backup=`pwd` +DIR="$( cd "$( dirname "$0" )" && pwd )" +cd $DIR + +. ./BUILD_CONFIG + +sh build-source.sh + +rm -fv release/${pkg_name}-*.deb + +build_deb_for_dist() { + +dist=$1 +arch=$2 + +echo "" +echo "==========================================================================" +echo " build-deb.sh : $dist-$arch" +echo "==========================================================================" +echo "" + +rm -rfv release/${arch} +mkdir -pv release/${arch} + +echo "-------------------------------------------------------------------------" + +pbuilder-dist $dist $arch build release/source/${pkg_name}*.dsc --buildresult release/$arch + +if [ $? -ne 0 ]; then cd "$backup"; echo "Failed"; exit 1; fi + +echo "--------------------------------------------------------------------------" + +cp -pv --no-preserve=ownership release/${arch}/${pkg_name}*.deb release/${pkg_name}-v${pkg_version}-${arch}.deb + +if [ $? -ne 0 ]; then cd "$backup"; echo "Failed"; exit 1; fi + +echo "--------------------------------------------------------------------------" + +} + +build_deb_for_dist xenial i386 +build_deb_for_dist xenial amd64 +#build_deb_for_dist stretch armel +#build_deb_for_dist stretch armhf + +cd "$backup" diff --git a/build-installers.sh b/build-installers.sh new file mode 100755 index 0000000..7b2fc71 --- /dev/null +++ b/build-installers.sh @@ -0,0 +1,49 @@ +#!/bin/bash + +backup=`pwd` +DIR="$( cd "$( dirname "$0" )" && pwd )" +cd $DIR + +. ./BUILD_CONFIG + +rm -vf release/*.run +rm -vf release/*.deb + +# build debs +sh build-deb.sh + + +for arch in i386 amd64 +do + +rm -rfv release/${arch}/files +mkdir -pv release/${arch}/files + +echo "" +echo "==========================================================================" +echo " build-installers.sh : $arch" +echo "==========================================================================" +echo "" + +dpkg-deb -x release/${pkg_name}-v${pkg_version}-${arch}.deb release/${arch}/files + +if [ $? -ne 0 ]; then cd "$backup"; echo "Failed"; exit 1;fi + +echo "--------------------------------------------------------------------------" + +rm -rfv release/${arch}/${pkg_name}*.* # remove source files created by pbuilder +cp -pv --no-preserve=ownership release/sanity.config release/${arch}/sanity.config +sanity --generate --base-path release/${arch} --out-path release --arch ${arch} + +if [ $? -ne 0 ]; then cd "$backup"; echo "Failed"; exit 1; fi + +mv -v release/*${arch}.run release/${pkg_name}-v${pkg_version}-${arch}.run + +echo "--------------------------------------------------------------------------" + +done + +cp -vf release/*.run ../PACKAGES/ +cp -vf release/*.deb ../PACKAGES/ + +cd "$backup" diff --git a/build-source.sh b/build-source.sh new file mode 100755 index 0000000..3b0c906 --- /dev/null +++ b/build-source.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +backup=`pwd` +DIR="$( cd "$( dirname "$0" )" && pwd )" +cd "$DIR" + +. ./BUILD_CONFIG + +echo "" +echo "==========================================================================" +echo " build-source.sh" +echo "==========================================================================" +echo "" + +echo "app_name: $app_name" +echo "pkg_name: $pkg_name" +echo "--------------------------------------------------------------------------" + +# clean build dir + +rm -rfv /tmp/builds +mkdir -pv /tmp/builds + +make clean + +rm -rfv release/source +mkdir -pv release/source + +echo "--------------------------------------------------------------------------" + +# build source package +dpkg-source --build ./ + +mv -vf ../$pkg_name*.dsc release/source/ +mv -vf ../$pkg_name*.tar.xz release/source/ + +if [ $? -ne 0 ]; then cd "$backup"; echo "Failed"; exit 1; fi + +echo "--------------------------------------------------------------------------" + +# list files +ls -l release/source + +echo "-------------------------------------------------------------------------" + +cd "$backup" diff --git a/build.sh b/build.sh new file mode 100644 index 0000000..c8add27 --- /dev/null +++ b/build.sh @@ -0,0 +1,2 @@ + +make 2>&1 | grep -E --color=never 'error:|.vala:.*warning:' | grep -E --color=always "error:|$" diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 0000000..dba8146 --- /dev/null +++ b/debian/changelog @@ -0,0 +1,25 @@ +aptik (17.9.1) xenial; urgency=medium + + * Beta 10 Update 1 + + -- Tony George Mon, 18 Sep 2017 08:00:00 +0530 + +aptik (17.9) xenial; urgency=medium + + * Beta 10 + + -- Tony George Sun, 17 Sep 2017 10:00:00 +0530 + + +aptik (17.7.1) xenial; urgency=medium + + * Beta 9 + + -- Tony George Sun, 09 Jul 2017 10:00:00 +0530 + + +aptik (17.7) xenial; urgency=medium + + * Initial release + + -- Tony George Sat, 01 Jul 2017 10:00:00 +0530 diff --git a/debian/compat b/debian/compat new file mode 100644 index 0000000..45a4fb7 --- /dev/null +++ b/debian/compat @@ -0,0 +1 @@ +8 diff --git a/debian/control b/debian/control new file mode 100644 index 0000000..a0b247c --- /dev/null +++ b/debian/control @@ -0,0 +1,17 @@ +Source: aptik-ng +Section: utils +Priority: extra +Maintainer: Tony George +Build-Depends: debhelper (>= 8.0.0), autotools-dev, valac, libgee-0.8-dev, libjson-glib-dev +Standards-Version: 3.9.3 +Homepage: http://teejeetech.blogspot.in/ +#Vcs-Git: +#Vcs-Browser: + +Package: aptik-ng +Architecture: any +Depends: ${shlibs:Depends}, ${misc:Depends}, apt, aptitude, gdebi, apt-transport-https, pv +#Recommends: +Replaces: aptik +Description: Aptik system migration utility + Aptik system migration utility diff --git a/debian/copyright b/debian/copyright new file mode 100644 index 0000000..a67bead --- /dev/null +++ b/debian/copyright @@ -0,0 +1,23 @@ +Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: aptik +Source: + +Files: * +Copyright: 2013 Tony George +License: GPL-2+ + This package 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 2 of the License, or + (at your option) any later version. + . + This package 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 + . + On Debian systems, the complete text of the GNU General + Public License version 2 can be found in "/usr/share/common-licenses/GPL-2". + diff --git a/debian/docs b/debian/docs new file mode 100644 index 0000000..e69de29 diff --git a/debian/rules b/debian/rules new file mode 100755 index 0000000..465d63b --- /dev/null +++ b/debian/rules @@ -0,0 +1,15 @@ +#!/usr/bin/make -f +# -*- makefile -*- +# Sample debian/rules that uses debhelper. +# This file was originally written by Joey Hess and Craig Small. +# As a special exception, when this file is copied by dh-make into a +# dh-make output file, you may use that output file without restriction. +# This special exception was added by Craig Small in version 0.37 of dh-make. + +# Uncomment this to turn on verbose mode. +#export DH_VERBOSE=1 + +override_dh_usrlocal: + +%: + dh $@ --with autotools-dev diff --git a/debian/source/format b/debian/source/format new file mode 100644 index 0000000..89ae9db --- /dev/null +++ b/debian/source/format @@ -0,0 +1 @@ +3.0 (native) diff --git a/makefile b/makefile new file mode 100644 index 0000000..545f291 --- /dev/null +++ b/makefile @@ -0,0 +1,14 @@ +all: + cd src; make all + +clean: + cd src; make clean + +aptik-console: + cd src; make aptik-console + +install: + cd src; make install + +uninstall: + cd src; make uninstall diff --git a/release/sanity.config b/release/sanity.config new file mode 100644 index 0000000..745ede4 --- /dev/null +++ b/release/sanity.config @@ -0,0 +1,7 @@ +app_name: Aptik NG +depends_debian: libgee-0.8-2 libjson-glib-1.0-0 apt aptitude gdebi apt-transport-https pv +depends_redhat: libgee json-glib pv +depends_arch: libgee json-glib pv +depends_generic: libgee json-glib pv +assume_yes: 0 +exec_line: pkexec aptik diff --git a/src/.ee.swp b/src/.ee.swp new file mode 100644 index 0000000000000000000000000000000000000000..1c4daa65b14973a8c422ff4dba93474f06f94e69 GIT binary patch literal 1024 zcmYc?$V<%2S1{5u)iY*50({{N3?-?lS*fW=f;gBEb-D$~IOJi%#FzzBJ4%m+z-S22 GJ_G>qc?xI% literal 0 HcmV?d00001 diff --git a/src/.uu.swp b/src/.uu.swp new file mode 100644 index 0000000000000000000000000000000000000000..37121580a15bc58b0867a0949256311abe0c613e GIT binary patch literal 1024 zcmYc?$V<%2S1{5u)iY*50v@3Z3?-?lS*fW=f;gBEb-D$~IOJi%rKK>|C_NeiqaiRD GLI40h$qK*# literal 0 HcmV?d00001 diff --git a/src/Gtk/AptikGtk.vala b/src/Gtk/AptikGtk.vala new file mode 100644 index 0000000..7613058 --- /dev/null +++ b/src/Gtk/AptikGtk.vala @@ -0,0 +1,154 @@ +/* + * AptikGtk.vala + * + * Copyright 2012-2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +using GLib; +using Gtk; +using Gee; +using Json; + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.JsonHelper; +using TeeJee.ProcessHelper; +using TeeJee.System; +using TeeJee.Misc; +using TeeJee.GtkHelper; + +public const string AppName = "Aptik NG"; +public const string AppShortName = "aptik-gtk"; +public const string AppVersion = "17.10"; +public const string AppAuthor = "Tony George"; +public const string AppAuthorEmail = "teejeetech@gmail.com"; + +const string GETTEXT_PACKAGE = ""; +const string LOCALE_DIR = "/usr/share/locale"; + +extern void exit(int exit_code); + +public AptikGtk App; + +public class AptikGtk : GLib.Object { + + public string basepath = ""; + + public static int main (string[] args) { + + set_locale(); + + Gtk.init(ref args); + + init_tmp(AppShortName); + + IconManager.init(args, AppShortName); + + App = new AptikGtk(); + App.load_settings(); + App.parse_arguments(args); + + var window = new MainWindow(); + window.destroy.connect(Gtk.main_quit); + window.show_all(); + + //start event loop + Gtk.main(); + + App.save_settings(); + + //App.exit_app(); + + return 0; + } + + private static void set_locale() { + + Intl.setlocale(GLib.LocaleCategory.MESSAGES, "aptik"); + Intl.textdomain(GETTEXT_PACKAGE); + Intl.bind_textdomain_codeset(GETTEXT_PACKAGE, "utf-8"); + Intl.bindtextdomain(GETTEXT_PACKAGE, LOCALE_DIR); + } + + public bool parse_arguments(string[] args) { + + // parse options + for (int k = 1; k < args.length; k++) // Oth arg is app path + { + switch (args[k].down()) { + case "--debug": + LOG_DEBUG = true; + break; + + case "--help": + case "--h": + case "-h": + log_msg(help_message()); + exit(0); + return true; + + default: + // unknown option; show help and exit + log_error("%s: %s".printf(_("Unknown option"), args[k])); + log_msg(help_message()); + exit(1); + return false; + } + } + + return true; + } + + public static string help_message() { + + string msg = "\n" + AppName + " v" + AppVersion + " by %s (%s)".printf(AppAuthor, AppAuthorEmail) + "\n"; + msg += "\n"; + msg += _("Syntax") + ": aptik-gtk [options]\n"; + msg += "\n"; + msg += _("Options") + ":\n"; + msg += "\n"; + msg += " --debug " + _("Print debug information") + "\n"; + msg += " --h[elp] " + _("Show all options") + "\n"; + msg += "\n"; + return msg; + } + + // settings --------------------------------- + + public void save_settings(){ + + var app_config_path = path_combine(get_user_home(), ".config/aptik-ng"); + + var param = path_combine(app_config_path, "basepath"); + file_write(param, basepath); + } + + public void load_settings(){ + + var app_config_path = path_combine(get_user_home(), ".config/aptik-ng"); + + var param = path_combine(app_config_path, "basepath"); + if (file_exists(param)){ + basepath = file_read(param); + } + } + +} + diff --git a/src/Gtk/MainWindow.vala b/src/Gtk/MainWindow.vala new file mode 100644 index 0000000..88b7c46 --- /dev/null +++ b/src/Gtk/MainWindow.vala @@ -0,0 +1,793 @@ +/* + * MainWindow.vala + * + * Copyright 2012-2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +using Gtk; +using Gee; + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.JsonHelper; +using TeeJee.ProcessHelper; +using TeeJee.System; +using TeeJee.Misc; +using TeeJee.GtkHelper; +using TeeJee.GtkHelper; + +public class MainWindow : Window { + + private Box vbox_main; + + private Grid grid; + + private TerminalWindow termwin; + + private Toolbar toolbar_bottom; + private ToolButton btn_donate; + private ToolButton btn_about; + + private Gtk.Entry txt_basepath; + private Gtk.Entry txt_password; + + private Button btn_restore_packages; + private Button btn_backup_packages; + + private Button btn_restore_repos; + private Button btn_backup_repos; + + private Button btn_restore_cache; + private Button btn_backup_cache; + + private Button btn_restore_config; + private Button btn_backup_config; + + private Button btn_restore_theme; + private Button btn_backup_theme; + + private Button btn_restore_mount; + private Button btn_backup_mount; + + private Button btn_restore_home; + private Button btn_backup_home; + + private Button btn_restore_crontab; + private Button btn_backup_crontab; + + private Button btn_restore_user; + private Button btn_backup_user; + + private ProgressBar progressbar; + private Label lbl_status; + + //private TerminalWindow term; + + int def_width = 450; + int def_height = -1; + + int icon_size_list = 22; + int button_width = 85; + int button_height = 15; + + string app_config_path = ""; + + public MainWindow () { + + title = AppName + " v" + AppVersion; + window_position = WindowPosition.CENTER; + resizable = false; + destroy.connect (Gtk.main_quit); + //set_default_size (def_width, def_height); + icon = get_app_icon(16); + + //vboxMain + vbox_main = new Box (Orientation.VERTICAL, 6); + vbox_main.margin = 6; + vbox_main.set_size_request (def_width, def_height); + add (vbox_main); + + //actions --------------------------------------------- + + init_section_location(); + + //init_section_password(); + + init_section_backup(); + + txt_basepath.text = App.basepath; + + termwin = new TerminalWindow.with_parent(this, false, true); + termwin.start_shell(); + + //init_section_toolbar_bottom(); + + //init_section_status(); + } + + private void init_section_location() { + + // header + var label = new Label ("" + _("Backup Location") + ""); + label.set_use_markup(true); + label.halign = Align.START; + //label.margin_top = 12; + label.margin_bottom = 6; + vbox_main.pack_start (label, false, true, 0); + + var hbox = new Box (Gtk.Orientation.HORIZONTAL, 6); + hbox.margin_bottom = 6; + vbox_main.pack_start (hbox, false, true, 0); + + // entry + var entry = new Gtk.Entry(); + entry.hexpand = true; + //entry.secondary_icon_stock = "gtk-open"; + entry.placeholder_text = _("Select backup directory"); + entry.margin_left = 6; + hbox.pack_start (entry, true, true, 0); + txt_basepath = entry; + + /*if ((App.backup_dir != null) && dir_exists (App.backup_dir)) { + var path = App.backup_dir; + path = path.has_suffix("/") ? path[0:path.length-1] : path; + txt_basepath.text = path; + }*/ + + entry.changed.connect(() => { + App.basepath = txt_basepath.text; + }); + + entry.icon_release.connect((p0, p1) => { + backup_location_browse(); + }); + + // btn_browse_backup_dir + var button = new Gtk.Button.with_label (" " + _("Select") + " "); + button.set_size_request(button_width, button_height); + button.set_tooltip_text(_("Select backup location")); + hbox.pack_start (button, false, true, 0); + + button.clicked.connect(backup_location_browse); + + // btn_open_backup_dir + button = new Gtk.Button.with_label (" " + _("Open") + " "); + button.set_size_request(button_width, button_height); + button.set_tooltip_text(_("Open backup location")); + hbox.pack_start (button, false, true, 0); + + button.clicked.connect(() => { + if (check_backup_folder()) { + //exo_open_folder(App.backup_dir, false); + } + }); + + button.grab_focus(); + } + + private void backup_location_browse(){ + + //chooser + var chooser = new Gtk.FileChooserDialog( + "Select Path", + this, + FileChooserAction.SELECT_FOLDER, + "_Cancel", + Gtk.ResponseType.CANCEL, + "_Open", + Gtk.ResponseType.ACCEPT + ); + + chooser.select_multiple = false; + chooser.set_filename(App.basepath); + + if (chooser.run() == Gtk.ResponseType.ACCEPT) { + txt_basepath.text = chooser.get_filename(); + } + + chooser.destroy(); + } + + private void init_section_backup() { + + // lbl_header_backup + var label = new Label ("" + _("Backup & Restore") + ""); + label.set_use_markup(true); + label.halign = Align.START; + label.margin_bottom = 6; + vbox_main.pack_start (label, false, true, 0); + + //grid + grid = new Grid(); + grid.set_column_spacing(6); + grid.set_row_spacing(6); + grid.margin_left = 6; + grid.margin_bottom = 6; + grid.margin_right = 6; + vbox_main.pack_start (grid, false, true, 0); + + int row = -1; + + init_section_repos(++row); + + init_section_cache(++row); + + init_section_packages(++row); + + init_section_users(++row); + + init_section_groups(++row); + + init_section_home(++row); + + init_section_mounts(++row); + + init_section_icons(++row); + + init_section_themes(++row); + + init_section_fonts(++row); + + init_section_dconf(++row); + + init_section_cron(++row); + + var sep = new Gtk.Separator(Gtk.Orientation.HORIZONTAL); + sep.margin = 6; + grid.attach(sep, 0, ++row, 4, 1); + + init_section_all(++row); + } + + // helpers ----------------------------- + + private void add_section_icon(int row, string icon_name) { + + var img = IconManager.lookup_image(icon_name, icon_size_list); + grid.attach(img, 0, row, 1, 1); + } + + private void add_section_label(int row, string text) { + + var label = new Gtk.Label(text); + //label.set_tooltip_text(tooltip); + label.set_use_markup(true); + label.halign = Align.START; + label.hexpand = true; + grid.attach(label, 1, row, 1, 1); + } + + private Gtk.Button add_section_button_view(int row) { + + var button = new Gtk.Button.with_label (_("View")); + button.set_size_request(button_width, button_height); + grid.attach(button, 2, row, 1, 1); + return button; + } + + private Gtk.Button add_section_button_backup(int row) { + + var button = new Gtk.Button.with_label (_("Backup")); + button.set_size_request(button_width, button_height); + grid.attach(button, 3, row, 1, 1); + return button; + } + + private Gtk.Button add_section_button_restore(int row) { + + var button = new Gtk.Button.with_label (_("Restore")); + button.set_size_request(button_width, button_height); + grid.attach(button, 4, row, 1, 1); + return button; + } + + private void execute(string cmd){ + + termwin.reset(); + termwin.show_all(); + termwin.execute_command(cmd); + } + + // sections --------------------------------------- + + private void init_section_repos(int row) { + + add_section_icon(row, "x-system-software-sources"); + + add_section_label(row, Messages.TASK_REPOS); + + var bbox = new Gtk.ButtonBox(Orientation.HORIZONTAL); + bbox.set_layout(Gtk.ButtonBoxStyle.CENTER); + bbox.margin = 3; + vbox_main.add(bbox); + + var button = add_section_button_view(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --list-repos --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_backup(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --backup-repos --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_restore(row); + btn_restore_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --restore-repos --basepath '%s'".printf(App.basepath)); + }); + } + + private void init_section_cache(int row) { + + add_section_icon(row, "download"); + + add_section_label(row, Messages.TASK_CACHE); + + var button = add_section_button_backup(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --backup-cache --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_restore(row); + btn_restore_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --restore-cache --basepath '%s'".printf(App.basepath)); + }); + } + + private void init_section_packages(int row) { + + add_section_icon(row, "package-x-generic"); + + add_section_label(row, Messages.TASK_PACKAGES); + + var button = add_section_button_backup(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --backup-packages --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_restore(row); + btn_restore_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --restore-packages --basepath '%s'".printf(App.basepath)); + }); + } + + private void init_section_users(int row) { + + add_section_icon(row, "config-users"); + + add_section_label(row, Messages.TASK_USERS); + + var button = add_section_button_backup(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --backup-users --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_restore(row); + btn_restore_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --restore-users --basepath '%s'".printf(App.basepath)); + }); + } + + private void init_section_groups(int row) { + + add_section_icon(row, "config-users"); + + add_section_label(row, Messages.TASK_GROUPS); + + var button = add_section_button_backup(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --backup-groups --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_restore(row); + btn_restore_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --restore-groups --basepath '%s'".printf(App.basepath)); + }); + } + + private void init_section_home(int row) { + + add_section_icon(row, "user-home"); + + add_section_label(row, Messages.TASK_HOME); + + var button = add_section_button_backup(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --backup-home --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_restore(row); + btn_restore_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --restore-home --basepath '%s'".printf(App.basepath)); + }); + } + + private void init_section_mounts(int row) { + + add_section_icon(row, "drive-harddisk"); + + add_section_label(row, Messages.TASK_MOUNTS); + + var button = add_section_button_backup(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --backup-mounts --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_restore(row); + btn_restore_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --restore-mounts --basepath '%s'".printf(App.basepath)); + }); + } + + private void init_section_icons(int row) { + + add_section_icon(row, "preferences-theme"); + + add_section_label(row, Messages.TASK_ICONS); + + var button = add_section_button_backup(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --backup-icons --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_restore(row); + btn_restore_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --restore-icons --basepath '%s'".printf(App.basepath)); + }); + } + + private void init_section_themes(int row) { + + add_section_icon(row, "preferences-theme"); + + add_section_label(row, Messages.TASK_THEMES); + + var button = add_section_button_backup(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --backup-themes --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_restore(row); + btn_restore_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --restore-themes --basepath '%s'".printf(App.basepath)); + }); + } + + private void init_section_fonts(int row) { + + add_section_icon(row, "preferences-theme"); + + add_section_label(row, Messages.TASK_FONTS); + + var button = add_section_button_backup(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --backup-fonts --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_restore(row); + btn_restore_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --restore-fonts --basepath '%s'".printf(App.basepath)); + }); + } + + private void init_section_dconf(int row) { + + add_section_icon(row, "preferences-system"); + + add_section_label(row, Messages.TASK_DCONF); + + var button = add_section_button_backup(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --backup-dconf --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_restore(row); + btn_restore_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + var win = new TerminalWindow.with_parent(this, false, true); + win.start_shell(); + win.execute_command("pkexec aptik --restore-dconf --basepath '%s'".printf(App.basepath)); + }); + } + + private void init_section_cron(int row) { + + add_section_icon(row, "clock"); + + add_section_label(row, Messages.TASK_CRON); + + var button = add_section_button_backup(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --backup-cron --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_restore(row); + btn_restore_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + var win = new TerminalWindow.with_parent(this, false, true); + win.start_shell(); + win.execute_command("pkexec aptik --restore-cron --basepath '%s'".printf(App.basepath)); + }); + } + + private void init_section_all(int row) { + + add_section_icon(row, "edit-select-all"); + + add_section_label(row, Messages.TASK_ALL); + + var button = add_section_button_backup(row); + btn_backup_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --backup-all --basepath '%s'".printf(App.basepath)); + }); + + button = add_section_button_restore(row); + btn_restore_repos = button; + + button.clicked.connect(()=>{ + + if (!check_backup_folder()) { return; } + + execute("pkexec aptik --restore-all --basepath '%s'".printf(App.basepath)); + }); + } + + private void btn_about_clicked () { + var dialog = new AboutWindow(); + dialog.set_transient_for (this); + + dialog.authors = { + "Tony George:teejeetech@gmail.com" + }; + + dialog.contributors = { + "Shem Pasamba (Proxy support for package downloads):shemgp@gmail.com" + }; + + dialog.third_party = { + "Numix project (Main app icon):https://numixproject.org/", + "Elementary project (various icons):https://github.com/elementary/icons", + "Tango project (various icons):http://tango.freedesktop.org/Tango_Desktop_Project" + }; + + dialog.translators = { + "B. W. Knight (Korean):https://launchpad.net/~kbd0651", + "giulux (Italian):https://launchpad.net/~giulbuntu", + "Jorge Jamhour (Brazilian Portuguese):https://launchpad.net/~jorge-jamhour", + "Radek Otáhal (Czech):radek.otahal@email.cz", + "Rodion R. (Russian):https://launchpad.net/~r0di0n", + "Åke Engelbrektson:https://launchpad.net/~eson" + }; + + dialog.documenters = null; + dialog.artists = null; + dialog.donations = null; + + dialog.program_name = AppName; + dialog.comments = _("Migration utility for Ubuntu-based distributions"); + dialog.copyright = "Copyright © 2012-2017 %s (%s)".printf(AppAuthor, AppAuthorEmail); + dialog.version = AppVersion; + dialog.logo = get_app_icon(128); + + dialog.license = "This program is free for personal and commercial use and comes with absolutely no warranty. You use this program entirely at your own risk. The author will not be liable for any damages arising from the use of this program."; + dialog.website = "http://teejeetech.in"; + dialog.website_label = "http://teejeetech.blogspot.in"; + + dialog.initialize(); + dialog.show_all(); + } + + private bool check_backup_folder() { + if (dir_exists (txt_basepath.text)) { + return true; + } + else { + string title = _("Backup Directory Not Selected"); + string msg = _("Select the backup directory"); + gtk_messagebox(title, msg, this, false); + return false; + } + } + + private bool check_password() { + + //App.arg_password = txt_password.text; + + //if (App.arg_password.length > 0){ + return true; + //} + //else { + /*string title = _("Password Field is Empty"); + string msg = _("Enter the passphrase for encryption"); + gtk_messagebox(title, msg, this, false); + return false;*/ + //} + } + + private bool check_backup_file(string file_name) { + /*if (check_backup_folder()) { + string backup_file = App.backup_dir + file_name; + var f = File.new_for_path(backup_file); + if (!f.query_exists()) { + string title = _("File Not Found"); + string msg = _("File not found in backup directory") + " - %s".printf(file_name); + gtk_messagebox(title, msg, this, true); + return false; + } + else { + return true; + } + } + else { + return false; + }*/ + return false; + } + + private bool check_backup_subfolder(string folder_name) { + /*if (check_backup_folder()) { + string folder = App.backup_dir + folder_name; + var f = File.new_for_path(folder); + if (!f.query_exists()) { + string title = _("Folder Not Found"); + string msg = _("Folder not found in backup directory") + " - %s".printf(folder_name); + gtk_messagebox(title, msg, this, true); + return false; + } + else { + return true; + } + } + else {*/ + return false; + //} + } + +} + + diff --git a/src/Gtk/RepoWindow.vala b/src/Gtk/RepoWindow.vala new file mode 100644 index 0000000..8eea58b --- /dev/null +++ b/src/Gtk/RepoWindow.vala @@ -0,0 +1,378 @@ +/* + * RepoWindow.vala + * + * Copyright 2012-2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + + +using Gtk; +using Gee; + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.JsonHelper; +using TeeJee.ProcessHelper; +using TeeJee.System; +using TeeJee.Misc; +using TeeJee.GtkHelper; + +public class Item : GLib.Object{ + + public string name = ""; + public string desc = ""; + public bool selected = false; + public bool installed = false; +} + +public class RepoWindow : Window { + + private Gee.ArrayList items; + + private Gtk.Box vbox_main; + + private Button btn_restore; + private Button btn_backup; + private Button btn_cancel; + private Button btn_select_all; + private Button btn_select_none; + + private TreeView treeview; + //private TreeViewColumn col_status; + private ScrolledWindow scrolled; + + private int def_width = 700; + private int def_height = 450; + private uint tmr_init = 0; + + private bool is_running = false; + private bool is_restore_view = false; + + private bool is_backup_view{ + get{ + return !is_restore_view; + } + } + + // init ------------------------- + + public RepoWindow.with_parent(Window parent, bool restore) { + + set_transient_for(parent); + set_modal(true); + is_restore_view = restore; + + destroy.connect(()=>{ + parent.present(); + }); + + init_window(); + } + + public void init_window () { + + window_position = WindowPosition.CENTER; + set_default_size (def_width, def_height); + icon = get_app_icon(16); + resizable = true; + deletable = true; + + //vbox_main + vbox_main = new Gtk.Box (Orientation.VERTICAL, 6); + vbox_main.margin = 6; + add (vbox_main); + + //treeview + init_treeview(); + + //buttons + init_actions(); + + show_all(); + + tmr_init = Timeout.add(100, init_delayed); + } + + private bool init_delayed() { + + /* any actions that need to run after window has been displayed */ + + if (tmr_init > 0) { + Source.remove(tmr_init); + tmr_init = 0; + } + + if (is_restore_view){ + title = _("Restore"); + + btn_restore.show(); + btn_restore.visible = true; + + restore_init(); + } + else{ + title = _("Backup"); + + btn_backup.show(); + btn_backup.visible = true; + + backup_init(); + } + + return false; + } + + private void init_treeview() { + + // treeview + treeview = new Gtk.TreeView(); + treeview.get_selection().mode = SelectionMode.MULTIPLE; + treeview.headers_clickable = true; + treeview.set_rules_hint (true); + treeview.set_tooltip_column(3); + + // scrolled + scrolled = new Gtk.ScrolledWindow(null, null); + scrolled.set_shadow_type (ShadowType.ETCHED_IN); + scrolled.add (treeview); + scrolled.expand = true; + vbox_main.add(scrolled); + + // col_select ---------------------- + + var col_select = new Gtk.TreeViewColumn(); + col_select.title = ""; + treeview.append_column(col_select); + + var cell_select = new Gtk.CellRendererToggle(); + cell_select.activatable = true; + col_select.pack_start (cell_select, false); + + col_select.set_cell_data_func (cell_select, (cell_layout, cell, model, iter) => { + bool selected; + Item item; + model.get (iter, 0, out selected, 1, out item, -1); + (cell as Gtk.CellRendererToggle).active = selected; + (cell as Gtk.CellRendererToggle).sensitive = !is_restore_view || !item.installed; + }); + + cell_select.toggled.connect((path) => { + var model = (Gtk.ListStore)treeview.model; + bool selected; + Item item; + TreeIter iter; + + model.get_iter_from_string (out iter, path); + model.get (iter, 0, out selected); + model.get (iter, 1, out item); + model.set (iter, 0, !selected); + item.selected = !selected; + }); + + // col_status ---------------------- + + var col_status = new Gtk.TreeViewColumn(); + col_status.resizable = true; + treeview.append_column(col_status); + + var cell_status = new Gtk.CellRendererPixbuf (); + col_status.pack_start (cell_status, false); + col_status.set_attributes(cell_status, "pixbuf", 2); + + // col_name ---------------------- + + var col_name = new Gtk.TreeViewColumn(); + col_name.title = _("Name"); + col_name.resizable = true; + col_name.min_width = 180; + treeview.append_column(col_name); + + var cell_name = new Gtk.CellRendererText (); + cell_name.ellipsize = Pango.EllipsizeMode.END; + col_name.pack_start (cell_name, false); + + col_name.set_cell_data_func (cell_name, (cell_layout, cell, model, iter) => { + Item item; + model.get (iter, 1, out item, -1); + (cell as Gtk.CellRendererText).text = item.name; + }); + + // col_desc ---------------------- + + var col_desc = new Gtk.TreeViewColumn(); + if (is_restore_view){ + col_desc.title = _("Desc"); + } + else{ + col_desc.title = _("Desc"); + } + col_desc.resizable = true; + treeview.append_column(col_desc); + + var cell_desc = new Gtk.CellRendererText (); + cell_desc.ellipsize = Pango.EllipsizeMode.END; + col_desc.pack_start (cell_desc, false); + + col_desc.set_cell_data_func (cell_desc, (cell_layout, cell, model, iter) => { + Item item; + model.get (iter, 1, out item, -1); + (cell as Gtk.CellRendererText).text = item.desc; + }); + } + + private void init_actions() { + + var hbox = new Box (Orientation.HORIZONTAL, 6); + vbox_main.add (hbox); + + // btn_select_all + var button = new Gtk.Button.with_label (_("Select All")); + hbox.pack_start (button, true, true, 0); + btn_select_all = button; + + button.clicked.connect(() => { + + foreach(var item in items) { + + if (is_restore_view) { + + if (!item.installed) { + item.selected = true; + } + else { + //no change + } + } + else { + item.selected = true; + } + } + + treeview_refresh(); + }); + + // btn_select_none + button = new Gtk.Button.with_label (" " + _("Select None") + " "); + hbox.pack_start (button, true, true, 0); + btn_select_none = button; + + btn_select_none.clicked.connect(() => { + + foreach(var item in items) { + + if (is_restore_view) { + + if (!item.installed) { + item.selected = false; + } + else { + //no change + } + } + else { + item.selected = false; + } + } + + treeview_refresh(); + }); + + // btn_backup + button = new Gtk.Button.with_label (" " + _("Backup") + " "); + button.no_show_all = true; + hbox.pack_start(button, true, true, 0); + btn_backup = button; + + button.clicked.connect(btn_backup_clicked); + + // btn_restore + button = new Gtk.Button.with_label (" " + _("Restore") + " "); + button.no_show_all = true; + hbox.pack_start(button, true, true, 0); + btn_restore = button; + + button.clicked.connect(btn_restore_clicked); + + // btn_cancel + button = new Gtk.Button.with_label (" " + _("Close") + " "); + hbox.pack_start(button, true, true, 0); + btn_cancel = button; + + button.clicked.connect(() => { + this.close(); + }); + + set_bold_font_for_buttons(); + } + + private void set_bold_font_for_buttons() { + //set bold font for some buttons + foreach(Button btn in new Button[] { btn_backup, btn_restore }) { + foreach(Widget widget in btn.get_children()) { + if (widget is Label) { + Label lbl = (Label)widget; + lbl.set_markup(lbl.label); + } + } + } + } + + // events + + private void treeview_refresh() { + + var model = new Gtk.ListStore(4, typeof(bool), typeof(Item), typeof(Gdk.Pixbuf), typeof(string)); + + Gdk.Pixbuf pix_enabled = IconManager.lookup("item-green.png", 16); + Gdk.Pixbuf pix_missing = IconManager.lookup("item-gray.png", 16); + + TreeIter iter; + + foreach(var item in items) { + + //add row + model.append(out iter); + model.set (iter, 0, item.selected); + model.set (iter, 1, item); + model.set (iter, 2, item.installed ? pix_enabled : pix_missing); + model.set (iter, 3, ""); + } + + treeview.set_model(model); + treeview.columns_autosize(); + } + + private void backup_init(){ + + } + + private void restore_init(){ + + } + + private void btn_backup_clicked(){ + + } + + private void btn_restore_clicked(){ + + } +} + + diff --git a/src/Gtk/TermBox.vala b/src/Gtk/TermBox.vala new file mode 100644 index 0000000..6b1179e --- /dev/null +++ b/src/Gtk/TermBox.vala @@ -0,0 +1,301 @@ +/* + * TermBox.vala + * + * Copyright 2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + + +using Gtk; +using Gee; + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.JsonHelper; +using TeeJee.ProcessHelper; +using TeeJee.GtkHelper; +using TeeJee.System; +using TeeJee.Misc; + +public class TermBox : Gtk.Box { + + private Vte.Terminal term; + private Pid child_pid; + private bool cancelled = false; + private bool is_running = false; + private Gtk.Window window; + + public const int DEF_FONT_SIZE = 11; + public const string DEF_COLOR_FG = "#DCDCDC"; + public const string DEF_COLOR_BG = "#2C2C2C"; + + public signal void child_exited(); + + public TermBox(Gtk.Window _window){ + //base(Gtk.Orientation.VERTICAL, 6); // issue with vala + Object(orientation: Gtk.Orientation.VERTICAL, spacing: 0); // work-around + + window = _window; + + init_ui(); + } + + private void init_ui(){ + + log_debug("TermBox: init_ui()"); + + //scrolled + var scrolled = new Gtk.ScrolledWindow(null, null); + scrolled.set_shadow_type (ShadowType.ETCHED_IN); + scrolled.expand = true; + this.add(scrolled); + + //terminal + term = new Vte.Terminal(); + term.expand = true; + scrolled.add(term); + + term.input_enabled = true; + term.backspace_binding = Vte.EraseBinding.AUTO; + term.cursor_blink_mode = Vte.CursorBlinkMode.SYSTEM; + term.cursor_shape = Vte.CursorShape.UNDERLINE; + term.rewrap_on_resize = true; + term.allow_bold = false; + + term.scroll_on_keystroke = true; + term.scroll_on_output = true; + term.scrollback_lines = 100000; + + var fontdesc = Pango.FontDescription.from_string("liberation mono,droid sans mono,ubuntu mono,monospace regular 11"); + + set_font_desc(fontdesc); + + set_color_foreground("#EEEEEC"); + + set_color_background("#2E3436"); + } + + public void start_shell(){ + + log_debug("TermBox: start_shell()"); + + string[] argv = new string[1]; + argv[0] = get_cmd_path("bash"); + + if (!cmd_exists("bash")){ + argv[0] = get_cmd_path("sh"); + } + + string[] env = Environ.get(); + + try{ + + is_running = true; + + term.spawn_sync( + Vte.PtyFlags.DEFAULT, //pty_flags + "/root", //working_directory + argv, //argv + env, //env + GLib.SpawnFlags.SEARCH_PATH, //spawn_flags + null, //child_setup + out child_pid, + null + ); + + init_bash(); + + term.child_exited.connect((status)=>{ + log_debug("TermBox: child_exited(): pid=%d, status=%d".printf(child_pid, status)); + child_exited(); + //if (!cancelled){ + // start_shell(); + //} + }); + + reset(); + + log_debug("TermBox: start_shell(): started"); + } + catch (Error e) { + log_error (e.message); + } + } + + public void init_bash(){ + + string cmd = +""" +if [ "`id -u`" -eq 0 ]; then + PS1='\[\e[31m\]\# \[\e[m\]' +else + PS1='\[\033[01;93m\]\$ \[\033[00m\]' +fi +"""; + + feed_command(cmd); + } + + public void exit_shell(){ + cancelled = true; + feed_command("exit"); + } + + public void restart_shell(){ + exit_shell(); + start_shell(); + } + + public void terminate_child(){ + cancelled = true; + process_quit(child_pid); + } + + public bool has_running_process { + get{ + var children = get_process_children(child_pid); + return (children.length > 0); + } + } + + public int get_child_pid() { + return child_pid; + } + + public void feed_command(string command, bool newline = true){ + + string cmd = command; + + if (newline){ + cmd = "%s\n".printf(cmd); + } + + term.feed_child(cmd, -1); + } + + public void refresh(){ + + log_debug("TermBox: refresh()"); + + if (this.visible && !is_running){ + start_shell(); + } + } + + public void change_directory(string dir_path){ + + log_debug("TermBox: change_directory()"); + + feed_command("cd '%s'".printf(escape_single_quote(dir_path))); + } + + private void show_running_process_message(){ + // TODO: Add check to ignore background process + gtk_messagebox(_("Terminal is busy"),_("This action cannot be executed while a process is running"), window, true); + } + + public void copy(){ + + log_debug("TermBox: copy()"); + + term.copy_primary(); + + Gdk.Display display = this.get_display (); + var clipboard = Gtk.Clipboard.get_for_display (display, Gdk.SELECTION_PRIMARY); + string txt = clipboard.wait_for_text(); + if (txt != null){ + clipboard = Gtk.Clipboard.get_for_display (display, Gdk.SELECTION_CLIPBOARD); + clipboard.set_text(txt, -1); + } + } + + public void paste(){ + + log_debug("TermBox: paste()"); + + Gdk.Display display = this.get_display (); + Gtk.Clipboard clipboard = Gtk.Clipboard.get_for_display (display, Gdk.SELECTION_CLIPBOARD); + string txt = clipboard.wait_for_text(); + if (txt != null){ + feed_command(txt, false); + } + } + + public void reset(){ + + log_debug("TermBox: reset()"); + + feed_command("tput reset"); + } + + public void open_settings(){ + + log_debug("TermBox: open_settings()"); + + feed_command("fish_config"); + } + + public void set_font_size(int size_pts){ + term.font_desc = Pango.FontDescription.from_string("normal %d".printf(size_pts)); + } + + public void set_font_desc(Pango.FontDescription font_desc){ + term.set_font(font_desc); + } + + public void set_color_foreground(string color){ + + log_debug("TermBox: set_color_foreground(): %s".printf(color)); + + var rgba = Gdk.RGBA(); + rgba.parse(color); + term.set_color_foreground(rgba); + } + + public void set_color_background(string color){ + + log_debug("TermBox: set_color_background(): %s".printf(color)); + + var rgba = Gdk.RGBA(); + rgba.parse(color); + term.set_color_background(rgba); + } + + public void set_defaults(){ + set_font_size(DEF_FONT_SIZE); + set_color_foreground(DEF_COLOR_FG); + set_color_background(DEF_COLOR_BG); + } + + public void chroot_current(){ + + feed_command("sudo polo-chroot $(pwd)"); + } + + public void chroot(string path){ + + var cmd = "sudo polo-chroot '%s' \n".printf( + //App.term_enable_network ? "--enable-network" : "", + //App.term_enable_gui ? "--enable-gui" : "", + escape_single_quote(path)); + + feed_command(cmd); + } +} + diff --git a/src/Gtk/TerminalWindow.vala b/src/Gtk/TerminalWindow.vala new file mode 100644 index 0000000..4ed074f --- /dev/null +++ b/src/Gtk/TerminalWindow.vala @@ -0,0 +1,136 @@ +/* + * TerminalWindow.vala + * + * Copyright 2012-2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + + +using Gtk; +using Gee; + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.JsonHelper; +using TeeJee.ProcessHelper; +using TeeJee.System; +using TeeJee.Misc; +using TeeJee.GtkHelper; + +public class TerminalWindow : Gtk.Window { + + private Gtk.Box vbox_main; + private TermBox term; + private Gtk.Button btn_cancel; + + private int def_width = 900; + private int def_height = 500; + + private Gtk.Window parent_win = null; + + // init + + public TerminalWindow.with_parent(Gtk.Window? parent, bool fullscreen = false, bool show_cancel_button = false) { + + if (parent != null){ + set_transient_for(parent); + parent_win = parent; + } + + set_modal(false); + window_position = WindowPosition.CENTER; + + if (fullscreen){ + this.fullscreen(); + } + + this.delete_event.connect(on_delete_event); + + init_window(); + } + + public bool on_delete_event(){ + + if (term.has_running_process){ + term.terminate_child(); + return true; // stay open + } + + this.hide(); + return true; // stay open + } + + public void init_window () { + + title = ""; + icon = get_app_icon(16); + resizable = true; + deletable = true; + + // vbox_main ------------------------------ + + vbox_main = new Gtk.Box(Orientation.VERTICAL, 0); + vbox_main.margin = 0; + vbox_main.set_size_request(def_width, def_height); + this.add(vbox_main); + + // terminal ------------------------------ + + term = new TermBox(this); + term.expand = true; + vbox_main.add(term); + + // actions ------------------------------ + + var bbox = new Gtk.ButtonBox(Orientation.HORIZONTAL); + bbox.set_layout(Gtk.ButtonBoxStyle.CENTER); + bbox.margin = 3; + vbox_main.add(bbox); + + //btn_cancel + var button = new Gtk.Button.with_label (_("Close")); + bbox.add(button); + btn_cancel = button; + + btn_cancel.clicked.connect(()=>{ + on_delete_event(); + }); + + term.child_exited.connect(()=>{ + button.label = _("Close"); + }); + } + + public void start_shell(){ + + term.start_shell(); + } + + public void execute_command(string cmd){ + + term.feed_command(cmd); + } + + public void reset(){ + + term.reset(); + } +} + + diff --git a/src/Messages.vala b/src/Messages.vala new file mode 100644 index 0000000..aba7c67 --- /dev/null +++ b/src/Messages.vala @@ -0,0 +1,77 @@ + +public class Messages : GLib.Object { + + public const string APT_GET_ERROR = _("Package installation has failed or was aborted by user"); + + public const string INTERNET_OFFLINE = _("Internet connection is not active. Check the connection and try again."); + + public const string BACKUP_OK = _("Backup completed"); + public const string BACKUP_ERROR = _("Backup completed with errors"); + public const string BACKUP_SAVED = _("Backup saved"); + public const string BACKUP_SAVE_ERROR = _("Failed to save backup"); + + public const string UNKNOWN_DISTRO = _("Unknown Linux Distribution & Package Manager"); + public const string UNKNOWN_CODENAME = _("CODENAME is unknown for this Linux distribution"); + + public const string MISSING_PACKAGE_MANAGER = _("Package Manager Not Found"); + + public const string MISSING_COMMAND = _("Missing command"); + + public const string CACHE_NOT_SUPPORTED = _("Cache backup & restore not supported for package manager"); + + public const string RESTORE_OK = _("Restore completed"); + public const string RESTORE_ERROR = _("Restore completed with errors"); + + public const string FILE_EXISTS = _("File exists"); + public const string FILE_MISSING = _("File not found"); + + public const string FILE_SAVE_OK = _("File saved"); + public const string FILE_SAVE_ERROR = _("Failed to save file"); + + public const string FILE_READ_OK = _("File read"); + public const string FILE_READ_ERROR = _("Failed to read file"); + + public const string FILE_DECRYPT_OK = _("File decrypted"); + public const string FILE_DECRYPT_ERROR = _("Failed to decrypt file"); + + public const string FILE_DELETE_OK = _("File deleted"); + public const string FILE_DELETE_ERROR = _("Failed to delete file"); + + public const string DIR_CREATE_OK = _("Directory created"); + public const string DIR_CREATE_ERROR = _("Failed to create directory"); + + public const string DIR_EXISTS = _("Directory exists"); + public const string DIR_MISSING = _("Directory missing"); + + public const string USER_ADD_OK = _("User added"); + public const string USER_ADD_ERROR = _("Failed to add user"); + + public const string GROUP_ADD_OK = _("Group added"); + public const string GROUP_ADD_ERROR = _("Failed to add group"); + + public const string GROUP_ADD_USER_OK = _("User added to group"); + public const string GROUP_ADD_USER_ERROR = _("Failed to add user to group"); + + public const string NO_CHANGES_REQUIRED = _("No changes required"); + + public const string PASSWORD_MISSING = _("Password not specified!"); + public const string ENTER_PASSWORD_BACKUP = _("Enter password for encrypting backup"); + public const string ENTER_PASSWORD_RESTORE = _("Enter password for decrypting backup"); + public const string PASSWORD_EMPTY = _("Password cannot be empty!"); + public const string PASSWORD_NOT_MATCHING = _("Passwords do not match!"); + + public const string TASK_REPOS = _("Software Repositories"); + public const string TASK_CACHE = _("Downloaded Packages"); + public const string TASK_PACKAGES = _("Installed Software"); + public const string TASK_HOME = _("Home Directory Data"); + public const string TASK_MOUNTS = _("Mount Entries"); + public const string TASK_ICONS = _("Icons"); + public const string TASK_THEMES = _("Themes"); + public const string TASK_FONTS = _("Fonts"); + public const string TASK_USERS = _("User Accounts"); + public const string TASK_GROUPS = _("User Groups"); + public const string TASK_DCONF = _("Dconf Settings"); + public const string TASK_CRON = _("Scheduled Tasks"); + public const string TASK_ALL = _("All Items"); +} + diff --git a/src/README b/src/README new file mode 100644 index 0000000..db8fb4d --- /dev/null +++ b/src/README @@ -0,0 +1,7 @@ + +/Console/ -- Command-line version of this App; Does not contain GUI code (no references to Gtk, Gdk, etc) +/Gtk/ -- Gtk version of this App; Contains GUI code (references to Gtk, Gdk, etc); Calls the commandline version to get work done; + +/Utility/ -- Helper classes +/Utility/Console/ -- Helper classes; Does not contain GUI code (no references to Gtk, Gdk, etc) +/Utility/Gtk/ -- Helper classes; Contains GUI code (references to Gtk, Gdk, etc) diff --git a/src/Utility/Console/AppLock.vala b/src/Utility/Console/AppLock.vala new file mode 100644 index 0000000..85db02e --- /dev/null +++ b/src/Utility/Console/AppLock.vala @@ -0,0 +1,106 @@ + +/* + * AppLock.vala + * + * Copyright 2016 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.ProcessHelper; +using TeeJee.Misc; + +public class AppLock : GLib.Object { + public string lock_dir = ""; + public string lock_file = ""; + public string lock_message = ""; + + public AppLock(string app_name){ + lock_dir = "/var/run/lock/%s".printf(app_name); + lock_file = path_combine(lock_dir, "lock"); + } + + public bool create(string message){ + + dir_create(lock_dir); + + try{ + var file = File.new_for_path(lock_file); + if (file.query_exists()) { + + string txt = file_read(lock_file); + string process_id = txt.split(";")[0].strip(); + lock_message = txt.split(";")[1].strip(); + long pid = long.parse(process_id); + + if (process_is_running(pid)){ + log_msg(_("Another instance of this application is running") + + " (PID=%ld)".printf(pid)); + return false; + } + else{ + log_msg(_("[Warning] Deleted invalid lock")); + file.delete(); + write_lock_file(message); + return true; + } + } + else{ + write_lock_file(message); + return true; + } + } + catch (Error e) { + log_error (e.message); + return false; + } + } + + private void write_lock_file(string message){ + string current_pid = ((long) Posix.getpid()).to_string(); + file_write(lock_file, "%s;%s".printf(current_pid, message)); + } + + public void kill_existing_process(){ + var file = File.new_for_path(lock_file); + if (file.query_exists()) { + string txt = file_read(lock_file); + string process_id = txt.split(";")[0].strip(); + long pid = long.parse(process_id); + + if (process_is_running(pid)){ + process_kill((Pid)pid); + } + } + } + + public void remove(){ + try{ + var file = File.new_for_path (lock_file); + if (file.query_exists()) { + file.delete(); + } + } + catch (Error e) { + log_error (e.message); + } + } + +} diff --git a/src/Utility/Console/AsyncTask.vala b/src/Utility/Console/AsyncTask.vala new file mode 100644 index 0000000..a9434c1 --- /dev/null +++ b/src/Utility/Console/AsyncTask.vala @@ -0,0 +1,570 @@ +/* + * AsyncTask.vala + * + * Copyright 2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.ProcessHelper; +using TeeJee.System; +using TeeJee.Misc; + +public abstract class AsyncTask : GLib.Object{ + + private string err_line = ""; + private string out_line = ""; + private DataOutputStream dos_in; + private DataInputStream dis_out; + private DataInputStream dis_err; + protected DataOutputStream dos_log; + protected bool is_terminated = false; + + private bool stdout_is_open = false; + private bool stderr_is_open = false; + + protected Pid child_pid; + private int input_fd; + private int output_fd; + private int error_fd; + private bool finish_called = false; + + protected string script_file = ""; + protected string working_dir = ""; + protected string log_file = ""; + + public bool background_mode = false; + + // public + public AppStatus status; + public string status_line = ""; + public string stats_line = ""; + public string error_msg = ""; + public GLib.Timer timer; + public double progress = 0.0; + public double percent = 0.0; + public int64 prg_count = 0; + public int64 prg_count_total = 0; + public int64 prg_bytes = 0; + public int64 prg_bytes_total = 0; + public string eta = ""; + public string rate = ""; + public int64 count_completed = 0; + public int64 count_total = 0; + public int64 bytes_completed = 0; + public int64 bytes_total = 0; + //public bool is_running = false; + + // regex + protected Gee.HashMap regex_list; + + // signals + public signal void stdout_line_read(string line); + public signal void stderr_line_read(string line); + public signal void task_complete(); + + public AsyncTask(){ + init_temp_directories(); + } + + public void init_temp_directories(){ + working_dir = TEMP_DIR + "/" + timestamp_for_path(); + script_file = path_combine(working_dir, "script.sh"); + log_file = path_combine(working_dir, "task.log"); + dir_create(working_dir); + } + + public bool begin(){ + + status = AppStatus.RUNNING; + + bool has_started = true; + is_terminated = false; + finish_called = false; + + prg_count = 0; + prg_bytes = 0; + error_msg = ""; + + log_debug("AsyncTask: %s".printf(script_file)); + + string[] spawn_args = new string[1]; + spawn_args[0] = script_file; + + string[] spawn_env = Environ.get(); + + try { + // start timer + timer = new GLib.Timer(); + timer.start(); + + // execute script file + Process.spawn_async_with_pipes( + working_dir, // working dir + spawn_args, // argv + spawn_env, // environment + SpawnFlags.SEARCH_PATH, + null, // child_setup + out child_pid, + out input_fd, + out output_fd, + out error_fd); + + set_priority(); + + log_debug("AsyncTask: child_pid: %d".printf(child_pid)); + + // create stream readers + UnixOutputStream uos_in = new UnixOutputStream(input_fd, false); + UnixInputStream uis_out = new UnixInputStream(output_fd, false); + UnixInputStream uis_err = new UnixInputStream(error_fd, false); + dos_in = new DataOutputStream(uos_in); + dis_out = new DataInputStream(uis_out); + dis_err = new DataInputStream(uis_err); + dis_out.newline_type = DataStreamNewlineType.ANY; + dis_err.newline_type = DataStreamNewlineType.ANY; + + // create log file + if (log_file.length > 0){ + var file = File.new_for_path(log_file); + if (file.query_exists()){ + file.delete(); + } + var file_stream = file.create (FileCreateFlags.REPLACE_DESTINATION); + dos_log = new DataOutputStream (file_stream); + } + + try { + //start thread for reading output stream + Thread.create (read_stdout, true); + } catch (Error e) { + log_error ("AsyncTask.begin():create_thread:read_stdout()"); + log_error (e.message); + } + + try { + //start thread for reading error stream + Thread.create (read_stderr, true); + } catch (Error e) { + log_error ("AsyncTask.begin():create_thread:read_stderr()"); + log_error (e.message); + } + } + catch (Error e) { + log_error ("AsyncTask.begin()"); + log_error(e.message); + has_started = false; + //status = AppStatus.FINISHED; + } + + return has_started; + } + + private void read_stdout() { + try { + stdout_is_open = true; + + out_line = dis_out.read_line (null); + while (out_line != null) { + //log_msg("O: " + out_line); + if (!is_terminated && (out_line.length > 0)){ + parse_stdout_line(out_line); + stdout_line_read(out_line); //signal + } + out_line = dis_out.read_line (null); //read next + } + + stdout_is_open = false; + + // dispose stdout + if ((dis_out != null) && !dis_out.is_closed()){ + dis_out.close(); + } + //dis_out.close(); + dis_out = null; + GLib.FileUtils.close(output_fd); + + // check if complete + if (!stdout_is_open && !stderr_is_open){ + finish(); + } + } + catch (Error e) { + log_error ("AsyncTask.read_stdout()"); + log_error (e.message); + } + } + + private void read_stderr() { + try { + stderr_is_open = true; + + err_line = dis_err.read_line (null); + while (err_line != null) { + if (!is_terminated && (err_line.length > 0)){ + error_msg += "%s\n".printf(err_line); + + parse_stderr_line(err_line); + stderr_line_read(err_line); //signal + } + err_line = dis_err.read_line (null); //read next + } + + stderr_is_open = false; + + // dispose stderr + if ((dis_err != null) && !dis_err.is_closed()){ + dis_err.close(); + } + //dis_err.close(); + dis_err = null; + GLib.FileUtils.close(error_fd); + + // check if complete + if (!stdout_is_open && !stderr_is_open){ + finish(); + } + } + catch (Error e) { + log_error ("AsyncTask.read_stderr()"); + log_error (e.message); + } + } + + public void write_stdin(string line){ + try{ + if (status == AppStatus.RUNNING){ + dos_in.put_string(line + "\n"); + } + else{ + log_error ("AsyncTask.write_stdin(): NOT RUNNING"); + } + } + catch(Error e){ + log_error ("AsyncTask.write_stdin(): %s".printf(line)); + log_error (e.message); + } + } + + protected abstract void parse_stdout_line(string out_line); + + protected abstract void parse_stderr_line(string err_line); + + private void finish(){ + // finish() gets called by 2 threads but should be executed only once + + lock (finish_called){ + if (finish_called) { return; } + finish_called = true; + } + + log_debug("AsyncTask: finish(): enter"); + + // dispose stdin + try{ + if ((dos_in != null) && !dos_in.is_closed() && !dos_in.is_closing()){ + dos_in.close(); + } + } + catch(Error e){ + // ignore + //log_error ("AsyncTask.finish(): dos_in.close()"); + //log_error (e.message); + } + + dos_in = null; + GLib.FileUtils.close(input_fd); + + // dispose child process + Process.close_pid(child_pid); //required on Windows, doesn't do anything on Unix + + try{ + // dispose log + if ((dos_log != null) && !dos_log.is_closed() && !dos_log.is_closing()){ + dos_log.close(); + } + dos_log = null; + } + catch (Error e) { + // error can be ignored + // dos_log is closed automatically when the last reference is set to null + // there may be pending operations which may throw an error + } + + status_line = ""; + err_line = ""; + out_line = ""; + + timer.stop(); + + finish_task(); + + if ((status != AppStatus.CANCELLED) && (status != AppStatus.PASSWORD_REQUIRED)) { + status = AppStatus.FINISHED; + } + + //dir_delete(working_dir); + + task_complete(); //signal + } + + protected abstract void finish_task(); + + public int get_exit_code(){ + int exit_code = -1; + var path = file_parent(script_file) + "/status"; + if (file_exists(path)){ + var txt = file_read(path); + exit_code = int.parse(txt); + } + log_debug(file_parent(script_file)); + log_debug("exit_code: %d".printf(exit_code)); + return exit_code; + } + + public bool is_running { + get { + return (status == AppStatus.RUNNING); + } + } + + // public actions -------------- + + public void pause() { + Pid sub_child_pid; + foreach (long pid in get_process_children(child_pid)) { + sub_child_pid = (Pid) pid; + process_pause(sub_child_pid); + } + + status = AppStatus.PAUSED; + } + + public void resume() { + Pid sub_child_pid; + foreach (long pid in get_process_children(child_pid)) { + sub_child_pid = (Pid) pid; + process_resume(sub_child_pid); + } + + status = AppStatus.RUNNING; + } + + public void stop(AppStatus status_to_update = AppStatus.CANCELLED) { + + log_debug("AsyncTask: stop(): %s".printf(status_to_update.to_string())); + + // we need to un-freeze the processes before we kill them + if (status == AppStatus.PAUSED) { + resume(); + } + + status = status_to_update; + + process_quit(child_pid); + + log_debug("process_quit: %d".printf(child_pid)); + } + + public void set_priority() { + if (background_mode){ + set_priority_value(5); + } + else{ + set_priority_value(0); + } + } + + public void set_priority_value(int prio) { + Pid app_pid = Posix.getpid(); + process_set_priority (app_pid, prio); + + if (status == AppStatus.RUNNING) { + process_set_priority (child_pid, prio); + + Pid sub_child_pid; + foreach (long pid in get_process_children (child_pid)) { + sub_child_pid = (Pid) pid; + process_set_priority (sub_child_pid, prio); + } + } + } + + public string stat_time_elapsed{ + owned get{ + long elapsed = (long) timer_elapsed(timer); + return format_duration(elapsed); + } + } + + public string stat_time_remaining{ + owned get{ + if (progress > 0){ + long elapsed = (long) timer_elapsed(timer); + long remaining = (long)((elapsed / progress) * (1.0 - progress)); + if (remaining < 0){ + remaining = 0; + } + return format_duration(remaining); + } + else{ + return "???"; + } + } + } + + public void print_app_status(){ + switch(status){ + case AppStatus.NOT_STARTED: + log_debug("status=%s".printf("NOT_STARTED")); + break; + case AppStatus.RUNNING: + log_debug("status=%s".printf("RUNNING")); + break; + case AppStatus.PAUSED: + log_debug("status=%s".printf("PAUSED")); + break; + case AppStatus.FINISHED: + log_debug("status=%s".printf("FINISHED")); + break; + case AppStatus.CANCELLED: + log_debug("status=%s".printf("CANCELLED")); + break; + case AppStatus.PASSWORD_REQUIRED: + log_debug("status=%s".printf("PASSWORD_REQUIRED")); + break; + } + } +} + +public enum AppStatus { + NOT_STARTED, + RUNNING, + PAUSED, + FINISHED, + CANCELLED, + PASSWORD_REQUIRED +} + +/* Sample Subclass: +public class RsyncTask : AsyncTask{ + + // parameters + public bool delete_extra = true; + + public RsyncTask(){ + * + init_regular_expressions(); + } + + private void init_regular_expressions(){ + + regex_list = new Gee.HashMap(); + + try { + // (1.00/100%) + regex_list["qemu-convert"] = new Regex("""[ \t]*[(]?([0-9.]+)\/[0-9.]+[%]?[)]?"""); + } + catch (Error e) { + log_error (e.message); + } + } + + public void prepare() { + + string script_text = build_script(); + save_bash_script_temp(script_text, script_file); + + count_completed = 0; + count_total = 100; + } + + private string build_script() { + + var script = new StringBuilder(); + + var cmd = "rsync -ai"; + + cmd += " --numeric-ids --stats --relative --delete-excluded"; + + return script.str; + } + + // execution ---------------------------- + + public void execute() { + + prepare(); + + begin(); + + if (status == AppStatus.RUNNING){ + + + } + } + + public override void parse_stdout_line(string out_line){ + if (is_terminated) { + return; + } + + update_progress_parse_console_output(out_line); + } + + public override void parse_stderr_line(string err_line){ + if (is_terminated) { + return; + } + + update_progress_parse_console_output(err_line); + } + + public bool update_progress_parse_console_output (string line) { + + if ((line == null) || (line.length == 0)) { return true; } + + MatchInfo match; + if (regex_list["qemu-convert"].match(line, 0, out match)) { + string txt = match.fetch(1); + count_completed = int.parse(txt); + status_line = "%lld%%".printf(count_completed); + } + + return true; + } + + protected override void finish_task(){ + if ((status != AppStatus.CANCELLED) && (status != AppStatus.PASSWORD_REQUIRED)) { + status = AppStatus.FINISHED; + } + } + + public int read_status(){ + var status_file = working_dir + "/status"; + var f = File.new_for_path(status_file); + if (f.query_exists()){ + var txt = file_read(status_file); + return int.parse(txt); + } + return -1; + } +} +*/ diff --git a/src/Utility/Console/Device.vala b/src/Utility/Console/Device.vala new file mode 100644 index 0000000..ce4df91 --- /dev/null +++ b/src/Utility/Console/Device.vala @@ -0,0 +1,2586 @@ + +/* + * Device.vala + * + * Copyright 2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +/* Functions and classes for handling disk partitions */ + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.ProcessHelper; + +public class Device : GLib.Object{ + + /* Class for storing disk information */ + + public static double KB = 1000; + public static double MB = 1000 * KB; + public static double GB = 1000 * MB; + + public static double KiB = 1024; + public static double MiB = 1024 * KiB; + public static double GiB = 1024 * MiB; + + public string device = ""; + public string name = ""; + public string kname = ""; + public string pkname = ""; + public string pkname_toplevel = ""; + public string mapped_name = ""; + public string uuid = ""; + public string label = ""; + public int major = -1; + public int minor = -1; + + public string type = ""; // disk, part, crypt, loop, rom, lvm + public string fstype = ""; // iso9660, ext4, btrfs, ... + + public int order = -1; + + public string vendor = ""; + public string model = ""; + public string serial = ""; + public string revision = ""; + + public bool removable = false; + public bool read_only = false; + + public int64 size_bytes = 0; + public int64 used_bytes = 0; + public int64 available_bytes = 0; + + //public string used_percent = ""; + public string dist_info = ""; + public Gee.ArrayList mount_points = new Gee.ArrayList(); + public Gee.ArrayList symlinks = new Gee.ArrayList(); + + public Device? parent = null; + public Gee.ArrayList children = new Gee.ArrayList(); + + private static string lsblk_version = ""; + private static bool lsblk_is_ancient = false; + + private static Gee.ArrayList device_list; + + private static DeviceMonitor? monitor; + + // static ----------------------------- + + public static void init(){ + + get_block_devices(); + + get_monitor(); + } + + public static DeviceMonitor get_monitor(){ + + if (monitor != null){ return monitor; } + + var monitor = DeviceMonitor.get_monitor(); + + monitor.changed.connect(()=>{ + //get_block_devices_using_lsblk(); + get_block_devices(); + }); + + return monitor; + } + + public static void test_lsblk_version(){ + + if ((lsblk_version != null) && (lsblk_version.length > 0)){ + return; + } + + string std_out, std_err; + int status = exec_sync("lsblk --bytes --pairs --output HOTPLUG,PKNAME,VENDOR,SERIAL,REV", out std_out, out std_err); + if (status == 0){ + lsblk_version = std_out; + lsblk_is_ancient = false; + } + else{ + lsblk_version = "ancient"; + lsblk_is_ancient = true; + } + } + + public static Gee.ArrayList get_devices(){ + + if (device_list == null){ + get_block_devices(); + } + + return device_list; + } + + // instance ------------------ + + public Device(){ + mount_points = new Gee.ArrayList(); + symlinks = new Gee.ArrayList(); + children = new Gee.ArrayList(); + + test_lsblk_version(); + } + + public int64 free_bytes{ + get{ + return (used_bytes == 0) ? 0 : (size_bytes - used_bytes); + } + } + + public string size_formatted{ + owned get{ + return (size_bytes == 0) ? "" : format_file_size(size_bytes); + } + } + + public string used_formatted{ + owned get{ + return (used_bytes == 0) ? "" : format_file_size(used_bytes); + } + } + + public string free_formatted{ + owned get{ + return (free_bytes == 0) ? "" : format_file_size(free_bytes); + } + } + + public string mount_path{ + owned get{ + string mpath = ""; + foreach(var mp in mount_points){ + if (mpath.length == 0){ + mpath = mp.mount_point; + } + else if (mp.subvolume_name() == "/"){ + mpath = mp.mount_point; // use this instead of first one + } + } + return mpath; + } + } + + public bool is_mounted { + get { + return (mount_points.size > 0); + } + } + + public bool is_mounted_at_path(string subvolname, string mount_path){ + + foreach (var mnt in mount_points){ + if (mnt.mount_point == mount_path){ + if (subvolname.length == 0){ + return true; + } + else if (mnt.mount_options.contains("subvol=%s".printf(subvolname)) + || mnt.mount_options.contains("subvol=/%s".printf(subvolname))){ + + return true; + } + } + } + + return false; + } + + public bool has_linux_filesystem(){ + switch (fstype){ + case "ext2": + case "ext3": + case "ext4": + case "reiserfs": + case "reiser4": + case "xfs": + case "jfs": + case "btrfs": + case "lvm": + case "lvm2": + case "lvm2_member": + case "luks": + case "crypt": + case "crypto_luks": + return true; + default: + return false; + } + } + + public bool is_encrypted_partition { + get { + return (type == "part") && fstype.down().contains("luks"); + } + } + + public bool is_on_encrypted_partition { + get { + return (type == "crypt"); + } + } + + public bool is_lvm_partition(){ + return (type == "part") && fstype.down().contains("lvm2_member"); + } + + public bool has_children { + get{ + return (children.size > 0); + } + } + + public Device? first_linux_child(){ + + foreach(var child in children){ + if (child.has_linux_filesystem()){ + return child; + } + } + + return null; + } + + public bool has_parent(){ + return (parent != null); + } + + public bool is_system_device { + get { + bool is_system = false; + + foreach (var mnt in mount_points){ + switch (mnt.mount_point){ + case "/": + case "/boot": + case "/boot/efi": + case "/home": + is_system = true; + break; + default: + if (fstype == "swap"){ + is_system = true; + } + break; + } + } + + return is_system; + } + } + + public bool is_snap_volume { + get { + return (mount_points.size > 0) && (mount_points[0].mount_point.has_prefix("/snap/")); + } + } + + public bool is_swap_volume { + get { + return (fstype == "swap"); + } + } + + // actions ------------------------------ + + public bool unmount(){ + + var cmd = "udisksctl unmount -b '%s'".printf(device); + log_debug(cmd); + string std_err, std_out; + exec_sync(cmd, out std_out, out std_err); + + if (std_err.length > 0){ + log_error(std_err); + } + + query_mount_points(); + return is_mounted; + } + + public bool automount(bool show_on_success = false){ + + query_mount_points(); + if (is_mounted){ + return true; + } + + string std_out, std_err; + int status; + if (device.has_prefix("/dev/nbd")){ + + string mpath = "/mnt/%s".printf(uuid); + + string cmd = ""; + cmd += "mkdir -p '%s' &&".printf(escape_single_quote(mpath)); + cmd += "mount '%s' '%s'".printf(device, mpath); + log_debug(cmd); + + status = exec_script_sync(cmd, out std_out, out std_err, false, true); + } + else { + var cmd = ""; + cmd += "udisksctl mount -b '%s'".printf(device); + log_debug(cmd); + + status = exec_sync(cmd, out std_out, out std_err); + } + + query_mount_points(); + + if (is_mounted){ + string message = _("Device mounted successfully"); + string details = "%s: %s, %s: %s".printf(_("Device"), device, _("Path"), mount_points[0].mount_point); + bool is_error = false; + show_message(message, details, is_error, show_on_success); + return is_error; + } + else{ + string message = _("Failed to mount device"); + string details = "%s: %s\n\n%s".printf(_("Device"), device, std_err); + bool is_error = true; + show_message(message, details, is_error, show_on_success); + return is_error; + } + } + + public bool unlock(string mapped_name, string passphrase, bool show_on_success = false){ + + /* Unlocks a LUKS device using provided passphrase. + * Prompts the user for passphrase if empty. + * Displays a GTK prompt if parent_window is not null + * Otherwise prompts user on terminal with a timeout of 20 secsonds + * */ + + log_debug("Device: unlock(): %s".printf(device)); + + Device unlocked_device = null; + string std_out = "", std_err = ""; + bool is_error = false; + string message = ""; + string details = ""; + + // check if not encrypted + if (!is_encrypted_partition){ + log_debug("not encrypted!"); + return true; + } + + // check if already unlocked + query_changes(); + if (has_children){ + log_debug("has children!"); + return true; + } + + string luks_pass = passphrase; + string luks_name = mapped_name; + + if ((luks_name == null) || (luks_name.length == 0)){ + luks_name = "%s_crypt".printf(kname); + } + + // console mode + + if ((luks_pass == null) || (luks_pass.length == 0)){ + + // prompt user on terminal and unlock, else timeout after 20 secs + + var counter = new TimeoutCounter(); + counter.kill_process_on_timeout("cryptsetup", 20, true); + string cmd = "cryptsetup luksOpen '%s' '%s'".printf(device, luks_name); + + log_debug(cmd); + Posix.system(cmd); + counter.stop(); + log_msg(""); + + // no need to show messages + } + else{ + + // use password to unlock + + var cmd = "echo -n -e '%s' | cryptsetup luksOpen --key-file - '%s' '%s'\n".printf( + luks_pass, device, luks_name); + + log_debug(cmd.replace(luks_pass, "**PASSWORD**")); + + int status = exec_script_sync(cmd, out std_out, out std_err, false, true); + + switch (status){ + case 512: // invalid passphrase + message = _("Wrong password"); + details = _("Failed to unlock device"); + show_message(message, details, true, show_on_success); + return false; + } + } + + // check if unlocked + query_changes(); + if (has_children){ + unlocked_device = children[0]; + } + + if (unlocked_device == null){ + message = _("Failed to unlock device"); + details = "%s: %s\n\n%s".printf(_("Device"), device, std_err); + is_error = true; + } + else{ + message = _("Unlocked successfully"); + details = "%s: %s, %s: /dev/mapper/%s".printf(_("Device"), device, _("Unlocked"), unlocked_device.mapped_name); + is_error = false; + } + + show_message(message, details, is_error, show_on_success); + return (unlocked_device != null); + } + + public bool lock_device(bool show_on_success = false){ + + log_debug("Device: lock_device(): %s".printf(device)); + + // check if not on encrypted device + if (!is_encrypted_partition){ + log_debug("Device not encrypted!"); + return true; + } + + if (!has_children){ + log_debug("Device does not have unlocked children!"); + return true; + } + + var cmd = "cryptsetup luksClose %s".printf(children[0].mapped_name); + log_debug(cmd); + string std_out, std_err; + exec_script_sync(cmd, out std_out, out std_err, false, true); // prompt user if not admin + + query_changes(); + + if (has_children){ + string message = _("Failed to lock device"); + string details = "%s: %s\n\n%s".printf(_("Device"), device, std_err); + bool is_error = true; + show_message(message, details, is_error, show_on_success); + return !is_error; + } + else{ + string message = _("Locked successfully"); + string details = "%s: %s".printf(_("Locked"), parent.device); + bool is_error = false; + show_message(message, details, is_error, show_on_success); + return !is_error; + } + } + + public void flush_buffers(){ + if (!is_mounted) { return; } + if (type != "disk") { return; } + string cmd = "blockdev --flushbufs %s".printf(device); + Posix.system(cmd); + } + + // static -------------------------------- + + public static Gee.ArrayList get_block_devices(){ + + /* Returns list of block devices + Populates all fields in Device class */ + + log_debug("Device: get_block_devices()"); + + var list = get_block_devices_using_lsblk(); + + if (device_list == null){ + device_list = list; // initialize in advance if null + } + + //update_device_ids(list); + + update_usage(list); + + update_mounts(list); + + device_list = list; + + //print_device_list(list); + + //print_device_mounts(list); + + log_debug("Device: get_block_devices(): %d".printf(device_list.size)); + + return device_list; + } + + public static void update_usage(Gee.ArrayList list = get_devices()){ + + log_debug("Device: update_usage(): %d".printf(list.size)); + + var list_df = get_disk_space_using_df(); + + foreach(var dev_df in list_df){ + + var dev = find_device_in_list_by_uuid(list, dev_df.uuid); + + if (dev != null){ + dev.size_bytes = dev_df.size_bytes; + dev.used_bytes = dev_df.used_bytes; + dev.available_bytes = dev_df.available_bytes; + } + } + } + + public static void update_mounts(Gee.ArrayList list = get_devices()){ + + log_debug("Device: update_mounts(): %d".printf(list.size)); + + var list_mtab = get_mounted_filesystems_using_mtab(); + + foreach(var dev_mtab in list_mtab){ + + var dev = find_device_in_list_by_uuid(list, dev_mtab.uuid); + + if (dev != null){ + dev.mount_points = dev_mtab.mount_points; + } + } + } + + private static void find_child_devices(Gee.ArrayList list, Device parent){ + if (lsblk_is_ancient && (parent.type == "disk")){ + foreach (var part in list){ + if ((part.kname != parent.kname) && part.kname.has_prefix(parent.kname)){ + parent.children.add(part); + part.parent = parent; + part.pkname = parent.kname; + //log_debug("%s -> %s".printf(parent.kname, part.kname)); + } + } + } + else{ + foreach (var part in list){ + if (part.pkname == parent.kname){ + parent.children.add(part); + part.parent = parent; + } + } + } + } + + private static void find_toplevel_parent(Gee.ArrayList list, Device dev){ + + if (dev.pkname.length == 0){ return; } + + var top_kname = dev.pkname; + + foreach (var part in list){ + if (part.kname == top_kname){ + if (part.pkname.length > 0){ + top_kname = part.pkname; // get parent's parent if not empty + } + } + } + + dev.pkname_toplevel = top_kname; + + //log_debug("%s -> %s -> %s".printf(dev.pkname_toplevel, dev.pkname, dev.kname)); + } + + private static void find_child_devices_using_dmsetup(Gee.ArrayList list){ + + string std_out, std_err; + exec_sync("dmsetup deps -o blkdevname", out std_out, out std_err); + + /* + sdb3_crypt: 1 dependencies : (sdb3) + sda5_crypt: 1 dependencies : (sda5) + mmcblk0_crypt: 1 dependencies : (mmcblk0) + */ + + Regex rex; + MatchInfo match; + + foreach(string line in std_out.split("\n")){ + if (line.strip().length == 0) { continue; } + + try{ + + rex = new Regex("""([^:]*)\:.*\((.*)\)"""); + + if (rex.match (line, 0, out match)){ + + string child_name = match.fetch(1).strip(); + string parent_kname = match.fetch(2).strip(); + + Device parent = null; + foreach(var dev in list){ + if ((dev.kname == parent_kname)){ + parent = dev; + break; + } + } + + Device child = null; + foreach(var dev in list){ + if ((dev.mapped_name == child_name)){ + child = dev; + break; + } + } + + if ((parent != null) && (child != null)){ + child.pkname = parent.kname; + //log_debug("%s -> %s".printf(parent.kname, child.kname)); + } + + } + else{ + log_debug("no-match: %s".printf(line)); + } + } + catch(Error e){ + log_error (e.message); + } + } + } + + + public static Gee.ArrayList get_block_devices_using_lsblk(string dev_name = ""){ + + //log_debug("Device: get_block_devices_using_lsblk()"); + + /* Returns list of mounted partitions using 'lsblk' command + Populates device, type, uuid, label */ + + test_lsblk_version(); + + var list = new Gee.ArrayList(); + + string std_out; + string std_err; + string cmd; + int ret_val; + Regex rex; + MatchInfo match; + + if (lsblk_is_ancient){ + cmd = "lsblk --bytes --pairs --output NAME,KNAME,LABEL,UUID,TYPE,FSTYPE,SIZE,MOUNTPOINT,MODEL,RO,RM,MAJ:MIN"; + } + else{ + cmd = "lsblk --bytes --pairs --output NAME,KNAME,LABEL,UUID,TYPE,FSTYPE,SIZE,MOUNTPOINT,MODEL,RO,HOTPLUG,MAJ:MIN,PKNAME,VENDOR,SERIAL,REV"; + } + + if (dev_name.length > 0){ + cmd += " %s".printf(dev_name); + } + + //if (LOG_DEBUG){ + // log_debug(""); + // log_debug(cmd); + //} + + ret_val = exec_sync(cmd, out std_out, out std_err); + + //if (ret_val != 0){ + // var msg = "lsblk: " + _("Failed to get partition list"); + // msg += (device_file.length > 0) ? ": " + device_file : ""; + // log_error (msg); + // return list; //return empty map + //} + + /* + sample output + ----------------- + NAME="sda" KNAME="sda" PKNAME="" LABEL="" UUID="" FSTYPE="" SIZE="119.2G" MOUNTPOINT="" HOTPLUG="0" + + NAME="sda1" KNAME="sda1" PKNAME="sda" LABEL="" UUID="5345-E139" FSTYPE="vfat" SIZE="47.7M" MOUNTPOINT="/boot/efi" HOTPLUG="0" + + NAME="mmcblk0p1" KNAME="mmcblk0p1" PKNAME="mmcblk0" LABEL="" UUID="3c0e4bbf" FSTYPE="crypto_LUKS" SIZE="60.4G" MOUNTPOINT="" HOTPLUG="1" + + NAME="luks-3c0" KNAME="dm-1" PKNAME="mmcblk0p1" LABEL="" UUID="f0d933c0-" FSTYPE="ext4" SIZE="60.4G" MOUNTPOINT="/mnt/sdcard" HOTPLUG="0" + */ + + /* + Note: Multiple loop devices can have same UUIDs. + Example: Loop devices created by mounting the same ISO multiple times. + */ + + //parse output and build filesystem map ------------- + + int index = -1; + + foreach(string line in std_out.split("\n")){ + if (line.strip().length == 0) { continue; } + + try{ + if (lsblk_is_ancient){ + rex = new Regex("""NAME="(.*)" KNAME="(.*)" LABEL="(.*)" UUID="(.*)" TYPE="(.*)" FSTYPE="(.*)" SIZE="(.*)" MOUNTPOINT="(.*)" MODEL="(.*)" RO="([0-9]+)" RM="([0-9]+)" MAJ:MIN="([0-9:]+)""""); + } + else{ + rex = new Regex("""NAME="(.*)" KNAME="(.*)" LABEL="(.*)" UUID="(.*)" TYPE="(.*)" FSTYPE="(.*)" SIZE="(.*)" MOUNTPOINT="(.*)" MODEL="(.*)" RO="([0-9]+)" HOTPLUG="([0-9]+)" MAJ:MIN="([0-9:]+)" PKNAME="(.*)" VENDOR="(.*)" SERIAL="(.*)" REV="(.*)""""); + } + + if (rex.match (line, 0, out match)){ + + Device pi = new Device(); + pi.name = match.fetch(1).strip(); + pi.kname = match.fetch(2).strip(); + pi.label = match.fetch(3); // do not strip - labels can have leading or trailing spaces + pi.uuid = match.fetch(4).strip(); + pi.type = match.fetch(5).strip().down(); + + pi.fstype = match.fetch(6).strip().down(); + pi.fstype = (pi.fstype == "crypto_luks") ? "luks" : pi.fstype; + pi.fstype = (pi.fstype == "lvm2_member") ? "lvm2" : pi.fstype; + + pi.size_bytes = int64.parse(match.fetch(7).strip()); + + var mp = match.fetch(8).strip(); + if (mp.length > 0){ + pi.mount_points.add(new MountEntry(pi,mp,"")); + } + + pi.model = match.fetch(9).strip(); + + pi.read_only = (match.fetch(10).strip() == "1"); + + pi.removable = (match.fetch(11).strip() == "1"); + + string txt = match.fetch(12).strip(); + if (txt.contains(":")){ + pi.major = int.parse(txt.split(":")[0]); + pi.minor = int.parse(txt.split(":")[1]); + } + + if (!lsblk_is_ancient){ + pi.pkname = match.fetch(13).strip(); + pi.vendor = match.fetch(14).strip(); + pi.serial = match.fetch(15).strip(); + pi.revision = match.fetch(16).strip(); + } + + pi.order = ++index; + pi.device = "/dev/%s".printf(pi.kname); + + //if ((pi.type == "crypt") && (pi.pkname.length > 0)){ + // pi.name = "%s (unlocked)".printf(pi.pkname); + //} + + //if ((pi.uuid.length > 0) && (pi.pkname.length > 0)){ + list.add(pi); + //} + } + else{ + log_debug("no-match: %s".printf(line)); + } + } + catch(Error e){ + log_error (e.message); + } + } + + // already sorted + /*list.sort((a,b)=>{ + return (a.order - b.order); + });*/ + + // add aliases from /dev/disk/by-uuid/ + + foreach(var dev in list){ + var dev_by_uuid = path_combine("/dev/disk/by-uuid/", dev.uuid); + if (file_exists(dev_by_uuid)){ + dev.symlinks.add(dev_by_uuid); + } + } + + // add aliases from /dev/mapper/ + + try + { + File f_dev_mapper = File.new_for_path ("/dev/mapper"); + + FileEnumerator enumerator = f_dev_mapper.enumerate_children ( + "%s,%s".printf( + FileAttribute.STANDARD_NAME, FileAttribute.STANDARD_SYMLINK_TARGET), + FileQueryInfoFlags.NOFOLLOW_SYMLINKS); + + FileInfo info; + while ((info = enumerator.next_file ()) != null) { + + if (info.get_name() == "control") { continue; } + + File f_mapped = f_dev_mapper.resolve_relative_path(info.get_name()); + + string mapped_file = f_mapped.get_path(); + string mapped_device = info.get_symlink_target(); + mapped_device = mapped_device.replace("..","/dev"); + //log_debug("info.get_name(): %s".printf(info.get_name())); + //log_debug("info.get_symlink_target(): %s".printf(info.get_symlink_target())); + //log_debug("mapped_file: %s".printf(mapped_file)); + //log_debug("mapped_device: %s".printf(mapped_device)); + + foreach(var dev in list){ + if (dev.device == mapped_device){ + dev.mapped_name = mapped_file.replace("/dev/mapper/",""); + dev.symlinks.add(mapped_file); + //log_debug("found link: %s -> %s".printf(mapped_file, dev.device)); + break; + } + } + } + } + catch (Error e) { + log_error (e.message); + } + + foreach (var part in list){ + find_child_devices(list, part); + find_toplevel_parent(list, part); + } + + //find_toplevel_parent(); + + if (lsblk_is_ancient){ + find_child_devices_using_dmsetup(list); + } + + //print_device_list(list); + + //log_debug("Device: get_block_devices_using_lsblk(): %d".printf(list.size)); + + return list; + } + + /* Not useful */ + public static Gee.ArrayList get_block_devices_using_glib(){ + + log_debug("Device: get_block_devices_using_glib()"); + + var list = new Gee.ArrayList(); + + var vmon = VolumeMonitor.get(); + var volumes = vmon.get_volumes(); + foreach (var volume in volumes) { + Device dev = new Device(); + dev.uuid = volume.get_uuid(); + list.add(dev); + /* + stdout.printf (" - name: %s\n", volume.get_name()); + stdout.printf (" - uuid: %s\n", volume.get_uuid()); + stdout.printf (" - UUID: %s\n", volume.get_identifier(GLib.VolumeIdentifier.UUID)); + stdout.printf (" - LABEL: %s\n", volume.get_identifier(GLib.VolumeIdentifier.LABEL)); + stdout.printf (" - UNIX_DEVICE: %s\n", volume.get_identifier(GLib.VolumeIdentifier.UNIX_DEVICE)); + stdout.printf (" - NFS_MOUNT: %s\n", volume.get_identifier(GLib.VolumeIdentifier.NFS_MOUNT)); + stdout.printf (" - HAL_UDI: %s\n", volume.get_identifier(GLib.VolumeIdentifier.HAL_UDI)); + stdout.printf (" - CLASS: %s\n", volume.get_identifier(GLib.VolumeIdentifier.CLASS)); + * */ + } + + return list; + } + + public static Gee.ArrayList get_disk_space_using_df(string dev_name_or_mount_point = ""){ + + /* + Returns list of mounted partitions using 'df' command + Populates device, type, size, used and mount_point_list + */ + + var list = new Gee.ArrayList(); + + string std_out; + string std_err; + string cmd; + int ret_val; + + cmd = "df -T -B1"; + + if (dev_name_or_mount_point.length > 0){ + cmd += " '%s'".printf(escape_single_quote(dev_name_or_mount_point)); + } + + if (LOG_DEBUG){ + //log_debug(cmd); + } + + ret_val = exec_sync(cmd, out std_out, out std_err); + //ret_val is not reliable, no need to check + + /* + sample output + ----------------- + Filesystem Type 1M-blocks Used Available Use% Mounted on + /dev/sda3 ext4 25070M 19508M 4282M 83% / + none tmpfs 1M 0M 1M 0% /sys/fs/cgroup + udev devtmpfs 3903M 1M 3903M 1% /dev + tmpfs tmpfs 789M 1M 788M 1% /run + none tmpfs 5M 0M 5M 0% /run/lock + /dev/sda3 ext4 25070M 19508M 4282M 83% /mnt/timeshift + */ + + string[] lines = std_out.split("\n"); + + int line_num = 0; + foreach(string line in lines){ + + if (++line_num == 1) { continue; } + if (line.strip().length == 0) { continue; } + + Device pi = new Device(); + + //parse & populate fields ------------------ + + int k = 1; + foreach(string val in line.split(" ")){ + + if (val.strip().length == 0){ continue; } + + switch(k++){ + case 1: + pi.device = val.strip(); + break; + case 2: + pi.fstype = val.strip(); + break; + case 3: + pi.size_bytes = int64.parse(val.strip()); + break; + case 4: + pi.used_bytes = int64.parse(val.strip()); + break; + case 5: + pi.available_bytes = int64.parse(val.strip()); + break; + case 6: + //pi.used_percent = val.strip(); + break; + case 7: + //string mount_point = val.strip(); + //if (!pi.mount_point_list.contains(mount_point)){ + // pi.mount_point_list.add(mount_point); + //} + break; + } + } + + /* Note: + * The mount points displayed by 'df' are not reliable. + * For example, if same device is mounted at 2 locations, 'df' displays only the first location. + * Hence, we will not populate the 'mount_points' field in Device object + * Use get_mounted_filesystems_using_mtab() if mount info is required + * */ + + // resolve device name -------------------- + + //log_debug("pi.device=%s".printf(pi.device)); + + pi.device = resolve_device_name(pi.device); + + //log_debug("resolved pi.device=%s".printf(pi.device)); + + // get uuid --------------------------- + + pi.uuid = get_uuid_by_name(pi.device); + + //log_debug("resolved pi.uuid=%s".printf(pi.uuid)); + + // add to map ------------------------- + + if (pi.uuid.length > 0){ + list.add(pi); + } + } + + log_debug("Device: get_disk_space_using_df(): %d".printf(list.size)); + + return list; + } + + public static Gee.ArrayList get_mounted_filesystems_using_mtab(){ + + /* Returns list of mounted partitions by reading /proc/mounts + Populates device, type and mount_point_list */ + + var list = new Gee.ArrayList(); + + string mtab_path = "/etc/mtab"; + string mtab_lines = ""; + + File f; + + // find mtab file ----------- + + mtab_path = "/proc/mounts"; + f = File.new_for_path(mtab_path); + if(!f.query_exists()){ + mtab_path = "/proc/self/mounts"; + f = File.new_for_path(mtab_path); + if(!f.query_exists()){ + mtab_path = "/etc/mtab"; + f = File.new_for_path(mtab_path); + if(!f.query_exists()){ + return list; //empty list + } + } + } + + /* Note: + * /etc/mtab represents what 'mount' passed to the kernel + * whereas /proc/mounts shows the data as seen inside the kernel + * Hence /proc/mounts is always up-to-date whereas /etc/mtab might not be + * */ + + //read ----------- + + mtab_lines = file_read(mtab_path); + + /* + sample mtab + ----------------- + /dev/sda3 / ext4 rw,errors=remount-ro 0 0 + proc /proc proc rw,noexec,nosuid,nodev 0 0 + sysfs /sys sysfs rw,noexec,nosuid,nodev 0 0 + none /sys/fs/cgroup tmpfs rw 0 0 + none /sys/fs/fuse/connections fusectl rw 0 0 + none /sys/kernel/debug debugfs rw 0 0 + none /sys/kernel/security securityfs rw 0 0 + udev /dev devtmpfs rw,mode=0755 0 0 + + device - the device or remote filesystem that is mounted. + mountpoint - the place in the filesystem the device was mounted. + filesystemtype - the type of filesystem mounted. + options - the mount options for the filesystem + dump - used by dump to decide if the filesystem needs dumping. + fsckorder - used by fsck to detrmine the fsck pass to use. + */ + + //parse ------------ + + string[] lines = mtab_lines.split("\n"); + var mount_list = new Gee.ArrayList(); + + foreach (var line in lines){ + + if (line.strip().length == 0) { continue; } + + var pi = new Device(); + + var mp = new MountEntry(pi,"",""); + + //parse & populate fields ------------------ + + int k = 1; + foreach(string val in line.strip().split(" ")){ + + if (val.strip().length == 0){ continue; } + + switch(k++){ + case 1: //device + pi.device = val.strip(); + break; + case 2: //mountpoint + mp.mount_point = val.strip().replace("""\040"""," "); // replace space. TODO: other chars? + if (!mount_list.contains(mp.mount_point)){ + mount_list.add(mp.mount_point); + pi.mount_points.add(mp); + } + break; + case 3: //filesystemtype + pi.fstype = val.strip(); + break; + case 4: //options + mp.mount_options = val.strip(); + break; + default: + //ignore + break; + } + } + + // resolve device names ---------------- + + pi.device = resolve_device_name(pi.device); + + // get uuid --------------------------- + + pi.uuid = get_uuid_by_name(pi.device); + + // add to map ------------------------- + + if (pi.uuid.length > 0){ + var dev = find_device_in_list_by_uuid(list, pi.uuid); + if (dev == null){ + list.add(pi); + } + else{ + // add mount points to existing device + foreach(var item in pi.mount_points){ + dev.mount_points.add(item); + } + } + } + } + + log_debug("Device: get_mounted_filesystems_using_mtab(): %d".printf(list.size)); + + return list; + } + + public static Device? get_device_for_path(string path){ + + Device dev = null; + string mpath = ""; + + // find longest matching mount_path and device + foreach(var d in device_list){ + // loop through all mount_points (not just mount_path) + foreach(var mp in d.mount_points){ + if (path.has_prefix(mp.mount_point) && (mp.mount_point.length > mpath.length)){ + dev = d; + mpath = mp.mount_point; + } + } + } + + return dev; + } + + // deprecated: use get_block_devices_using_lsblk() instead + public static Gee.ArrayList get_block_devices_using_blkid(string dev_name = ""){ + + /* Returns list of mounted partitions using 'blkid' command + Populates device, type, uuid, label */ + + var list = new Gee.ArrayList(); + + string std_out; + string std_err; + string cmd; + int ret_val; + Regex rex; + MatchInfo match; + + cmd = "/sbin/blkid" + ((dev_name.length > 0) ? " " + dev_name: ""); + + if (LOG_DEBUG){ + log_debug(cmd); + } + + ret_val = exec_script_sync(cmd, out std_out, out std_err); + if (ret_val != 0){ + var msg = "blkid: " + _("Failed to get partition list"); + msg += (dev_name.length > 0) ? ": " + dev_name : ""; + log_error(msg); + return list; //return empty list + } + + /* + sample output + ----------------- + /dev/sda1: LABEL="System Reserved" UUID="F476B08076B04560" TYPE="ntfs" + /dev/sda2: LABEL="windows" UUID="BE00B6DB00B69A3B" TYPE="ntfs" + /dev/sda3: UUID="03f3f35d-71fa-4dff-b740-9cca19e7555f" TYPE="ext4" + */ + + //parse output and build filesystem map ------------- + + foreach(string line in std_out.split("\n")){ + if (line.strip().length == 0) { continue; } + + Device pi = new Device(); + + pi.device = line.split(":")[0].strip(); + + if (pi.device.length == 0) { continue; } + + //exclude non-standard devices -------------------- + + if (!pi.device.has_prefix("/dev/")){ + continue; + } + + if (pi.device.has_prefix("/dev/sd") || pi.device.has_prefix("/dev/hd") || pi.device.has_prefix("/dev/mapper/") || pi.device.has_prefix("/dev/dm")) { + //ok + } + else if (pi.device.has_prefix("/dev/disk/by-uuid/")){ + //ok, get uuid + pi.uuid = pi.device.replace("/dev/disk/by-uuid/",""); + } + else{ + continue; //skip + } + + //parse & populate fields ------------------ + + try{ + rex = new Regex("""LABEL=\"([^\"]*)\""""); + if (rex.match (line, 0, out match)){ + pi.label = match.fetch(1); // do not strip - labels can have leading or trailing spaces + } + + rex = new Regex("""UUID=\"([^\"]*)\""""); + if (rex.match (line, 0, out match)){ + pi.uuid = match.fetch(1).strip(); + } + + rex = new Regex("""TYPE=\"([^\"]*)\""""); + if (rex.match (line, 0, out match)){ + pi.fstype = match.fetch(1).strip(); + } + } + catch(Error e){ + log_error (e.message); + } + + //add to map ------------------------- + + if (pi.uuid.length > 0){ + list.add(pi); + } + } + + log_debug("Device: get_block_devices_using_blkid(): %d".printf(list.size)); + + return list; + } + + // static helpers ---------------------------------- + + public static void print_device_list_short(Gee.ArrayList list){ + + string txt = ""; + foreach(var item in list){ + txt += (txt.length == 0) ? "" : " "; + txt += "%s".printf(file_basename(item.device)); + } + log_debug("Devices: " + txt); + } + + public static Device? find_device_in_list_by_name(Gee.ArrayList list, string dev_name){ + + foreach(var dev in list){ + if (dev.device == dev_name){ + return dev; + } + else if (dev.kname == dev_name){ + return dev; + } + else if (dev.mapped_name == dev_name.replace("/dev/mapper/","")){ + return dev; + } + } + + return null; + } + + public static Device? find_device_in_list_by_uuid(Gee.ArrayList list, string dev_uuid){ + + foreach(var dev in list){ + if (dev.uuid == dev_uuid){ + return dev; + } + } + + return null; + } + + public static Device? get_device_by_uuid(string uuid){ + + foreach(var dev in device_list){ + if (dev.uuid == uuid){ + return dev; + } + } + + return null; + } + + public static Device? get_device_by_name(string file_name){ + + var device_name = resolve_device_name(file_name); + + foreach(var dev in device_list){ + if (dev.device == device_name){ + return dev; + } + } + + return null; + } + + public static Device? get_device_by_path(string path_to_check){ + + var list = Device.get_disk_space_using_df(path_to_check); + + print_device_list_short(list); + + if (list.size > 0){ + return list[0]; + } + + return null; + } + + public static string get_uuid_by_name(string device){ + + foreach(var dev in device_list){ + if (dev.device == device){ + return dev.uuid; + } + } + + return ""; + } + + public static Gee.ArrayList get_device_mount_points(string dev_name_or_uuid){ + + // resolve device name and uuid ----------------------------- + + string device = ""; + string uuid = ""; + if (dev_name_or_uuid.has_prefix("/dev")){ + device = dev_name_or_uuid; + uuid = Device.get_uuid_by_name(dev_name_or_uuid); + } + else{ + uuid = dev_name_or_uuid; + device = "/dev/disk/by-uuid/%s".printf(uuid); + device = resolve_device_name(device); + } + + var list_mtab = get_mounted_filesystems_using_mtab(); + + var dev = find_device_in_list_by_uuid(list_mtab, uuid); + + if (dev != null){ + return dev.mount_points; + } + else{ + return (new Gee.ArrayList()); + } + } + + public static bool device_is_mounted(string dev_name_or_uuid){ + + var mps = Device.get_device_mount_points(dev_name_or_uuid); + if (mps.size > 0){ + return true; + } + + return false; + } + + public static bool mount_point_in_use(string mount_point){ + var list = Device.get_mounted_filesystems_using_mtab(); + foreach (var dev in list){ + foreach(var mp in dev.mount_points){ + if (mp.mount_point.has_prefix(mount_point)){ + // check for any mount point at or under the given mount_point + return true; + } + } + } + return false; + } + + public static string resolve_device_name(string dev_alias){ + + string resolved = dev_alias; + + if (dev_alias.has_prefix("/dev/mapper/")){ + var link_path = file_get_symlink_target(dev_alias); + if (link_path.has_prefix("../")){ + resolved = link_path.replace("../","/dev/"); + } + } + + if (dev_alias.has_prefix("/dev/disk/")){ + var link_path = file_get_symlink_target(dev_alias); + if (link_path.has_prefix("../../")){ + resolved = link_path.replace("../../","/dev/"); + } + } + + if (dev_alias != resolved){ + //log_debug("Device: resolved '%s' to '%s'".printf(dev_alias, resolved)); + } + + return resolved; + } + + // instance helpers ------------------------------- + + public void copy_fields_from(Device dev2){ + + this.device = dev2.device; + this.name = dev2.name; + this.kname = dev2.kname; + this.pkname = dev2.pkname; + this.pkname_toplevel = dev2.pkname_toplevel; + this.mapped_name = dev2.mapped_name; + this.uuid = dev2.uuid; + this.label = dev2.label; + this.major = dev2.major; + this.minor = dev2.minor; + + this.type = dev2.type; + this.fstype = dev2.fstype; + this.dist_info = dev2.dist_info; + + this.vendor = dev2.vendor; + this.model = dev2.model; + this.serial = dev2.serial; + this.revision = dev2.revision; + this.removable = dev2.removable; + this.read_only = dev2.read_only; + + this.size_bytes = dev2.size_bytes; + this.used_bytes = dev2.used_bytes; + this.available_bytes = dev2.available_bytes; + + this.mount_points = dev2.mount_points; + this.symlinks = dev2.symlinks; + this.parent = dev2.parent; + this.children = dev2.children; + } + + public Device? query_changes(){ + + foreach (var dev in get_block_devices()){ + if (uuid.length > 0){ + if (dev.uuid == uuid){ + copy_fields_from(dev); + break; + } + } + else{ + if (dev.device == device){ + copy_fields_from(dev); + break; + } + } + } + + return this; + } + + public void query_disk_space(){ + + /* Updates disk space info */ + + var list_df = get_disk_space_using_df(device); + + var dev_df = find_device_in_list_by_uuid(list_df, uuid); + + if (dev_df != null){ + // update fields + size_bytes = dev_df.size_bytes; + used_bytes = dev_df.used_bytes; + available_bytes = dev_df.available_bytes; + } + } + + public void query_mount_points(){ + + /* Updates mount point information */ + + var list = get_mounted_filesystems_using_mtab(); + var dev = find_device_in_list_by_uuid(list, uuid); + if (dev != null){ + // update fields + mount_points = dev.mount_points; + } + } + + // mounting --------------------------------- + + public static bool automount_udisks(Device dev, bool show_on_success = false){ + + dev.query_mount_points(); + if (dev.is_mounted){ + return true; + } + + if (dev.device.has_prefix("/dev/nbd")){ + + string cmd = ""; + + string mpath = "/mnt/%s".printf(dev.uuid); + + cmd += "mkdir -p '%s'".printf(escape_single_quote(mpath)); + + cmd += "\n"; + + cmd += "mount '%s' '%s'".printf(dev.device, mpath); + + cmd += "\n"; + + string std_out, std_err; + exec_script_sync(cmd, out std_out, out std_err, false, true); + + if (std_err.length > 0){ + log_error(std_err); + return false; + } + + return true; + } + + var cmd = "udisksctl mount -b '%s'".printf(dev.device); + log_debug(cmd); + string std_out, std_err; + int status = exec_sync(cmd, out std_out, out std_err); + + dev.query_mount_points(); + if (dev.is_mounted){ + string message = _("Device mounted successfully"); + string details = "%s: %s, %s: %s".printf(_("Device"), dev.device, _("Path"), dev.mount_points[0].mount_point); + bool is_error = false; + show_message(message, details, is_error, show_on_success); + } + else{ + string message = _("Failed to mount device"); + string details = "%s: %s\n\n%s".printf(_("Device"), dev.device, std_err); + bool is_error = true; + show_message(message, details, is_error, show_on_success); + } + + return (status == 0); + } + + public static Device? automount_udisks_iso(string iso_file_path){ + + Device? loop_dev = null; + + if (!file_exists(iso_file_path)){ + string msg = "%s: %s".printf(_("Could not find file"), iso_file_path); + log_error(msg); + return loop_dev; + } + + var cmd = "udisksctl loop-setup -r -f '%s'".printf( + escape_single_quote(iso_file_path)); + + log_debug(cmd); + string std_out, std_err; + int exit_code = exec_sync(cmd, out std_out, out std_err); + + if (exit_code == 0){ + log_msg("%s".printf(std_out)); + //log_msg("%s".printf(std_err)); + + if (!std_out.contains(" as ")){ + log_error("Could not determine loop device"); + return loop_dev; + } + + var loop_name = std_out.split(" as ")[1].replace(".","").strip(); + log_msg("Loop device: %s".printf(loop_name)); + + get_block_devices(); // required + loop_dev = Device.get_device_by_name(loop_name); + } + + return loop_dev; + } + + public static bool unmount_udisks(string dev_name_or_uuid){ + + if (dev_name_or_uuid.length == 0){ + log_error(_("Device name is empty!")); + return false; + } + + var cmd = "udisksctl unmount -b '%s'".printf(dev_name_or_uuid); + log_debug(cmd); + string std_err, std_out; + int status = exec_sync(cmd, out std_out, out std_err); + + if (std_err.length > 0){ + log_error(std_err); + } + + return (status == 0); + } + + public static Device? luks_unlock(Device dev, string mapped_name, string passphrase, bool show_on_success = false){ + + /* Unlocks a LUKS device using provided passphrase. + * Prompts the user for passphrase if empty. + * Displays a GTK prompt if parent_window is not null + * Otherwise prompts user on terminal with a timeout of 20 secsonds + * */ + + Device unlocked_device = null; + string std_out = "", std_err = ""; + bool is_error = false; + string message = ""; + string details = ""; + + // check if not encrypted + if (!dev.is_encrypted_partition){ + return dev; + } + + // check if already unlocked + dev.query_changes(); + if (dev.has_children){ + return dev.children[0]; + } + + string luks_pass = passphrase; + string luks_name = mapped_name; + + if ((luks_name == null) || (luks_name.length == 0)){ + luks_name = "%s_crypt".printf(dev.kname); + } + + // console mode + + if ((luks_pass == null) || (luks_pass.length == 0)){ + + // prompt user on terminal and unlock, else timeout after 20 secs + + var counter = new TimeoutCounter(); + counter.kill_process_on_timeout("cryptsetup", 20, true); + string cmd = "cryptsetup luksOpen '%s' '%s'".printf(dev.device, luks_name); + + log_debug(cmd); + Posix.system(cmd); + counter.stop(); + log_msg(""); + + // no need to show messages + } + else{ + + // use password to unlock + + var cmd = "echo -n -e '%s' | cryptsetup luksOpen --key-file - '%s' '%s'\n".printf( + luks_pass, dev.device, luks_name); + + log_debug(cmd.replace(luks_pass, "**PASSWORD**")); + + int status = exec_script_sync(cmd, out std_out, out std_err, false, true); + + switch (status){ + case 512: // invalid passphrase + message = _("Wrong password"); + details = _("Failed to unlock device"); + show_message(message, details, true, show_on_success); + return null; + } + } + + // check if unlocked + dev.query_changes(); + if (dev.has_children){ + unlocked_device = dev.children[0]; + } + + + if (unlocked_device == null){ + message = _("Failed to unlock device"); + details = "%s: %s\n\n%s".printf(_("Device"), dev.device, std_err); + is_error = true; + } + else{ + message = _("Unlocked successfully"); + details = "%s: %s, %s: /dev/mapper/%s".printf(_("Device"), dev.device, _("Unlocked"), unlocked_device.mapped_name); + is_error = false; + } + + show_message(message, details, is_error, show_on_success); + return unlocked_device; + } + + public static Device luks_lock(Device dev, bool show_on_success){ + + // check if not on encrypted device + if (!dev.is_on_encrypted_partition){ + log_debug("Device is not encrypted: %s".printf(dev.device)); + return dev; + } + + var parent_device = dev.parent; + + var cmd = "cryptsetup luksClose %s".printf(dev.kname); + log_debug(cmd); + string std_out, std_err; + exec_script_sync(cmd, out std_out, out std_err, false, true); // prompt user if not admin + + parent_device.query_changes(); + + if (parent_device.has_children){ + string message = _("Failed to lock device"); + string details = "%s: %s\n\n%s".printf(_("Device"), dev.device, std_err); + bool is_error = true; + show_message(message, details, is_error, show_on_success); + } + else{ + string message = _("Locked successfully"); + string details = "%s: %s".printf(_("Locked"), parent_device.device); + bool is_error = false; + show_message(message, details, is_error, show_on_success); + } + + return parent_device; + + /*log_debug(cmd); + + if (bash_admin_shell != null){ + int status = bash_admin_shell.execute(cmd); + return (status == 0); + } + else{ + int status = exec_script_sync(cmd,null,null,false,true); + return (status == 0); + }*/ + } + + public static bool mount( + string dev_name_or_uuid, string mount_point, string mount_options = "", bool silent = false){ + + /* + * Mounts specified device at specified mount point. + * + * */ + + string cmd = ""; + string std_out; + string std_err; + int ret_val; + + // resolve device name and uuid ----------------------------- + + string device = ""; + string uuid = ""; + if (dev_name_or_uuid.has_prefix("/dev")){ + device = dev_name_or_uuid; + uuid = Device.get_uuid_by_name(dev_name_or_uuid); + } + else{ + uuid = dev_name_or_uuid; + device = "/dev/disk/by-uuid/%s".printf(uuid); + device = resolve_device_name(device); + } + + // check if already mounted -------------- + + var mps = Device.get_device_mount_points(dev_name_or_uuid); + + log_debug("------------------"); + log_debug("arg=%s, device=%s".printf(dev_name_or_uuid, device)); + foreach(var mp in mps){ + log_debug(mp.mount_point); + } + log_debug("------------------"); + + foreach(var mp in mps){ + if ((mp.mount_point == mount_point) && mp.mount_options.contains(mount_options)){ + if (!silent){ + var msg = "%s is mounted at: %s".printf(device, mount_point); + if (mp.mount_options.length > 0){ + msg += ", options: %s".printf(mp.mount_options); + } + log_msg(msg); + } + return true; + } + } + + dir_create(mount_point); + + // unmount if any other device is mounted + + unmount_path(mount_point); + + // mount the device ------------------- + + if (mount_options.length > 0){ + cmd = "mount -o %s \"%s\" \"%s\"".printf(mount_options, device, mount_point); + } + else{ + cmd = "mount \"%s\" \"%s\"".printf(device, mount_point); + } + + ret_val = exec_sync(cmd, out std_out, out std_err); + + if (ret_val != 0){ + log_error ("Failed to mount device '%s' at mount point '%s'".printf(device, mount_point)); + log_error (std_err); + return false; + } + else{ + if (!silent){ + Device dev = get_device_by_name(device); + log_msg ("Mounted '%s'%s at '%s'".printf( + (dev == null) ? device : dev.device_name_with_parent, + (mount_options.length > 0) ? " (%s)".printf(mount_options) : "", + mount_point)); + } + return true; + } + + // check if mounted successfully ------------------ + + /*mps = Device.get_device_mount_points(dev_name_or_uuid); + if (mps.contains(mount_point)){ + log_msg("Device '%s' is mounted at '%s'".printf(dev_name_or_uuid, mount_point)); + return true; + } + else{ + return false; + }*/ + } + + public static string automount_device( + string dev_name_or_uuid, string mount_options = "", string mount_prefix = "/mnt"){ + + /* Returns the mount point of specified device. + * If unmounted, mounts the device to /mnt/ and returns the mount point. + * */ + + // resolve device name and uuid ----------------------------- + + string device = ""; + string uuid = ""; + if (dev_name_or_uuid.has_prefix("/dev")){ + device = dev_name_or_uuid; + uuid = Device.get_uuid_by_name(dev_name_or_uuid); + } + else{ + uuid = dev_name_or_uuid; + device = "/dev/disk/by-uuid/%s".printf(uuid); + device = resolve_device_name(device); + } + + // check if already mounted and return mount point ------------- + + var list = Device.get_block_devices(); + var dev = find_device_in_list_by_uuid(list, uuid); + if (dev != null){ + return dev.mount_points[0].mount_point; + } + + // check and create mount point ------------------- + + string mount_point = "%s/%s".printf(mount_prefix, uuid); + + try{ + File file = File.new_for_path(mount_point); + if (!file.query_exists()){ + file.make_directory_with_parents(); + } + } + catch(Error e){ + log_error (e.message); + return ""; + } + + // mount the device and return mount_point -------------------- + + if (mount(uuid, mount_point, mount_options)){ + return mount_point; + } + else{ + return ""; + } + } + + public static bool unmount_path(string mount_point){ + + /* Recursively unmounts all devices at given mount_point and subdirectories + * */ + + string cmd = ""; + string std_out; + string std_err; + int ret_val; + + // check if mount point is in use + if (!Device.mount_point_in_use(mount_point)) { + return true; + } + + // try to unmount ------------------ + + try{ + + string cmd_unmount = "cat /proc/mounts | awk '{print $2}' | grep '%s' | sort -r | xargs umount".printf(mount_point); + + log_debug(_("Unmounting from") + ": '%s'".printf(mount_point)); + + //sync before unmount + cmd = "sync"; + Process.spawn_command_line_sync(cmd, out std_out, out std_err, out ret_val); + //ignore success/failure + + //unmount + ret_val = exec_script_sync(cmd_unmount, out std_out, out std_err); + + if (ret_val != 0){ + log_error (_("Failed to unmount")); + log_error (std_err); + } + } + catch(Error e){ + log_error (e.message); + return false; + } + + // check if mount point is in use + if (!Device.mount_point_in_use(mount_point)) { + return true; + } + else{ + return false; + } + } + + public static void show_message(string message, string details, bool is_error, bool show_on_success){ + + if (is_error){ + log_error(message); + log_error(details); + } + else if (show_on_success){ + log_msg(message); + log_msg(details); + } + else{ + log_debug(message); + log_debug(details); + } + } + + // description helpers + + public string full_name_with_alias{ + owned get{ + string text = device; + if (mapped_name.length > 0){ + text += " (%s)".printf(mapped_name); + } + return text; + } + } + + public string full_name_with_parent{ + owned get{ + return device_name_with_parent; + } + } + + public string short_name_with_alias{ + owned get{ + string text = kname; + if (mapped_name.length > 0){ + text += " (%s)".printf(mapped_name); + } + return text; + } + } + + public string short_name_with_parent{ + owned get{ + string text = kname; + + if (has_parent() && (parent.type == "part")){ + text += " (%s)".printf(pkname); + } + + return text; + } + } + + public string short_name_with_parent_and_label{ + owned get{ + string s = kname; + + if (has_parent() && (parent.type == "part")){ + s = "%s → %s".printf(pkname, kname); + } + + s += (label.length > 0) ? " (%s)".printf(label): ""; + + return s; + } + } + + public string device_name_with_parent{ + owned get{ + string text = device; + + if (has_parent() && (parent.type == "part")){ + text += " (%s)".printf(parent.kname); + } + + return text; + } + } + + public double used_percent{ + get{ + return (used_bytes * 100.0) / size_bytes; + } + } + + public string used_percent_text{ + owned get{ + return "%.0f%%".printf(used_percent); + } + } + + public string description(){ + return description_formatted().replace("","").replace("",""); + } + + public string description_formatted(){ + string s = ""; + + if (type == "disk"){ + s += "" + kname + " ~"; + if (vendor.length > 0){ + s += " " + vendor; + } + if (model.length > 0){ + s += " " + model; + } + if (size_bytes > 0) { + s += " (%s)".printf(format_file_size(size_bytes, false, "", true, 0)); + } + } + else{ + s += "" + short_name_with_parent + "" ; + s += (label.length > 0) ? " (%s)".printf(label): ""; + s += (fstype.length > 0) ? " ~ " + fstype : ""; + if (size_bytes > 0) { + s += " (%s)".printf(format_file_size(size_bytes, false, "", true, 0)); + } + } + + return s.strip(); + } + + public string description_simple(bool show_device_file = true){ + + string s = ""; + + if (type == "disk"){ + if (vendor.length > 0){ + s += " " + vendor; + } + if (model.length > 0){ + s += " " + model; + } + if (size_bytes > 0) { + if (s.strip().length == 0){ + s += "%s Device".printf(format_file_size(size_bytes, false, "", true, 0)); + } + else{ + s += " (%s)".printf(format_file_size(size_bytes, false, "", true, 0)); + } + } + if (show_device_file && (device.length > 0)){ + s += " ~ %s".printf(device); + } + } + else{ + s += short_name_with_parent; + s += (label.length > 0) ? " (" + label + ")": ""; + s += (fstype.length > 0) ? " ~ " + fstype : ""; + if (size_bytes > 0) { + s += " (%s)".printf(format_file_size(size_bytes, false, "", true, 0)); + } + } + + return s.strip(); + } + + public string description_simple_formatted(){ + + string s = ""; + + if (type == "disk"){ + if (vendor.length > 0){ + s += " " + vendor; + } + if (model.length > 0){ + s += " " + model; + } + if (size_bytes > 0) { + if (s.strip().length == 0){ + s += "%s Device".printf(format_file_size(size_bytes, false, "", true, 0)); + } + else{ + s += " (%s)".printf(format_file_size(size_bytes, false, "", true, 0)); + } + } + } + else{ + s += "" + short_name_with_parent + "" ; + s += (label.length > 0) ? " (" + label + ")": ""; + s += (fstype.length > 0) ? " ~ " + fstype : ""; + if (size_bytes > 0) { + s += " (%s)".printf(format_file_size(size_bytes, false, "", true, 0)); + } + } + + return s.strip(); + } + + public string description_full_free(){ + string s = ""; + + if (type == "disk"){ + s += "%s %s".printf(model, vendor).strip(); + if (s.length == 0){ + s = "%s Disk".printf(format_file_size(size_bytes)); + } + else{ + s += " (%s Disk)".printf(format_file_size(size_bytes)); + } + } + else{ + s += kname; + if (label.length > 0){ + s += " (%s)".printf(label); + } + if (fstype.length > 0){ + s += " ~ %s".printf(fstype); + } + if (free_bytes > 0){ + s += " ~ %s".printf(description_free()); + } + } + + return s; + } + + public string description_full(){ + string s = ""; + s += device; + s += (label.length > 0) ? " (" + label + ")": ""; + s += (uuid.length > 0) ? " ~ " + uuid : ""; + s += (fstype.length > 0) ? " ~ " + fstype : ""; + s += (used_bytes > 0) ? " ~ " + used_formatted + " / " + size_formatted + " used (" + used_percent_text + ")" : ""; + + return s; + } + + public string description_usage(){ + if (used_bytes > 0){ + return used_formatted + " / " + size_formatted + " used (" + used_percent_text + ")"; + } + else{ + return ""; + } + } + + public string description_free(){ + if (used_bytes > 0){ + return format_file_size(free_bytes, false, "g", false) + + " / " + format_file_size(size_bytes, false, "g", true) + " free"; + } + else{ + return ""; + } + } + + public string tooltip_text(){ + string tt = ""; + + if (type == "disk"){ + tt += "%-15s: %s\n".printf(_("Device"), device); + tt += "%-15s: %s\n".printf(_("Vendor"), vendor); + tt += "%-15s: %s\n".printf(_("Model"), model); + tt += "%-15s: %s\n".printf(_("Serial"), serial); + tt += "%-15s: %s\n".printf(_("Revision"), revision); + + tt += "%-15s: %s\n".printf( _("Size"), + (size_bytes > 0) ? format_file_size(size_bytes) : "N/A"); + } + else{ + tt += "%-15s: %s\n".printf(_("Device"), + (mapped_name.length > 0) ? "%s → %s".printf(device, mapped_name) : device); + + if (has_parent()){ + tt += "%-15s: %s\n".printf(_("Parent Device"), parent.device); + } + tt += "%-15s: %s\n".printf(_("UUID"),uuid); + tt += "%-15s: %s\n".printf(_("Type"),type); + tt += "%-15s: %s\n".printf(_("Filesystem"),fstype); + tt += "%-15s: %s\n".printf(_("Label"),label); + + tt += "%-15s: %s\n".printf(_("Size"), + (size_bytes > 0) ? format_file_size(size_bytes) : "N/A"); + + tt += "%-15s: %s\n".printf(_("Used"), + (used_bytes > 0) ? format_file_size(used_bytes) : "N/A"); + + tt += "%-15s: %s\n".printf(_("System"),dist_info); + } + + return "%s".printf(tt); + } + + // testing ----------------------------------- + + public static void test_all(){ + var list = get_block_devices(); + log_msg("\n> get_block_devices()"); + print_device_list(list); + + log_msg(""); + + list = get_mounted_filesystems_using_mtab(); + log_msg("\n> get_mounted_filesystems_using_mtab()"); + print_device_mounts(list); + + log_msg(""); + + list = get_disk_space_using_df(); + log_msg("\n> get_disk_space_using_df()"); + print_device_disk_space(list); + + log_msg(""); + + list = get_block_devices(); + log_msg("\n> get_filesystems()"); + print_device_list(list); + print_device_mounts(list); + print_device_disk_space(list); + + log_msg(""); + } + + public static void print_device_list(Gee.ArrayList list = get_devices()){ + + log_debug(""); + + log_debug("%-15s %-10s %-10s %-10s %-10s %-10s".printf( + "device", + "pkname", + "kname", + "type", + "fstype", + "mapped" + )); + + log_debug(string.nfill(100, '-')); + + foreach(var dev in list){ + log_debug("%-15s %-10s %-10s %-10s %-10s %-10s".printf( + dev.device , + dev.pkname, + dev.kname, + dev.type, + dev.fstype, + dev.mapped_name + )); + } + + log_debug(""); + + print_device_relationships(list); + } + + public static void print_device_relationships(Gee.ArrayList list = get_devices()){ + + log_debug(""); + + log_debug(string.nfill(100, '-')); + + foreach(var dev in list){ + + if (dev.pkname.length == 0){ + + log_debug("%-10s".printf(dev.kname)); + + foreach(var child1 in dev.children){ + if (!child1.has_children){ + log_debug("%-10s -- %-10s".printf(dev.kname, child1.kname)); + } + else{ + foreach(var child2 in child1.children){ + log_debug("%-10s -- %-10s -- %-10s".printf(dev.kname, child1.kname, child2.kname)); + } + } + } + } + } + + log_debug(""); + } + + public static void print_device_mounts(Gee.ArrayList list = get_devices()){ + + stdout.printf("\n"); + stdout.printf(string.nfill(100, '-') + "\n"); + + foreach(var dev in list){ + stdout.printf("%-15s: %s\n".printf(dev.device, dev.mount_path)); + foreach(var mp in dev.mount_points){ + stdout.printf(" -> %s: %s\n".printf(mp.mount_point, mp.mount_options)); + } + } + + stdout.printf("\n"); + } + + public static void print_device_disk_space(Gee.ArrayList list = get_devices()){ + log_debug(""); + + log_debug("%-15s %-12s %15s %15s %15s %10s".printf( + "device", + "fstype", + "size", + "used", + "available", + "used_percent" + )); + + log_debug(string.nfill(100, '-')); + + foreach(var dev in list){ + log_debug("%-15s %-12s %15s %15s %15s %10s".printf( + dev.device, + dev.fstype, + format_file_size(dev.size_bytes, true), + format_file_size(dev.used_bytes, true), + format_file_size(dev.available_bytes, true), + dev.used_percent_text + )); + } + + log_debug(""); + } +} + +public class DeviceMonitor : GLib.Object{ + + private static DeviceMonitor? device_monitor; + private static GLib.VolumeMonitor? monitor; + private static uint tmr_init = 0; + + public signal void changed(); + + public signal void drive_changed (Drive drive); + public signal void drive_connected (Drive drive); + public signal void drive_disconnected (Drive drive); + //public signal void drive_eject_button (Drive drive) + //public signal void drive_stop_button (Drive drive) + public signal void mount_added (Mount mount); + public signal void mount_changed (Mount mount); + //public signal void mount_pre_unmount (Mount mount) + public signal void mount_removed (Mount mount); + public signal void volume_added (Volume volume); + public signal void volume_changed (Volume volume); + public signal void volume_removed (Volume volume); + + private DeviceMonitor(){ + + } + + public static DeviceMonitor get_monitor(){ + + if (device_monitor != null){ return device_monitor; } + + device_monitor = new DeviceMonitor(); + monitor = VolumeMonitor.get(); + + // drive changes ------------------------------- + + monitor.drive_connected.connect((drive) => { + print_drive (drive, "Drive connected"); + device_monitor.drive_connected(drive); + start_timer(); + }); + + monitor.drive_changed.connect((drive) => { + print_drive (drive, "Drive changed"); + device_monitor.drive_changed(drive); + start_timer(); + }); + + monitor.drive_disconnected.connect((drive) => { + print_drive (drive, "Drive disconnected"); + device_monitor.drive_disconnected(drive); + start_timer(); + }); + + // mount changes ----------------------------------- + + monitor.mount_added.connect((mount) => { + print_mount (mount, "Mount added"); + device_monitor.mount_added (mount); + start_timer(); + }); + + monitor.mount_changed.connect((mount) => { + print_mount (mount, "Mount changed"); + device_monitor.mount_changed (mount); + start_timer(); + }); + + monitor.mount_removed.connect((mount) => { + print_mount (mount, "Mount removed"); + device_monitor.mount_removed (mount); + start_timer(); + }); + + // mountable volume changes + + monitor.volume_added.connect((volume) => { + print_volume (volume, "Volume added"); + device_monitor.volume_added (volume); + start_timer(); + }); + + monitor.volume_changed.connect((volume) => { + print_volume (volume, "Volume changed"); + device_monitor.volume_changed (volume); + start_timer(); + }); + + monitor.volume_removed.connect((volume) => { + print_volume (volume, "Volume removed"); + device_monitor.volume_removed (volume); + start_timer(); + }); + + /*monitor.drive_connected.connect ((drive) => { + print_drive (drive, "Drive connected"); + + // Reject all newly connected drives: + drive.eject_with_operation.begin (MountUnmountFlags.FORCE, null, null, (obj, res) => { + try { + bool status = drive.eject_with_operation.end (res); + stdout.printf ("eject: %s: %s\n", drive.get_name (), status.to_string ()); + } catch (Error e) { + stdout.printf ("Error: %s\n", e.message); + } + }); + });*/ + + + return device_monitor; + } + + private static void start_timer(){ + if (tmr_init > 0){ + Source.remove(tmr_init); + tmr_init = 0; + } + tmr_init = Timeout.add(500, init_delayed); + } + + private static bool init_delayed(){ + + if (tmr_init > 0){ + Source.remove(tmr_init); + tmr_init = 0; + } + + device_monitor.changed(); + + return false; + } + + private static void print_drive (Drive drive, string title) { + + stdout.printf ("\n"); + stdout.printf ("%s:\n", title); + stdout.printf (" name: %s\n", drive.get_name ()); + stdout.printf (" can-eject: %s\n", drive.can_eject ().to_string ()); + stdout.printf (" can-poll-for-media: %s\n", drive.can_poll_for_media ().to_string ()); + stdout.printf (" can-start: %s\n", drive.can_start ().to_string ()); + stdout.printf (" can-start-degraded: %s\n", drive.can_start_degraded ().to_string ()); + stdout.printf (" can-stop: %s\n", drive.can_stop ().to_string ()); + stdout.printf (" has-volumes: %s\n", drive.has_volumes ().to_string ()); + stdout.printf (" has-media: %s\n", drive.has_media ().to_string ()); + stdout.printf (" is-media-check-automatic: %s\n", drive.is_media_check_automatic ().to_string ()); + stdout.printf (" is-media-removable: %s\n", drive.is_media_removable ().to_string ()); + stdout.printf (" start-stop-type: %s\n", drive.get_start_stop_type ().to_string ()); + + string[] kinds = drive.enumerate_identifiers (); + foreach (unowned string kind in kinds) { + stdout.printf (" %s = %s\n", kind, drive.get_identifier (kind)); + } + stdout.printf ("\n"); + } + + private static void print_mount (Mount mount, string title) { + + stdout.printf ("\n"); + stdout.printf ("%s:\n", title); + stdout.printf (" name: %s\n", mount.get_name ()); + stdout.printf (" uuid: %s\n", mount.get_uuid ()); + stdout.printf (" can-eject: %s\n", mount.can_eject ().to_string ()); + stdout.printf (" can-unmount: %s\n", mount.can_unmount ().to_string ()); + stdout.printf (" is-shadowed: %s\n", mount.is_shadowed ().to_string ()); + stdout.printf (" default-location: %s\n", mount.get_default_location ().get_path ()); + stdout.printf (" icon: %s\n", mount.get_icon ().to_string ()); + stdout.printf (" root: %s\n", mount.get_root ().get_path ()); + + try { + string[] types = mount.guess_content_type_sync (false); + stdout.printf (" guess-content-type:\n"); + foreach (unowned string type in types) { + stdout.printf (" %s\n", type); + } + } catch (Error e) { + stdout.printf ("Error: %s\n", e.message); + } + stdout.printf ("\n"); + } + + private static void print_volume (Volume volume, string title) { + + stdout.printf ("\n"); + stdout.printf ("%s:\n", title); + stdout.printf (" name: %s\n", volume.get_name ()); + stdout.printf (" can-eject: %s\n", volume.can_eject ().to_string ()); + stdout.printf (" can-mount: %s\n", volume.can_mount ().to_string ()); + + string[] kinds = volume.enumerate_identifiers (); + foreach (unowned string kind in kinds) { + stdout.printf (" %s = %s\n", kind, volume.get_identifier (kind)); + } + stdout.printf ("\n"); + } + + public static List get_mounts(){ + return monitor.get_mounts(); + } +} + + + + + + diff --git a/src/Utility/Console/MountEntry.vala b/src/Utility/Console/MountEntry.vala new file mode 100644 index 0000000..8abf388 --- /dev/null +++ b/src/Utility/Console/MountEntry.vala @@ -0,0 +1,46 @@ +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.ProcessHelper; +using TeeJee.System; +using TeeJee.Misc; + +public class MountEntry : GLib.Object{ + public Device device = null; + public string mount_point = ""; + public string mount_options = ""; + + public MountEntry(Device? device, string mount_point, string mount_options){ + this.device = device; + this.mount_point = mount_point; + this.mount_options = mount_options; + } + + public string subvolume_name(){ + if (mount_options.contains("subvol=")){ + return mount_options.split("subvol=")[1].split(",")[0].strip(); + } + else{ + return ""; + } + } + + public string lvm_name(){ + if ((device != null) && (device.type == "lvm") && (device.mapped_name.length > 0)){ + return device.mapped_name.strip(); + } + else{ + return ""; + } + } + + public static MountEntry? find_entry_by_mount_point( + Gee.ArrayList entries, string mount_path){ + + foreach(var entry in entries){ + if (entry.mount_point == mount_path){ + return entry; + } + } + return null; + } +} diff --git a/src/Utility/Console/TeeJee.FileSystem.vala b/src/Utility/Console/TeeJee.FileSystem.vala new file mode 100644 index 0000000..918873e --- /dev/null +++ b/src/Utility/Console/TeeJee.FileSystem.vala @@ -0,0 +1,1095 @@ + +/* + * TeeJee.FileSystem.vala + * + * Copyright 2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +namespace TeeJee.FileSystem{ + + /* Convenience functions for handling files and directories */ + + using TeeJee.Logging; + using TeeJee.ProcessHelper; + using TeeJee.Misc; + + public const int64 KB = 1000; + public const int64 MB = 1000 * KB; + public const int64 GB = 1000 * MB; + public const int64 TB = 1000 * GB; + public const int64 KiB = 1024; + public const int64 MiB = 1024 * KiB; + public const int64 GiB = 1024 * MiB; + public const int64 TiB = 1024 * GiB; + + // path helpers ---------------------------- + + public string file_parent(string file_path){ + + string text = ""; + var arr = file_path.split("/"); + int index = 0; + + while (index < arr.length - 1){ + + if (index == 0){ + // append first part without / prefix + // appends empty string in case of /path/file and non-empty string in case of path/file + text += "%s".printf(arr[index++]); + continue; + } + + text += "/%s".printf(arr[index++]); + } + + if (text.length == 0){ + // parent for /path + text = "/"; + } + + return text; + + //return File.new_for_path(file_path).get_parent().get_path(); + } + + public string file_basename(string file_path){ + + var arr = file_path.split("/"); + + if (arr.length == 1){ + return file_path; + } + else{ + return arr[arr.length - 1]; + } + + //return File.new_for_path(file_path).get_basename(); + } + + public string file_get_title(string file_path){ + + string file_name = file_basename(file_path); + + int end = file_name.length - file_get_extension(file_path).length; + return file_name[0:end]; + } + + public string file_get_extension(string file_path){ + + string file_name = file_basename(file_path); + + string[] parts = file_name.split("."); + + if (parts.length == 1){ + // no extension + return ""; + } + + if (parts.length > 2){ + + string ext1 = parts[parts.length-2]; + string ext2 = parts[parts.length-1]; + + if ((ext1.length <= 4) && (ext2.length <= 4) && (ext1 == "tar")){ + // 2-part extension + return ".%s.%s".printf(parts[parts.length-2], parts[parts.length-1]); + } + } + + if (parts.length > 1){ + return ".%s".printf(parts[parts.length - 1]); + } + + return ""; + } + + + public string path_combine(string part1, string part2){ + return GLib.Path.build_path("/", part1, part2); + } + + public string remove_trailing_slash(string path){ + if (path.has_suffix("/")){ + return path[0:path.length - 1]; + } + else{ + return path; + } + } + + // file helpers ----------------------------- + + public bool file_or_dir_exists(string item_path){ + + /* check if item exists on disk*/ + + var item = File.new_for_path(item_path); + return item.query_exists(); + } + + public bool uri_exists(string uri){ + + /* check if resource exists at uri */ + + //log_debug("uri: %s".printf(uri)); + + var item = File.new_for_uri(uri); + return item.query_exists(); + } + + public bool file_exists (string file_path){ + /* Check if file exists */ + return (FileUtils.test(file_path, GLib.FileTest.EXISTS) + && !FileUtils.test(file_path, GLib.FileTest.IS_DIR)); + } + + public bool file_exists_regular (string file_path){ + /* Check if file exists */ + return ( FileUtils.test(file_path, GLib.FileTest.EXISTS) + && FileUtils.test(file_path, GLib.FileTest.IS_REGULAR)); + } + + public bool file_delete(string file_path){ + + /* Check and delete file */ + + try { + var file = File.new_for_path (file_path); + if (file.query_exists ()) { + file.delete (); + } + return true; + } catch (Error e) { + log_error (e.message); + log_error(_("Failed to delete file") + ": %s".printf(file_path)); + return false; + } + } + + public bool file_move_to_trash(string file_path){ + + /* Check and delete file */ + + var file = File.new_for_path (file_path); + if (file.query_exists ()) { + Posix.system("gvfs-trash '%s'".printf(escape_single_quote(file_path))); + } + return true; + } + + public bool file_shred(string file_path){ + + /* Check and delete file */ + + var file = File.new_for_path (file_path); + if (file.query_exists ()) { + Posix.system("shred -u '%s'".printf(escape_single_quote(file_path))); + } + return true; + } + + public int64 file_line_count (string file_path){ + /* Count number of lines in text file */ + string cmd = "wc -l '%s'".printf(escape_single_quote(file_path)); + string std_out, std_err; + exec_sync(cmd, out std_out, out std_err); + return long.parse(std_out.split("\t")[0]); + } + + public string? file_read (string file_path){ + + /* Reads text from file */ + + string txt; + size_t size; + + try{ + GLib.FileUtils.get_contents (file_path, out txt, out size); + return txt; + } + catch (Error e){ + log_error (e.message); + log_error(_("Failed to read file") + ": %s".printf(file_path)); + } + + return null; + } + + public bool file_write (string file_path, string contents, bool overwrite_in_place = false){ + + /* Write text to file */ + + try{ + + dir_create(file_parent(file_path)); + + var file = File.new_for_path (file_path); + + if (file.query_exists() && overwrite_in_place){ + + var iostream = file.open_readwrite(); + //int64 fsize = iostream.query_info("%s".printf(FileAttribute.STANDARD_SIZE)).get_size(); + //iostream.seek (0, GLib.SeekType.END); + iostream.truncate_fn(0); + //iostream.seek (0, GLib.SeekType.SET); + var ostream = iostream.output_stream; + var data_stream = new DataOutputStream(ostream); + data_stream.put_string(contents); + data_stream.close(); + } + else{ + + if (file.query_exists()) { + file.delete(); + } + + var file_stream = file.create (FileCreateFlags.REPLACE_DESTINATION); + var data_stream = new DataOutputStream (file_stream); + data_stream.put_string (contents); + data_stream.close(); + } + + return true; + } + catch (Error e) { + log_error(e.message); + return false; + } + } + + public bool file_copy (string src_file, string dest_file){ + try{ + var file_src = File.new_for_path (src_file); + if (file_src.query_exists()) { + var file_dest = File.new_for_path (dest_file); + file_src.copy(file_dest,FileCopyFlags.OVERWRITE,null,null); + return true; + } + } + catch(Error e){ + log_error (e.message); + log_error(_("Failed to copy file") + ": '%s', '%s'".printf(src_file, dest_file)); + } + + return false; + } + + public bool file_move (string src_file, string dest_file){ + try{ + var file_src = File.new_for_path (src_file); + if (file_src.query_exists()) { + var file_dest = File.new_for_path (dest_file); + file_src.move(file_dest,FileCopyFlags.OVERWRITE,null,null); + return true; + } + else{ + log_error(_("File not found") + ": '%s'".printf(src_file)); + return false; + } + } + catch(Error e){ + log_error (e.message); + log_error(_("Failed to move file") + ": '%s', '%s'".printf(src_file, dest_file)); + return false; + } + } + + public bool file_gzip (string src_file){ + + string dst_file = src_file + ".gz"; + file_delete(dst_file); + + string cmd = "gzip '%s'".printf(escape_single_quote(src_file)); + string std_out, std_err; + exec_sync(cmd, out std_out, out std_err); + + return file_exists(dst_file); + } + + public bool file_gunzip (string src_file){ + + string dst_file = src_file; + file_delete(dst_file); + + string cmd = "gunzip '%s'".printf(escape_single_quote(src_file)); + string std_out, std_err; + exec_sync(cmd, out std_out, out std_err); + + return file_exists(dst_file); + } + + public string file_checksum(string file_path, GLib.ChecksumType checksum_type = ChecksumType.MD5){ + + var checksum = new Checksum (ChecksumType.MD5); + + if (!file_exists(file_path)){ + return ""; + } + + FileStream stream = FileStream.open(file_path, "rb"); + uint8 fbuf[100]; + size_t size; + + while ((size = stream.read (fbuf)) > 0) { + checksum.update (fbuf, size); + } + + unowned string digest = checksum.get_string (); + return digest; + } + + public bool file_rename(string file_path, string new_file_name){ + + if (!file_or_dir_exists(file_path)){ return true; } + + string src = file_path; + string dst = path_combine(file_parent(file_path), new_file_name); + string cmd = "mv '%s' '%s'".printf(escape_single_quote(src), escape_single_quote(dst)); + log_debug(cmd); + + string std_out, std_err; + int status = exec_sync(cmd, out std_out, out std_err); + if (status != 0){ + log_error(std_err); + return false; + } + + return true; + } + + public string file_generate_unique_name(string file_path){ + + string title = file_get_title(file_path); + string extension = file_get_extension(file_path); + string location = file_parent(file_path); + + string outpath = file_path; + + int index = 1; + while (file_or_dir_exists(outpath)){ + string new_name = "%s%s%s".printf(title, " (%d)".printf(index++), extension); + outpath = path_combine(location, new_name); + } + + return outpath; + } + + public bool file_create_symlink(string file_path, string symlink_file_path, bool make_relative){ + + /* make_relative = null, decide automatically + * make_relative = true, force relative path + * make_relative = false, force absolute path + * */ + + if (!file_or_dir_exists(file_path)){ return true; } + + string src = file_path; + string dst = symlink_file_path; + + if (make_relative){ + + string[] list_src = src.split("/"); + string[] list_dst = dst.split("/"); + string relative_path = ""; + int mismatch_index = -1; + int parent_prefix_count = 0; + + for(int i = 0; i < list_dst.length - 1; i++){ // till n-1 (skip file name part) + + if (list_dst[i] == list_src[i]){ + // ignore matching prefix + } + else{ + if (mismatch_index == -1){ + mismatch_index = i; // save first mismatched part index + } + + // start appending "../" till file name + relative_path += "../"; + parent_prefix_count++; + } + } + + // append path starting from mismatched part and ending at source file directory + for(int i = mismatch_index; i < list_src.length - 1; i++){ + relative_path += "%s/".printf(list_src[i]); + } + + // append source file name + relative_path += file_basename(src); + + if (make_relative == true){ + src = relative_path; + } + else{ //make_relative == null + if (parent_prefix_count < 3){ + src = relative_path; + } + } + + /* Logic: + + file: /usr/share/icons/menta/48/folder.ico + sym: /usr/share/icons/menta/64/folder.ico -> ../48/folder.ico + + file: /usr/share/themes/adwaita/icons/48/folder.ico + sym: /usr/share/icons/menta/64/folder.ico -> ../../../themes/adwaita/48/folder.ico + */ + } + + string cmd = "ln -s '%s' '%s'".printf(escape_single_quote(src), escape_single_quote(dst)); + log_debug(cmd); + + string std_out, std_err; + int status = exec_sync(cmd, out std_out, out std_err); + if (status != 0){ + log_error(std_err); + return false; + } + + return true; + } + + public bool file_create_hardlink(string file_path, string symlink_file_path){ + + if (!file_or_dir_exists(file_path)){ return true; } + + string src = file_path; + string dst = symlink_file_path; + + string cmd = "ln -f '%s' '%s'".printf(escape_single_quote(src), escape_single_quote(dst)); + log_debug(cmd); + + string std_out, std_err; + int status = exec_sync(cmd, out std_out, out std_err); + if (status != 0){ + log_error(std_err); + return false; + } + + return true; + } + + public string string_checksum(string text, GLib.ChecksumType checksum_type = ChecksumType.MD5){ + return GLib.Checksum.compute_for_string(checksum_type, text); + } + + public string file_resolve_executable_path(string file_path){ + + if (file_path.has_prefix("/")){ + return file_path; + } + else if (!file_path.contains("/")){ + return GLib.Environment.find_program_in_path(file_path); + } + else if (file_path.has_prefix("./")){ + return path_combine(GLib.Environment.get_current_dir(), file_path[2:file_path.length]); + } + else if (file_path.has_prefix("../")){ + return path_combine(file_parent(GLib.Environment.get_current_dir()), file_path[3:file_path.length]); + } + else { + return path_combine(GLib.Environment.get_current_dir(), file_path); + } + } + + // file info ----------------- + + public int64 file_get_size(string file_path){ + try{ + File file = File.parse_name (file_path); + if (FileUtils.test(file_path, GLib.FileTest.EXISTS)){ + if (FileUtils.test(file_path, GLib.FileTest.IS_REGULAR) + && !FileUtils.test(file_path, GLib.FileTest.IS_SYMLINK)){ + return file.query_info("standard::size",0).get_size(); + } + } + } + catch(Error e){ + log_error (e.message); + } + + return -1; + } + + public DateTime file_get_modified_date(string file_path){ + try{ + FileInfo info; + File file = File.parse_name (file_path); + if (file.query_exists()) { + info = file.query_info("%s".printf(FileAttribute.TIME_MODIFIED), 0); + return (new DateTime.from_timeval_utc(info.get_modification_time())).to_local(); + } + } + catch (Error e) { + log_error (e.message); + } + + return (new DateTime.from_unix_utc(0)); //1970 + } + + public string file_get_symlink_target(string file_path){ + try{ + FileInfo info; + File file = File.parse_name (file_path); + if (file.query_exists()) { + info = file.query_info("%s".printf(FileAttribute.STANDARD_SYMLINK_TARGET), 0); + return info.get_symlink_target(); + } + } + catch (Error e) { + log_error (e.message); + } + + return ""; + } + + // directory helpers ---------------------- + + public bool dir_exists (string dir_path){ + + return ( FileUtils.test(dir_path, GLib.FileTest.EXISTS) && FileUtils.test(dir_path, GLib.FileTest.IS_DIR)); + + /*try{ + var dir = File.parse_name(dir_path); + + if (dir.query_exists()) { + + var info = dir.query_info("%s".printf(FileAttribute.STANDARD_TYPE), 0); // follows symlinks + + var file_type = info.get_file_type(); + + return (file_type == FileType.DIRECTORY); + } + else{ + log_debug("!exists: " + dir_path); + } + } + catch (Error e) { + log_error (e.message); + } + + return false;*/ + } + + public bool dir_create (string dir_path, bool show_message = false){ + + /* Creates a directory along with parents */ + + try{ + var dir = File.parse_name (dir_path); + if (dir.query_exists () == false) { + dir.make_directory_with_parents (null); + if (show_message){ + log_msg(_("Created directory") + ": %s".printf(dir_path)); + } + } + return dir.query_exists(); + } + catch (Error e) { + log_error (e.message); + log_error(_("Failed to create dir") + ": %s".printf(dir_path)); + return false; + } + } + + public bool dir_delete (string dir_path, bool show_message = false){ + + /* Recursively deletes directory along with contents */ + + if (!dir_exists(dir_path)){ return true; } + + string cmd = "rm -rf"; + + if (show_message){ + cmd += "v"; + } + + cmd += " '%s'".printf(escape_single_quote(dir_path)); + + int status = Posix.system(cmd); + return (status == 0); + } + + public bool dir_move_to_trash (string dir_path){ + return file_move_to_trash(dir_path); + } + + public bool dir_is_empty (string dir_path){ + + /* Check if directory is empty */ + + try{ + bool is_empty = true; + var dir = File.parse_name (dir_path); + if (dir.query_exists()) { + FileInfo info; + var enu = dir.enumerate_children ("%s".printf(FileAttribute.STANDARD_NAME), 0); + while ((info = enu.next_file()) != null) { + is_empty = false; + break; + } + } + return is_empty; + } + catch (Error e) { + log_error (e.message); + return false; + } + } + + public bool filesystem_supports_hardlinks(string path, out bool is_readonly){ + bool supports_hardlinks = false; + is_readonly = false; + + var test_file = path_combine(path, random_string() + "~"); + + if (file_write(test_file,"")){ + + var test_file2 = path_combine(path, random_string() + "~"); + + var cmd = "ln '%s' '%s'".printf( + escape_single_quote(test_file), + escape_single_quote(test_file2)); + + log_debug(cmd); + + string std_out, std_err; + int status = exec_sync(cmd, out std_out, out std_err); + + cmd = "stat --printf '%%h' '%s'".printf( + escape_single_quote(test_file)); + + log_debug(cmd); + + status = exec_sync(cmd, out std_out, out std_err); + log_debug("stdout: %s".printf(std_out)); + + int64 count = 0; + if (int64.try_parse(std_out, out count)){ + if (count > 1){ + supports_hardlinks = true; + } + } + + file_delete(test_file2); // delete if exists + file_delete(test_file); + } + else{ + is_readonly = true; + } + + return supports_hardlinks; + } + + public Gee.ArrayList dir_list_names(string path, bool full_path){ + + var list = new Gee.ArrayList(); + + try + { + File f_path = File.new_for_path (path); + + if (!f_path.query_exists()){ return list; } + + FileEnumerator enumerator = f_path.enumerate_children ("%s".printf(FileAttribute.STANDARD_NAME), 0); + FileInfo file; + while ((file = enumerator.next_file ()) != null) { + string name = file.get_name(); + + if (full_path){ + list.add(path_combine(path, name)); + } + else{ + list.add(name); + } + } + } + catch (Error e) { + log_error (e.message); + } + + //sort the list + CompareDataFunc entry_compare = (a, b) => { + return strcmp(a,b); + }; + list.sort((owned) entry_compare); + + return list; + } + + public bool dir_tar (string src_dir, string tar_file, bool recursion = true){ + if (dir_exists(src_dir)) { + + if (file_exists(tar_file)){ + file_delete(tar_file); + } + + var src_parent = file_parent(src_dir); + var src_name = file_basename(src_dir); + + string cmd = "tar cvf '%s' --overwrite --%srecursion -C '%s' '%s'\n".printf( + escape_single_quote(tar_file), + (recursion ? "" : "no-"), + escape_single_quote(src_parent), + escape_single_quote(src_name)); + + log_debug(cmd); + + string stdout, stderr; + int status = exec_script_sync(cmd, out stdout, out stderr); + if (status == 0){ + return true; + } + else{ + log_msg(stderr); + } + } + else{ + log_error(_("Dir not found") + ": %s".printf(src_dir)); + } + + return false; + } + + public bool dir_untar (string tar_file, string dst_dir){ + if (file_exists(tar_file)) { + + if (!dir_exists(dst_dir)){ + dir_create(dst_dir); + } + + string cmd = "tar xvf '%s' --overwrite --same-permissions -C '%s'\n".printf( + escape_single_quote(tar_file), + escape_single_quote(dst_dir)); + + log_debug(cmd); + + string stdout, stderr; + int status = exec_script_sync(cmd, out stdout, out stderr); + if (status == 0){ + return true; + } + else{ + log_msg(stderr); + } + } + else{ + log_error(_("File not found") + ": %s".printf(tar_file)); + } + + return false; + } + + public bool chown(string dir_path, string user_name, string group){ + string cmd = "chown %s:%s -R '%s'".printf(user_name, group, escape_single_quote(dir_path)); + log_debug("cmd: %s".printf(cmd)); + int status = exec_sync(cmd, null, null); + return (status == 0); + } + + // dir info ------------------- + + // dep: find wc TODO: rewrite + public long dir_count(string path){ + + long count = 0; + + try + { + File file = File.new_for_path (path); + FileInfo info; + FileEnumerator enumerator = file.enumerate_children ("%s".printf(FileAttribute.STANDARD_NAME), 0); + while ((info = enumerator.next_file()) != null) { + count++; + } + } + catch (Error e) { + log_error (e.message); + } + + return count; + } + + // dep: du + public long dir_size(string path){ + + /* Returns size of files and directories in KB*/ + + string cmd = "du -s -b '%s'".printf(escape_single_quote(path)); + string std_out, std_err; + exec_sync(cmd, out std_out, out std_err); + return long.parse(std_out.split("\t")[0]); + } + + // dep: du + public long dir_size_kb(string path){ + + /* Returns size of files and directories in KB*/ + + return (long)(dir_size(path) / 1024.0); + } + + // archiving and encryption ---------------- + + // dep: tar gzip gpg + public bool file_tar_encrypt (string src_file, string dst_file, string password){ + if (file_exists(src_file)) { + if (file_exists(dst_file)){ + file_delete(dst_file); + } + + var src_dir = file_parent(src_file); + var src_name = file_basename(src_file); + + var dst_dir = file_parent(dst_file); + var dst_name = file_basename(dst_file); + var tar_name = dst_name[0 : dst_name.index_of(".gpg")]; + var tar_file = "%s/%s".printf(dst_dir, tar_name); + + string cmd = "tar cvf '%s' --overwrite -C '%s' '%s'\n".printf( + escape_single_quote(tar_file), + escape_single_quote(src_dir), + escape_single_quote(src_name)); + + cmd += "gpg --passphrase '%s' -o '%s' --symmetric '%s'\n".printf( + password, + escape_single_quote(dst_file), + escape_single_quote(tar_file)); + + cmd += "rm -f '%s'\n".printf(escape_single_quote(tar_file)); + + log_debug(cmd); + + string stdout, stderr; + int status = exec_script_sync(cmd, out stdout, out stderr); + if (status == 0){ + return true; + } + else{ + log_msg(stderr); + } + } + + return false; + } + + // dep: tar gzip gpg + public string file_decrypt_untar_read (string src_file, string password){ + + if (file_exists(src_file)) { + + //var src_name = file_basename(src_file); + //var tar_name = src_name[0 : src_name.index_of(".gpg")]; + //var tar_file = "%s/%s".printf(TEMP_DIR, tar_name); + //var temp_file = "%s/%s".printf(TEMP_DIR, random_string()); + + string cmd = ""; + + cmd += "gpg --quiet --no-verbose --passphrase '%s' -o- --decrypt '%s'".printf( + password, + escape_single_quote(src_file)); + + cmd += " | tar xf - --to-stdout 2>/dev/null\n"; + cmd += "exit $?\n"; + + log_debug(cmd); + + string std_out, std_err; + int status = exec_script_sync(cmd, out std_out, out std_err); + if (status == 0){ + return std_out; + } + else{ + log_error(std_err); + return ""; + } + } + else{ + log_error(_("File is missing") + ": %s".printf(src_file)); + } + + return ""; + } + + // dep: tar gzip gpg + public bool decrypt_and_untar (string src_file, string dst_file, string password){ + if (file_exists(src_file)) { + if (file_exists(dst_file)){ + file_delete(dst_file); + } + + var src_dir = file_parent(src_file); + var src_name = file_basename(src_file); + var tar_name = src_name[0 : src_name.index_of(".gpg")]; + var tar_file = "%s/%s".printf(src_dir, tar_name); + + string cmd = ""; + + // gpg cannot overwrite - remove tar file if it exists + cmd += "rm -f '%s'\n".printf(escape_single_quote(tar_file)); + + cmd += "gpg --passphrase '%s' -o '%s' --decrypt '%s'\n".printf( + password, + escape_single_quote(tar_file), + escape_single_quote(src_file)); + + cmd += "status=$?; if [ $status -ne 0 ]; then exit $status; fi\n"; + + cmd += "tar xvf '%s' --overwrite --same-permissions -C '%s'\n".printf( + escape_single_quote(tar_file), + escape_single_quote(file_parent(dst_file))); + + cmd += "rm -f '%s'\n".printf(escape_single_quote(tar_file)); + + log_debug(cmd); + + string stdout, stderr; + int status = exec_script_sync(cmd, out stdout, out stderr); + if (status == 0){ + return true; + } + else{ + log_error(stderr); + return false; + } + } + else{ + log_error(_("File is missing") + ": %s".printf(src_file)); + } + + return false; + } + + // hashing ----------- + + public string hash_md5(string path){ + Checksum checksum = new Checksum (ChecksumType.MD5); + FileStream stream = FileStream.open (path, "rb"); + + uint8 fbuf[100]; + size_t size; + while ((size = stream.read (fbuf)) > 0){ + checksum.update (fbuf, size); + } + + unowned string digest = checksum.get_string(); + + return digest; + } + + // misc -------------------- + + public string format_file_size ( + uint64 size, bool binary_units = false, + string unit = "", bool show_units = true, int decimals = 1){ + + int64 unit_k = binary_units ? 1024 : 1000; + int64 unit_m = binary_units ? 1024 * unit_k : 1000 * unit_k; + int64 unit_g = binary_units ? 1024 * unit_m : 1000 * unit_m; + int64 unit_t = binary_units ? 1024 * unit_g : 1000 * unit_g; + + string txt = ""; + + if ((size > unit_t) && ((unit.length == 0) || (unit == "t"))){ + txt += ("%%'0.%df".printf(decimals)).printf(size / (1.0 * unit_t)); + if (show_units){ + txt += " %sB".printf(binary_units ? "Ti" : "T"); + } + } + else if ((size > unit_g) && ((unit.length == 0) || (unit == "g"))){ + txt += ("%%'0.%df".printf(decimals)).printf(size / (1.0 * unit_g)); + if (show_units){ + txt += " %sB".printf(binary_units ? "Gi" : "G"); + } + } + else if ((size > unit_m) && ((unit.length == 0) || (unit == "m"))){ + txt += ("%%'0.%df".printf(decimals)).printf(size / (1.0 * unit_m)); + if (show_units){ + txt += " %sB".printf(binary_units ? "Mi" : "M"); + } + } + else if ((size > unit_k) && ((unit.length == 0) || (unit == "k"))){ + txt += ("%%'0.%df".printf(decimals)).printf(size / (1.0 * unit_k)); + if (show_units){ + txt += " %sB".printf(binary_units ? "Ki" : "K"); + } + } + else{ + txt += "%'0lld".printf(size); + if (show_units){ + txt += " B"; + } + } + + return txt; + } + + public string escape_single_quote(string file_path){ + return file_path.replace("'","'\\''"); + } + + + // dep: chmod + public int chmod (string file, string permission){ + + /* Change file permissions */ + string cmd = "chmod %s '%s'".printf(permission, escape_single_quote(file)); + return exec_sync (cmd, null, null); + } + + // dep: realpath + public string resolve_relative_path (string filePath){ + + /* Resolve the full path of given file using 'realpath' command */ + + string filePath2 = filePath; + if (filePath2.has_prefix ("~")){ + filePath2 = Environment.get_home_dir () + "/" + filePath2[2:filePath2.length]; + } + + try { + string output = ""; + string cmd = "realpath '%s'".printf(escape_single_quote(filePath2)); + Process.spawn_command_line_sync(cmd, out output); + output = output.strip (); + if (FileUtils.test(output, GLib.FileTest.EXISTS)){ + return output; + } + } + catch(Error e){ + log_error (e.message); + } + + return filePath2; + } + + public int rsync (string sourceDirectory, string destDirectory, bool updateExisting, bool deleteExtra){ + + /* Sync files with rsync */ + + string cmd = "rsync -avh"; + cmd += updateExisting ? "" : " --ignore-existing"; + cmd += deleteExtra ? " --delete" : ""; + cmd += " '%s'".printf(escape_single_quote(sourceDirectory) + "//"); + cmd += " '%s'".printf(escape_single_quote(destDirectory)); + return exec_sync (cmd, null, null); + } +} diff --git a/src/Utility/Console/TeeJee.Logging.vala b/src/Utility/Console/TeeJee.Logging.vala new file mode 100644 index 0000000..c87111d --- /dev/null +++ b/src/Utility/Console/TeeJee.Logging.vala @@ -0,0 +1,192 @@ + +/* + * TeeJee.Logging.vala + * + * Copyright 2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +namespace TeeJee.Logging{ + + /* Functions for logging messages to console and log files */ + + using TeeJee.Misc; + + public DataOutputStream dos_log; + public string err_log; + public bool LOG_ENABLE = true; + public bool LOG_TIMESTAMP = false; + public bool LOG_COLORS = false; + public bool LOG_DEBUG = false; + public bool LOG_TRACE = false; + public bool LOG_COMMANDS = false; + + public void log_msg (string message, bool highlight = false){ + + if (!LOG_ENABLE) { return; } + + string msg = ""; + + if (highlight && LOG_COLORS){ + msg += "\033[1;38;5;34m"; + } + + if (LOG_TIMESTAMP){ + msg += "[" + timestamp(true) + "] "; + } + + msg += message; + + if (highlight && LOG_COLORS){ + msg += "\033[0m"; + } + + msg += "\n"; + + stdout.printf (msg); + stdout.flush(); + + try { + if (dos_log != null){ + dos_log.put_string ("[%s] %s\n".printf(timestamp(), message)); + } + } + catch (Error e) { + stdout.printf (e.message); + } + } + + public void log_error (string message, bool highlight = false, bool is_warning = false){ + + if (!LOG_ENABLE) { return; } + + string msg = ""; + + if (highlight && LOG_COLORS){ + msg += "\033[1;38;5;160m"; + } + + if (LOG_TIMESTAMP){ + msg += "[" + timestamp(true) + "] "; + } + + string prefix = (is_warning) ? _("W") : _("E"); + + msg += prefix + ": " + message; + + if (highlight && LOG_COLORS){ + msg += "\033[0m"; + } + + msg += "\n"; + + stderr.printf (msg); + stderr.flush(); + + try { + string str = "[%s] %s: %s\n".printf(timestamp(), prefix, message); + + if (dos_log != null){ + dos_log.put_string (str); + } + + if ((err_log != null) && !is_warning){ + err_log += "%s\n".printf(message); + } + } + catch (Error e) { + stdout.printf (e.message); + } + } + + public void log_warning (string message, bool highlight = false, bool is_warning = false){ + log_error(message, highlight, true); + } + + public void log_debug (string message, bool highlight = false){ + if (!LOG_ENABLE) { return; } + + if (LOG_DEBUG){ + log_msg ("D: " + message, highlight); + } + + try { + if (dos_log != null){ + dos_log.put_string ("[%s] %s\n".printf(timestamp(), message)); + } + } + catch (Error e) { + stdout.printf (e.message); + } + } + + public void log_trace (string message){ + if (!LOG_ENABLE) { return; } + + if (LOG_TRACE){ + log_msg ("T: " + message); + } + + try { + if (dos_log != null){ + dos_log.put_string ("[%s] %s\n".printf(timestamp(), message)); + } + } + catch (Error e) { + stdout.printf (e.message); + } + } + + public void log_to_file (string message, bool highlight = false){ + try { + if (dos_log != null){ + dos_log.put_string ("[%s] %s\n".printf(timestamp(), message)); + } + } + catch (Error e) { + stdout.printf (e.message); + } + } + + public void log_draw_line(){ + log_msg(string.nfill(70,'=')); + } + + public void show_err_log(Gtk.Window parent, bool disable_log = true){ + if ((err_log != null) && (err_log.length > 0)){ + //gtk_messagebox(_("Error"), err_log, parent, true); + } + + if (disable_log){ + err_log_disable(); + } + } + + public void err_log_clear(){ + err_log = ""; + } + + public string err_log_read(){ + return err_log; + } + + public void err_log_disable(){ + err_log = null; + } +} diff --git a/src/Utility/Console/TeeJee.Misc.vala b/src/Utility/Console/TeeJee.Misc.vala new file mode 100644 index 0000000..28406a3 --- /dev/null +++ b/src/Utility/Console/TeeJee.Misc.vala @@ -0,0 +1,349 @@ + +/* + * TeeJee.Misc.vala + * + * Copyright 2016 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +namespace TeeJee.Misc { + + /* Various utility functions */ + + using TeeJee.Logging; + + // timestamp ---------------- + + public string timestamp (bool show_millis = false){ + + /* Returns a formatted timestamp string */ + + // NOTE: format() does not support milliseconds + + DateTime now = new GLib.DateTime.now_local(); + + if (show_millis){ + var msec = now.get_microsecond () / 1000; + return "%s.%03d".printf(now.format("%H:%M:%S"), msec); + } + else{ + return now.format ("%H:%M:%S"); + } + } + + public string timestamp_numeric (){ + + /* Returns a numeric timestamp string */ + + return "%ld".printf((long) time_t ()); + } + + public string timestamp_for_path (){ + + /* Returns a formatted timestamp string */ + + Time t = Time.local (time_t ()); + return t.format ("%Y-%d-%m_%H-%M-%S"); + } + + // string formatting ------------------------------------------------- + + public string format_date(DateTime date){ + return date.format ("%Y-%m-%d %H:%M"); + } + + public string format_date_12_hour(DateTime date){ + return date.format ("%Y-%m-%d %I:%M %p"); + } + + public string format_duration (long millis){ + + /* Converts time in milliseconds to format '00:00:00.0' */ + + double time = millis / 1000.0; // time in seconds + + double hr = Math.floor(time / (60.0 * 60)); + time = time - (hr * 60 * 60); + double min = Math.floor(time / 60.0); + time = time - (min * 60); + double sec = Math.floor(time); + + return "%02.0lf:%02.0lf:%02.0lf".printf (hr, min, sec); + } + + public string format_time_left(int64 millis){ + double mins = (millis * 1.0) / 60000; + double secs = ((millis * 1.0) % 60000) / 1000; + string txt = ""; + if (mins >= 1){ + txt += "%.0fm ".printf(mins); + } + txt += "%.0fs".printf(secs); + return txt; + } + + public double parse_time (string time){ + + /* Converts time in format '00:00:00.0' to milliseconds */ + + string[] arr = time.split (":"); + double millis = 0; + if (arr.length >= 3){ + millis += double.parse(arr[0]) * 60 * 60; + millis += double.parse(arr[1]) * 60; + millis += double.parse(arr[2]); + } + return millis; + } + + public string string_replace(string str, string search, string replacement, int count = -1){ + string[] arr = str.split(search); + string new_txt = ""; + bool first = true; + + foreach(string part in arr){ + if (first){ + new_txt += part; + } + else{ + if (count == 0){ + new_txt += search; + new_txt += part; + } + else{ + new_txt += replacement; + new_txt += part; + count--; + } + } + first = false; + } + + return new_txt; + } + + public string escape_html(string html, bool pango_markup = true){ + string txt = html; + + if (pango_markup){ + txt = txt + .replace("\\u00", "") + .replace("\\x" , ""); + } + else{ + txt = txt + .replace(" ", " "); //pango markup throws an error with   + } + + txt = txt + .replace("&" , "&") + .replace("\"", """) + .replace("<" , "<") + .replace(">" , ">") + ; + + return txt; + } + + public string unescape_html(string html){ + return html + .replace("&","&") + .replace(""","\"") + //.replace(" "," ") //pango markup throws an error with   + .replace("<","<") + .replace(">",">") + ; + } + + public string uri_encode(string path, bool encode_forward_slash){ + string uri = Uri.escape_string(path); + if (!encode_forward_slash){ + uri = uri.replace("%2F","/"); + } + return uri; + } + + public string uri_decode(string path){ + return Uri.unescape_string(path); + } + + public DateTime datetime_from_string (string date_time_string){ + + /* Converts date time string to DateTime + * + * Supported inputs: + * 'yyyy-MM-dd' + * 'yyyy-MM-dd HH' + * 'yyyy-MM-dd HH:mm' + * 'yyyy-MM-dd HH:mm:ss' + * */ + + string[] arr = date_time_string.replace(":"," ").replace("-"," ").strip().split(" "); + + int year = (arr.length >= 3) ? int.parse(arr[0]) : 0; + int month = (arr.length >= 3) ? int.parse(arr[1]) : 0; + int day = (arr.length >= 3) ? int.parse(arr[2]) : 0; + int hour = (arr.length >= 4) ? int.parse(arr[3]) : 0; + int min = (arr.length >= 5) ? int.parse(arr[4]) : 0; + int sec = (arr.length >= 6) ? int.parse(arr[5]) : 0; + + return new DateTime.utc(year,month,day,hour,min,sec); + } + + public string break_string_by_word(string input_text){ + string text = ""; + string line = ""; + foreach(string part in input_text.split(" ")){ + line += part + " "; + if (line.length > 50){ + text += line.strip() + "\n"; + line = ""; + } + } + if (line.length > 0){ + text += line; + } + if (text.has_suffix("\n")){ + text = text[0:text.length-1].strip(); + } + return text; + } + + public string[] array_concat(string[] a, string[] b){ + string[] c = {}; + foreach(string str in a){ c += str; } + foreach(string str in b){ c += str; } + return c; + } + + public string random_string(int length = 8, string charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"){ + string random = ""; + + for(int i=0;i 0){ + sequence = string.nfill(max_length - sequence.length, pad_char) + sequence; + } + output += sequence; + sequence = ""; + seq_started = false; + } + + output += character; + } + } + + //append remaining characters in sequence + if (sequence.length > 0){ + if ((max_length - sequence.length) > 0){ + sequence = string.nfill(max_length - sequence.length, pad_char) + sequence; + } + output += sequence; + sequence = ""; + } + + return output; + } + + public bool is_numeric(string text){ + for (int i = 0; i < text.length; i++){ + if (!text[i].isdigit()){ + return false; + } + } + return true; + } + + public MatchInfo? regex_match(string expression, string line){ + + Regex regex = null; + + try { + regex = new Regex(expression); + } + catch (Error e) { + log_error (e.message); + return null; + } + + MatchInfo match; + if (regex.match(line, 0, out match)) { + return match; + } + else{ + return null; + } + } + + public string regex_escape(string str){ + + string chars = """.^$*+?()[{|"""; // no \ + + string txt = str; + + // replace the escape char first + txt = txt.replace("""\""","""\\"""); + + for (int i = 0; i < chars.length; i++){ + string ch = chars[i].to_string(); + txt = txt.replace(ch, """\""" + ch); + } + + return txt; + } + + public class Converter: GLib.Object { + + public Gee.ArrayList convert_to_arraylist(T[] array){ + + var list = new Gee.ArrayList(); + + foreach(var item in array){ + list.add(item); + } + + return list; + } + } +} diff --git a/src/Utility/Console/TeeJee.Process.vala b/src/Utility/Console/TeeJee.Process.vala new file mode 100644 index 0000000..6c443de --- /dev/null +++ b/src/Utility/Console/TeeJee.Process.vala @@ -0,0 +1,542 @@ + +/* + * TeeJee.ProcessHelper.vala + * + * Copyright 2016 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +namespace TeeJee.ProcessHelper{ + + using TeeJee.Logging; + using TeeJee.FileSystem; + using TeeJee.Misc; + + public string TEMP_DIR; + + /* Convenience functions for executing commands and managing processes */ + + // execute process --------------------------------- + + public static void init_tmp(string subdir_name){ + string std_out, std_err; + + TEMP_DIR = Environment.get_tmp_dir() + "/" + subdir_name + "/" + random_string(); + dir_create(TEMP_DIR); + + exec_script_sync("echo 'ok'",out std_out,out std_err, true); + if ((std_out == null)||(std_out.strip() != "ok")){ + TEMP_DIR = Environment.get_home_dir() + "/.temp/" + subdir_name + "/" + random_string(); + exec_sync("rm -rf '%s'".printf(TEMP_DIR), null, null); + dir_create(TEMP_DIR); + } + + log_debug("TEMP_DIR=" + TEMP_DIR); + } + + public string create_temp_subdir(){ + var temp = "%s/%s".printf(TEMP_DIR, random_string()); + dir_create(temp); + return temp; + } + + public int exec_sync (string cmd, out string? std_out, out string? std_err){ + + /* Executes single command synchronously. + * Pipes and multiple commands are not supported. + * std_out, std_err can be null. Output will be written to terminal if null. */ + + try { + int status; + Process.spawn_command_line_sync(cmd, out std_out, out std_err, out status); + return status; + } + catch (Error e){ + log_error (e.message); + return -1; + } + } + + public int exec_script_sync (string script, out string? std_out, out string? std_err, + bool supress_errors = false, bool run_as_admin = false, bool cleanup_tmp = true, bool print_to_terminal = false){ + + /* Executes commands synchronously. + * Pipes and multiple commands are fully supported. + * Commands are written to a temporary bash script and executed. + * std_out, std_err can be null. Output will be written to terminal if null. + * */ + + string sh_file = save_bash_script_temp(script, null, true, supress_errors, run_as_admin); + + std_err = ""; + std_out = ""; + + try { + string[] argv = new string[1]; + argv[0] = sh_file; + + string[] env = Environ.get(); + + int exit_code; + + if (print_to_terminal){ + + Process.spawn_sync ( + TEMP_DIR, //working dir + argv, //argv + env, //environment + SpawnFlags.SEARCH_PATH, + null, // child_setup + null, + null, + out exit_code + ); + } + else{ + + Process.spawn_sync ( + TEMP_DIR, //working dir + argv, //argv + env, //environment + SpawnFlags.SEARCH_PATH, + null, // child_setup + out std_out, + out std_err, + out exit_code + ); + } + + if (cleanup_tmp){ + file_delete(sh_file); + } + + return exit_code; + } + catch (Error e){ + if (!supress_errors){ + log_error (e.message); + } + return -1; + } + } + + public int exec_script_async (string script){ + + /* Executes commands synchronously. + * Pipes and multiple commands are fully supported. + * Commands are written to a temporary bash script and executed. + * Return value indicates if script was started successfully. + * */ + + try { + + string scriptfile = save_bash_script_temp (script); + + string[] argv = new string[1]; + argv[0] = scriptfile; + + string[] env = Environ.get(); + + Pid child_pid; + Process.spawn_async_with_pipes( + TEMP_DIR, //working dir + argv, //argv + env, //environment + SpawnFlags.SEARCH_PATH, + null, + out child_pid); + + return 0; + } + catch (Error e){ + log_error (e.message); + return 1; + } + } + + public string? save_bash_script_temp (string commands, string? script_path = null, + bool force_locale = true, bool supress_errors = false, bool admin_mode = false){ + + string sh_path = script_path; + + /* Creates a temporary bash script with given commands + * Returns the script file path */ + + var script = new StringBuilder(); + script.append ("#!/bin/bash\n"); + script.append ("\n"); + if (force_locale){ + script.append ("LANG=C\n"); + } + script.append ("\n"); + script.append ("%s\n".printf(commands)); + script.append ("\n\nexitCode=$?\n"); + script.append ("echo ${exitCode} > ${exitCode}\n"); + script.append ("echo ${exitCode} > status\n"); + + if ((sh_path == null) || (sh_path.length == 0)){ + sh_path = get_temp_file_path() + ".sh"; + } + + try{ + //write script file + var file = File.new_for_path (sh_path); + if (file.query_exists ()) { + file.delete (); + } + var file_stream = file.create (FileCreateFlags.REPLACE_DESTINATION); + var data_stream = new DataOutputStream (file_stream); + data_stream.put_string (script.str); + data_stream.close(); + + // set execute permission + chmod (sh_path, "u+x"); + } + catch (Error e) { + if (!supress_errors){ + log_error (e.message); + } + return null; + } + + if (admin_mode){ + + var script_admin = "#!/bin/bash\n"; + script_admin += "pkexec env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY"; + script_admin += " '%s'".printf(escape_single_quote(sh_path)); + + string sh_file_admin = ""; + sh_file_admin = GLib.Path.build_filename(file_parent(sh_path),"script-admin.sh"); + + save_bash_script_temp(script_admin, sh_file_admin, true, supress_errors); + + return sh_file_admin; + } + else{ + return sh_path; + } + } + + public string get_temp_file_path(){ + + /* Generates temporary file path */ + + return TEMP_DIR + "/" + timestamp_numeric() + (new Rand()).next_int().to_string(); + } + + public void exec_process_new_session(string command){ + exec_script_async("setsid %s &".printf(command)); + } + + // find process ------------------------------- + + // dep: which + public string get_cmd_path (string cmd_tool){ + + /* Returns the full path to a command */ + + try { + int exitCode; + string stdout, stderr; + Process.spawn_command_line_sync("which " + cmd_tool, out stdout, out stderr, out exitCode); + return stdout.replace("\n","").replace("\r",""); + } + catch (Error e){ + log_error (e.message); + return ""; + } + } + + public bool cmd_exists(string cmd_tool){ + string path = get_cmd_path (cmd_tool); + if ((path == null) || (path.length == 0)){ + return false; + } + else{ + return true; + } + } + + // dep: pidof, TODO: Rewrite using /proc + public int get_pid_by_name (string name){ + + /* Get the process ID for a process with given name */ + + string std_out, std_err; + exec_sync("pidof \"%s\"".printf(name), out std_out, out std_err); + + if (std_out != null){ + string[] arr = std_out.split ("\n"); + if (arr.length > 0){ + return int.parse (arr[0]); + } + } + + return -1; + } + + public int get_pid_by_command(string cmdline){ + + /* Searches for process using the command line used to start the process. + * Returns the process id if found. + * */ + + try { + FileEnumerator enumerator; + FileInfo info; + File file = File.parse_name ("/proc"); + + enumerator = file.enumerate_children ("standard::name", 0); + while ((info = enumerator.next_file()) != null) { + try { + string io_stat_file_path = "/proc/%s/cmdline".printf(info.get_name()); + var io_stat_file = File.new_for_path(io_stat_file_path); + if (file.query_exists()){ + var dis = new DataInputStream (io_stat_file.read()); + + string line; + string text = ""; + size_t length; + while((line = dis.read_until ("\0", out length)) != null){ + text += " " + line; + } + + if ((text != null) && text.contains(cmdline)){ + return int.parse(info.get_name()); + } + } //stream closed + } + catch(Error e){ + // do not log + // some processes cannot be accessed by non-admin user + } + } + } + catch(Error e){ + log_error (e.message); + } + + return -1; + } + + public void get_proc_io_stats(int pid, out int64 read_bytes, out int64 write_bytes){ + + /* Returns the number of bytes read and written by a process to disk */ + + string io_stat_file_path = "/proc/%d/io".printf(pid); + var file = File.new_for_path(io_stat_file_path); + + read_bytes = 0; + write_bytes = 0; + + try { + if (file.query_exists()){ + var dis = new DataInputStream (file.read()); + string line; + while ((line = dis.read_line (null)) != null) { + if(line.has_prefix("rchar:")){ + read_bytes = int64.parse(line.replace("rchar:","").strip()); + } + else if(line.has_prefix("wchar:")){ + write_bytes = int64.parse(line.replace("wchar:","").strip()); + } + } + } //stream closed + } + catch(Error e){ + log_error (e.message); + } + } + + // dep: ps TODO: Rewrite using /proc + public bool process_is_running(long pid){ + + /* Checks if given process is running */ + + string cmd = ""; + string std_out; + string std_err; + int ret_val; + + try{ + cmd = "ps --pid %ld".printf(pid); + Process.spawn_command_line_sync(cmd, out std_out, out std_err, out ret_val); + } + catch (Error e) { + log_error (e.message); + return false; + } + + return (ret_val == 0); + } + + // dep: pgrep TODO: Rewrite using /proc + public bool process_is_running_by_name(string proc_name){ + + /* Checks if given process is running */ + + string cmd = ""; + string std_out; + string std_err; + int ret_val; + + try{ + cmd = "pgrep -f '%s'".printf(proc_name); + Process.spawn_command_line_sync(cmd, out std_out, out std_err, out ret_val); + } + catch (Error e) { + log_error (e.message); + return false; + } + + return (ret_val == 0); + } + + // dep: ps TODO: Rewrite using /proc + public int[] get_process_children (Pid parent_pid){ + + /* Returns the list of child processes spawned by given process */ + + string std_out, std_err; + exec_sync("ps --ppid %d".printf(parent_pid), out std_out, out std_err); + + int pid; + int[] procList = {}; + string[] arr; + + foreach (string line in std_out.split ("\n")){ + arr = line.strip().split (" "); + if (arr.length < 1) { continue; } + + pid = 0; + pid = int.parse (arr[0]); + + if (pid != 0){ + procList += pid; + } + } + return procList; + } + + // manage process --------------------------------- + + public void process_quit(Pid process_pid, bool killChildren = true){ + + /* Kills specified process and its children (optional). + * Sends signal SIGTERM to the process to allow it to quit gracefully. + * */ + + int[] child_pids = get_process_children (process_pid); + Posix.kill (process_pid, Posix.SIGTERM); + + if (killChildren){ + Pid childPid; + foreach (long pid in child_pids){ + childPid = (Pid) pid; + Posix.kill(childPid, Posix.SIGTERM); + } + } + } + + public void process_kill(Pid process_pid, bool killChildren = true){ + + /* Kills specified process and its children (optional). + * Sends signal SIGKILL to the process to kill it forcefully. + * It is recommended to use the function process_quit() instead. + * */ + + int[] child_pids = get_process_children (process_pid); + Posix.kill (process_pid, Posix.SIGKILL); + + if (killChildren){ + Pid childPid; + foreach (long pid in child_pids){ + childPid = (Pid) pid; + Posix.kill (childPid, Posix.SIGKILL); + } + } + } + + // dep: kill + public int process_pause (Pid procID){ + + /* Pause/Freeze a process */ + + return exec_sync ("kill -STOP %d".printf(procID), null, null); + } + + // dep: kill + public int process_resume (Pid procID){ + + /* Resume/Un-freeze a process*/ + + return exec_sync ("kill -CONT %d".printf(procID), null, null); + } + + // dep: ps TODO: Rewrite using /proc + public void process_quit_by_name(string cmd_name, string cmd_to_match, bool exact_match){ + + /* Kills a specific command */ + + string std_out, std_err; + exec_sync ("ps w -C '%s'".printf(cmd_name), out std_out, out std_err); + //use 'ps ew -C conky' for all users + + string pid = ""; + foreach(string line in std_out.split("\n")){ + if ((exact_match && line.has_suffix(" " + cmd_to_match)) + || (!exact_match && (line.index_of(cmd_to_match) != -1))){ + pid = line.strip().split(" ")[0]; + Posix.kill ((Pid) int.parse(pid), 15); + log_debug(_("Stopped") + ": [PID=" + pid + "] "); + } + } + } + + // process priority --------------------------------------- + + public void process_set_priority (Pid procID, int prio){ + + /* Set process priority */ + + if (Posix.getpriority (Posix.PRIO_PROCESS, procID) != prio) + Posix.setpriority (Posix.PRIO_PROCESS, procID, prio); + } + + public int process_get_priority (Pid procID){ + + /* Get process priority */ + + return Posix.getpriority (Posix.PRIO_PROCESS, procID); + } + + public void process_set_priority_normal (Pid procID){ + + /* Set normal priority for process */ + + process_set_priority (procID, 0); + } + + public void process_set_priority_low (Pid procID){ + + /* Set low priority for process */ + + process_set_priority (procID, 5); + } +} diff --git a/src/Utility/Console/TeeJee.System.vala b/src/Utility/Console/TeeJee.System.vala new file mode 100644 index 0000000..a57d54a --- /dev/null +++ b/src/Utility/Console/TeeJee.System.vala @@ -0,0 +1,561 @@ + +/* + * TeeJee.System.vala + * + * Copyright 2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +namespace TeeJee.System{ + + using TeeJee.ProcessHelper; + using TeeJee.Logging; + using TeeJee.Misc; + using TeeJee.FileSystem; + + // user --------------------------------------------------- + + public bool user_is_admin (){ + + /* Check if current application is running with admin priviledges */ + + try{ + // create a process + string[] argv = { "sleep", "10" }; + Pid procId; + Process.spawn_async(null, argv, null, SpawnFlags.SEARCH_PATH, null, out procId); + + // try changing the priority + Posix.setpriority (Posix.PRIO_PROCESS, procId, -5); + + // check if priority was changed successfully + if (Posix.getpriority (Posix.PRIO_PROCESS, procId) == -5) + return true; + else + return false; + } + catch (Error e) { + log_error (e.message); + return false; + } + } + + public int get_user_id(){ + + // returns actual user id of current user (even for applications executed with sudo and pkexec) + + string pkexec_uid = GLib.Environment.get_variable("PKEXEC_UID"); + + if (pkexec_uid != null){ + return int.parse(pkexec_uid); + } + + string sudo_user = GLib.Environment.get_variable("SUDO_USER"); + + if (sudo_user != null){ + return get_user_id_from_username(sudo_user); + } + + return get_user_id_effective(); // normal user + } + + public int get_user_id_effective(){ + + // returns effective user id (0 for applications executed with sudo and pkexec) + + int uid = -1; + string cmd = "id -u"; + string std_out, std_err; + exec_sync(cmd, out std_out, out std_err); + if ((std_out != null) && (std_out.length > 0)){ + uid = int.parse(std_out); + } + + return uid; + } + + public string get_username(){ + + // returns actual username of current user (even for applications executed with sudo and pkexec) + + return get_username_from_uid(get_user_id()); + } + + public string get_username_effective(){ + + // returns effective user id ('root' for applications executed with sudo and pkexec) + + return get_username_from_uid(get_user_id_effective()); + } + + public int get_user_id_from_username(string username){ + + int user_id = -1; + + foreach(var line in file_read("/etc/passwd").split("\n")){ + var arr = line.split(":"); + if (arr.length < 3) { continue; } + if (arr[0] == username){ + user_id = int.parse(arr[2]); + break; + } + } + + return user_id; + } + + public string get_username_from_uid(int user_id){ + + string username = ""; + + foreach(var line in file_read("/etc/passwd").split("\n")){ + var arr = line.split(":"); + if (arr.length < 3) { continue; } + if (int.parse(arr[2]) == user_id){ + username = arr[0]; + break; + } + } + + return username; + } + + public string get_user_home(string username = get_username()){ + + string userhome = ""; + + foreach(var line in file_read("/etc/passwd").split("\n")){ + var arr = line.split(":"); + if (arr.length < 6) { continue; } + if (arr[0] == username){ + userhome = arr[5]; + break; + } + } + + return userhome; + } + + public string get_user_home_effective(){ + return get_user_home(get_username_effective()); + } + + // application ----------------------------------------------- + + public string get_app_path(){ + + /* Get path of current process */ + + try{ + return GLib.FileUtils.read_link ("/proc/self/exe"); + } + catch (Error e){ + log_error (e.message); + return ""; + } + } + + public string get_app_dir(){ + + /* Get parent directory of current process */ + + try{ + return (File.new_for_path (GLib.FileUtils.read_link ("/proc/self/exe"))).get_parent ().get_path (); + } + catch (Error e){ + log_error (e.message); + return ""; + } + } + + // system ------------------------------------ + + // dep: cat TODO: rewrite + public double get_system_uptime_seconds(){ + + /* Returns the system up-time in seconds */ + + string cmd = ""; + string std_out; + string std_err; + int ret_val; + + try{ + cmd = "cat /proc/uptime"; + Process.spawn_command_line_sync(cmd, out std_out, out std_err, out ret_val); + string uptime = std_out.split(" ")[0]; + double secs = double.parse(uptime); + return secs; + } + catch(Error e){ + log_error (e.message); + return 0; + } + } + + public string get_desktop_name(){ + + /* Return the names of the current Desktop environment */ + + int pid = -1; + + pid = get_pid_by_name("cinnamon"); + if (pid > 0){ + return "Cinnamon"; + } + + pid = get_pid_by_name("xfdesktop"); + if (pid > 0){ + return "Xfce"; + } + + pid = get_pid_by_name("lxsession"); + if (pid > 0){ + return "LXDE"; + } + + pid = get_pid_by_name("gnome-shell"); + if (pid > 0){ + return "Gnome"; + } + + pid = get_pid_by_name("wingpanel"); + if (pid > 0){ + return "Elementary"; + } + + pid = get_pid_by_name("unity-panel-service"); + if (pid > 0){ + return "Unity"; + } + + pid = get_pid_by_name("plasma-desktop"); + if (pid > 0){ + return "KDE"; + } + + return "Unknown"; + } + + public Gee.ArrayList list_dir_names(string path){ + var list = new Gee.ArrayList(); + + try + { + File f_home = File.new_for_path (path); + FileEnumerator enumerator = f_home.enumerate_children ("%s".printf(FileAttribute.STANDARD_NAME), 0); + FileInfo file; + while ((file = enumerator.next_file ()) != null) { + string name = file.get_name(); + //string item = path + "/" + name; + list.add(name); + } + } + catch (Error e) { + log_error (e.message); + } + + //sort the list + CompareDataFunc entry_compare = (a, b) => { + return strcmp(a,b); + }; + list.sort((owned) entry_compare); + + return list; + } + + // internet helpers ---------------------- + + public bool check_internet_connectivity(){ + bool connected = false; + connected = check_internet_connectivity_test1(); + + if (connected){ + return connected; + } + + if (!connected){ + connected = check_internet_connectivity_test2(); + } + + return connected; + } + + public bool check_internet_connectivity_test1(){ + int exit_code = -1; + string std_err; + string std_out; + + string cmd = "ping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3`\n"; + cmd += "exit $?"; + exit_code = exec_script_sync(cmd, out std_out, out std_err, false); + + return (exit_code == 0); + } + + public bool check_internet_connectivity_test2(){ + int exit_code = -1; + string std_err; + string std_out; + + string cmd = "ping -q -w 1 -c 1 google.com\n"; + cmd += "exit $?"; + exit_code = exec_script_sync(cmd, out std_out, out std_err, false); + + return (exit_code == 0); + } + + public bool shutdown (){ + + /* Shutdown the system immediately */ + + try{ + string[] argv = { "shutdown", "-h", "now" }; + Pid procId; + Process.spawn_async(null, argv, null, SpawnFlags.SEARCH_PATH, null, out procId); + return true; + } + catch (Error e) { + log_error (e.message); + return false; + } + } + + public bool command_exists(string command){ + string path = get_cmd_path(command); + return ((path != null) && (path.length > 0)); + } + + // open ----------------------------- + + public bool xdg_open (string file, string user = ""){ + string path = get_cmd_path ("xdg-open"); + if ((path != null) && (path != "")){ + string cmd = "xdg-open '%s'".printf(escape_single_quote(file)); + if (user.length > 0){ + cmd = "pkexec --user %s env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY ".printf(user) + cmd; + } + log_debug(cmd); + int status = exec_script_async(cmd); + return (status == 0); + } + return false; + } + + public bool exo_open_folder (string dir_path, bool xdg_open_try_first = true){ + + /* Tries to open the given directory in a file manager */ + + /* + xdg-open is a desktop-independent tool for configuring the default applications of a user. + Inside a desktop environment (e.g. GNOME, KDE, Xfce), xdg-open simply passes the arguments + to that desktop environment's file-opener application (gvfs-open, kde-open, exo-open, respectively). + We will first try using xdg-open and then check for specific file managers if it fails. + */ + + string path; + int status; + + if (xdg_open_try_first){ + //try using xdg-open + path = get_cmd_path ("xdg-open"); + if ((path != null)&&(path != "")){ + string cmd = "xdg-open '%s'".printf(escape_single_quote(dir_path)); + status = exec_script_async (cmd); + return (status == 0); + } + } + + foreach(string app_name in + new string[]{ "nemo", "nautilus", "thunar", "pantheon-files", "marlin"}){ + + path = get_cmd_path (app_name); + if ((path != null)&&(path != "")){ + string cmd = "%s '%s'".printf(app_name, escape_single_quote(dir_path)); + status = exec_script_async (cmd); + return (status == 0); + } + } + + if (xdg_open_try_first == false){ + //try using xdg-open + path = get_cmd_path ("xdg-open"); + if ((path != null)&&(path != "")){ + string cmd = "xdg-open '%s'".printf(escape_single_quote(dir_path)); + status = exec_script_async (cmd); + return (status == 0); + } + } + + return false; + } + + public bool exo_open_textfile (string txt_file){ + + /* Tries to open the given text file in a text editor */ + + string path; + int status; + string cmd; + + path = get_cmd_path ("exo-open"); + if ((path != null)&&(path != "")){ + cmd = "exo-open '%s'".printf(escape_single_quote(txt_file)); + status = exec_script_async (cmd); + return (status == 0); + } + + path = get_cmd_path ("gedit"); + if ((path != null)&&(path != "")){ + cmd = "gedit --new-document '%s'".printf(escape_single_quote(txt_file)); + status = exec_script_async (cmd); + return (status == 0); + } + + return false; + } + + public bool exo_open_url (string url){ + + /* Tries to open the given text file in a text editor */ + + string path; + int status; + //string cmd; + + path = get_cmd_path ("exo-open"); + if ((path != null)&&(path != "")){ + status = exec_script_async ("exo-open \"" + url + "\""); + return (status == 0); + } + + path = get_cmd_path ("firefox"); + if ((path != null)&&(path != "")){ + status = exec_script_async ("firefox \"" + url + "\""); + return (status == 0); + } + + path = get_cmd_path ("chromium-browser"); + if ((path != null)&&(path != "")){ + status = exec_script_async ("chromium-browser \"" + url + "\""); + return (status == 0); + } + + return false; + } + + public bool using_efi_boot(){ + + /* Returns true if the system was booted in EFI mode + * and false for BIOS mode */ + + return dir_exists("/sys/firmware/efi"); + } + + public void open_terminal_window( + string terminal_emulator, + string working_dir, + string script_file_to_execute, + bool run_as_admin){ + + string cmd = ""; + if (run_as_admin){ + cmd += "pkexec env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY "; + } + + string term = terminal_emulator; + if (!command_exists(term)){ + term = "gnome-terminal"; + if (!command_exists(term)){ + term = "xfce4-terminal"; + } + } + + cmd += term; + + switch (term){ + case "gnome-terminal": + case "xfce4-terminal": + if (working_dir.length > 0){ + cmd += " --working-directory='%s'".printf(escape_single_quote(working_dir)); + } + if (script_file_to_execute.length > 0){ + cmd += " -e '%s\n; echo Press ENTER to exit... ; read dummy;'".printf(escape_single_quote(script_file_to_execute)); + } + break; + } + + log_debug(cmd); + exec_script_async(cmd); + } + + // timers -------------------------------------------------- + + public GLib.Timer timer_start(){ + var timer = new GLib.Timer(); + timer.start(); + return timer; + } + + public void timer_restart(GLib.Timer timer){ + timer.reset(); + timer.start(); + } + + public ulong timer_elapsed(GLib.Timer timer, bool stop = true){ + ulong microseconds; + double seconds; + seconds = timer.elapsed (out microseconds); + if (stop){ + timer.stop(); + } + return (ulong)((seconds * 1000 ) + (microseconds / 1000)); + } + + public void sleep(int milliseconds){ + Thread.usleep ((ulong) milliseconds * 1000); + } + + public string timer_elapsed_string(GLib.Timer timer, bool stop = true){ + ulong microseconds; + double seconds; + seconds = timer.elapsed (out microseconds); + if (stop){ + timer.stop(); + } + return "%.0f ms".printf((seconds * 1000 ) + microseconds/1000); + } + + public void timer_elapsed_print(GLib.Timer timer, bool stop = true){ + ulong microseconds; + double seconds; + seconds = timer.elapsed (out microseconds); + if (stop){ + timer.stop(); + } + log_msg("%s %lu\n".printf(seconds.to_string(), microseconds)); + } + + + public void set_numeric_locale(string type){ + Intl.setlocale(GLib.LocaleCategory.NUMERIC, type); + Intl.setlocale(GLib.LocaleCategory.COLLATE, type); + Intl.setlocale(GLib.LocaleCategory.TIME, type); + } +} diff --git a/src/Utility/Console/TimeoutCounter.vala b/src/Utility/Console/TimeoutCounter.vala new file mode 100644 index 0000000..f3ffb22 --- /dev/null +++ b/src/Utility/Console/TimeoutCounter.vala @@ -0,0 +1,96 @@ + +/* + * TimeoutCounter.vala + * + * Copyright 2016 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.Misc; + +public class TimeoutCounter : GLib.Object { + + public bool active = false; + public string process_to_kill = ""; + public const int DEFAULT_SECONDS_TO_WAIT = 60; + public int seconds_to_wait = 60; + public bool exit_app = false; + + public void kill_process_on_timeout( + string process_to_kill, int seconds_to_wait = DEFAULT_SECONDS_TO_WAIT, bool exit_app = false){ + + this.process_to_kill = process_to_kill; + this.seconds_to_wait = seconds_to_wait; + this.exit_app = exit_app; + + try { + active = true; + Thread.create (start_counter_thread, true); + } + catch (Error e) { + log_error (e.message); + } + } + + public void exit_on_timeout(int seconds_to_wait = DEFAULT_SECONDS_TO_WAIT){ + this.process_to_kill = ""; + this.seconds_to_wait = seconds_to_wait; + this.exit_app = true; + + try { + active = true; + Thread.create (start_counter_thread, true); + } + catch (Error e) { + log_error (e.message); + } + } + + public void stop(){ + active = false; + } + + public void start_counter_thread(){ + int secs = 0; + + while (active && (secs < seconds_to_wait)){ + Thread.usleep((ulong) GLib.TimeSpan.MILLISECOND * 1000); + secs += 1; + } + + if (active){ + active = false; + stdout.printf("\n"); + + if (process_to_kill.length > 0){ + Posix.system("killall " + process_to_kill); + log_debug("[timeout] Killed process" + ": %s".printf(process_to_kill)); + } + + if (exit_app){ + log_debug("[timeout] Exit application"); + exit(0); + } + } + } +} + diff --git a/src/Utility/Console/Version.vala b/src/Utility/Console/Version.vala new file mode 100644 index 0000000..e12a31f --- /dev/null +++ b/src/Utility/Console/Version.vala @@ -0,0 +1,94 @@ + +/* + * Version.vala + * + * Copyright 2016 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.Misc; + +namespace TeeJee { + + public class Version : GLib.Object, Gee.Comparable { + + public string version = ""; + public Gee.ArrayList version_numbers; + + public Version(string version_string){ + version = version_string; + version_numbers = new Gee.ArrayList(); + + string[] arr = version.split_set (".-_"); + + foreach(var part in arr){ + if (is_numeric(part)){ + version_numbers.add(int.parse(part)); + } + else{ + break; + } + } + } + + public int compare_to(Version b){ + Version a = this; + int i = 0; + + // while both arrays have an element + while ((i < a.version_numbers.size) && (i < b.version_numbers.size)){ + + // continue if equal + if (a.version_numbers[i] == b.version_numbers[i]){ + i++; + continue; + } + + // return difference + return a.version_numbers[i] - b.version_numbers[i]; + } + + // one array has less parts than the other and all corresponding parts are equal + + // larger array is larger version + return a.version_numbers.size - b.version_numbers.size; + } + + public bool is_minimum(string version_string){ + Version a = this; + Version b = new Version(version_string); + return a.compare_to(b) >= 0; + } + + public bool is_maximum(string version_string){ + Version a = this; + Version b = new Version(version_string); + return a.compare_to(b) <= 0; + } + + public bool is_equal(string version_string){ + Version a = this; + Version b = new Version(version_string); + return a.compare_to(b) == 0; + } + } +} diff --git a/src/Utility/Gtk/AboutWindow.vala b/src/Utility/Gtk/AboutWindow.vala new file mode 100644 index 0000000..345a2a2 --- /dev/null +++ b/src/Utility/Gtk/AboutWindow.vala @@ -0,0 +1,526 @@ +/* + * AboutWindow.vala + * + * Copyright 2012-2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +using Gtk; + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.JsonHelper; +using TeeJee.ProcessHelper; +using TeeJee.GtkHelper; +using TeeJee.System; +using TeeJee.Misc; + +public class AboutWindow : Dialog { + + private Gtk.Box vbox_main; + private Gtk.Box vbox_logo; + private Gtk.Box vbox_credits; + private Gtk.Box vbox_license; + private Gtk.Box vbox_lines; + private Gtk.Box hbox_action; + private Gtk.Button btn_license; + private Gtk.Button btn_credits; + private Gtk.Button btn_close; + + private Gtk.Image img_logo; + private Gtk.Label lbl_program_name; + private Gtk.Label lbl_version; + private Gtk.Label lbl_comments; + private Gtk.Label lbl_license; + private Gtk.LinkButton lbtn_website; + private Gtk.Label lbl_copyright; + + private string[] _artists; + public string[] artists{ + get{ + return _artists; + } + set{ + _artists = value; + } + } + + private string[] _authors; + public string[] authors{ + get{ + return _authors; + } + set{ + _authors = value; + } + } + + private string[] _contributors; + public string[] contributors{ + get{ + return _contributors; + } + set{ + _contributors = value; + } + } + + private string _comments = ""; + public string comments{ + get{ + return _comments; + } + set{ + _comments = value; + } + } + + private string _copyright = ""; + public string copyright{ + get{ + return _copyright; + } + set{ + _copyright = value; + } + } + + private string[] _documenters; + public string[] documenters{ + get{ + return _documenters; + } + set{ + _documenters = value; + } + } + + private string[] _donations; + public string[] donations{ + get{ + return _donations; + } + set{ + _donations = value; + } + } + + private string _license = ""; + public string license{ + get{ + return _license; + } + set{ + _license = value; + } + } + + private Gdk.Pixbuf _logo; + public Gdk.Pixbuf logo{ + get{ + return _logo; + } + set{ + _logo = value; + } + } + + private string _program_name = ""; + public string program_name{ + get{ + return _program_name; + } + set{ + _program_name = value; + } + } + + private string[] _translators; + public string[] translators{ + get{ + return _translators; + } + set{ + _translators = value; + } + } + + private string[] _third_party; + public string[] third_party{ + get{ + return _third_party; + } + set{ + _third_party = value; + } + } + + private string _version = ""; + public string version{ + get{ + return _version; + } + set{ + _version = value; + } + } + + private string _website = ""; + public string website{ + get{ + return _website; + } + set{ + _website = value; + } + } + + private string _website_label = ""; + public string website_label{ + get{ + return _website_label; + } + set{ + _website_label = value; + } + } + + private string username = ""; + + public AboutWindow() { + + window_position = WindowPosition.CENTER_ON_PARENT; + set_destroy_with_parent (true); + set_modal (true); + skip_taskbar_hint = false; + set_default_size (450, 400); + + if (get_user_id_effective() == 0){ + username = get_username(); + } + + vbox_main = get_content_area(); + vbox_main.margin = 6; + vbox_main.spacing = 6; + + vbox_logo = new Gtk.Box(Orientation.VERTICAL,0); + vbox_main.add(vbox_logo); + + // license ------------------------------------- + + vbox_license = new Gtk.Box(Orientation.VERTICAL,0); + vbox_license.no_show_all = true; + vbox_main.add(vbox_license); + + var sw_license = new Gtk.ScrolledWindow(null, null); + sw_license.set_shadow_type(ShadowType.ETCHED_IN); + sw_license.expand = true; + vbox_license.add(sw_license); + + var label = new Gtk.Label(""); + label.set_use_markup(true); + label.margin_top = 5; + label.xalign = 0.0f; + label.yalign = 0.0f; + //label.max_width_chars = 70; + label.wrap = true; + label.wrap_mode = Pango.WrapMode.WORD_CHAR; + label.use_markup = true; + label.margin = 6; + label.margin_right = 25; + sw_license.add(label); + lbl_license = label; + + // credits -------------------------------- + + vbox_credits = new Gtk.Box(Orientation.VERTICAL,0); + vbox_credits.no_show_all = true; + vbox_main.add(vbox_credits); + + var sw_credits = new Gtk.ScrolledWindow(null, null); + sw_credits.set_shadow_type(ShadowType.ETCHED_IN); + sw_credits.expand = true; + vbox_credits.add(sw_credits); + + vbox_lines = new Gtk.Box(Orientation.VERTICAL,0); + vbox_lines.margin_top = 10; + sw_credits.add(vbox_lines); + + //logo + img_logo = new Gtk.Image(); + img_logo.margin_top = 6; + img_logo.margin_bottom = 6; + vbox_logo.add(img_logo); + + //program_name + lbl_program_name = new Gtk.Label(""); + lbl_program_name.set_use_markup(true); + vbox_logo.add(lbl_program_name); + + //version + lbl_version = new Gtk.Label(""); + lbl_version.set_use_markup(true); + lbl_version.margin_top = 5; + vbox_logo.add(lbl_version); + + //comments + lbl_comments = new Gtk.Label(""); + lbl_comments.set_use_markup(true); + lbl_comments.margin_top = 10; + vbox_logo.add(lbl_comments); + + //website + lbtn_website = new LinkButton(""); + lbtn_website.margin_top = 5; + vbox_logo.add(lbtn_website); + + lbtn_website.activate_link.connect(()=>{ + return xdg_open(lbtn_website.uri, username); + }); + + //copyright + lbl_copyright = new Gtk.Label(""); + lbl_copyright.set_use_markup(true); + lbl_copyright.margin_top = 5; + vbox_logo.add(lbl_copyright); + + //spacer_bottom + var spacer_bottom = new Gtk.Label(""); + spacer_bottom.margin_top = 20; + vbox_logo.add(spacer_bottom); + + add_action_buttons(); + } + + private void add_action_buttons(){ + + hbox_action = (Box) get_action_area(); + + //btn_license + btn_license = new Gtk.Button.with_label(" " + _("License")); + btn_license.image = IconManager.lookup_image("help-about-symbolic", 16); + hbox_action.add(btn_license); + + //btn_credits + btn_credits = new Gtk.Button.with_label(" " + _("Credits")); + btn_credits.image = IconManager.lookup_image("help-about-symbolic", 16); + hbox_action.add(btn_credits); + + // handlers + + btn_license.clicked.connect(()=>{ + + vbox_logo.visible = !vbox_logo.visible; + + vbox_license.visible = !vbox_license.visible; + + if (vbox_license.visible){ + vbox_license.set_no_show_all(false); + vbox_license.show_all(); + vbox_credits.hide(); + vbox_logo.hide(); + } + else{ + vbox_logo.show_all(); + } + + if (vbox_license.visible){ + btn_license.label = " " + _("Back"); + btn_license.image = IconManager.lookup_image("go-previous-symbolic", 16); + btn_license.always_show_image = true; + btn_credits.hide(); + this.resize(600, 500); + } + else{ + btn_license.label = " " + _("License"); + btn_license.image = null; + btn_license.always_show_image = false; + btn_credits.show(); + this.resize(450, 400); + } + }); + + btn_credits.clicked.connect(()=>{ + + vbox_logo.visible = !vbox_logo.visible; + + vbox_credits.visible = !vbox_credits.visible; + + if (vbox_credits.visible){ + vbox_credits.set_no_show_all(false); + vbox_credits.show_all(); + vbox_license.hide(); + vbox_logo.hide(); + } + else{ + vbox_logo.show_all(); + } + + if (vbox_credits.visible){ + btn_credits.label = " " + _("Back"); + btn_credits.image = IconManager.lookup_image("go-previous-symbolic", 16); + btn_credits.always_show_image = true; + btn_license.hide(); + } + else{ + btn_credits.label = " " + _("Credits"); + btn_credits.image = null; + btn_credits.always_show_image = false; + btn_license.show(); + } + }); + + + /*if (AppVersion == AppWikiVersion){ + // changelog + var button = new Gtk.Button.with_label(" " + _("Changelog")); + hbox_action.add(button); + + button.clicked.connect(()=>{ + //App.open_changelog_webpage(); + }); + }*/ + + // close + var button = new Gtk.Button.with_label(" " + _("Close")); + button.image = IconManager.lookup_image("window-close", 16); + hbox_action.add(button); + + button.clicked.connect(()=>{ this.destroy(); }); + } + + public void initialize() { + + title = program_name; + img_logo.pixbuf = logo.scale_simple(128,128,Gdk.InterpType.HYPER); + lbl_program_name.label = "%s".printf(program_name); + lbl_version.label = "v%s".printf(version); + lbl_comments.label = "%s".printf(comments); + lbtn_website.uri = website; + lbtn_website.label = website_label; + lbl_copyright.label = "%s".printf(copyright); + + if (license.length > 0){ + lbl_license.label = license + "\n\n" + escape_html(GPLv2LicenseText); + } + else{ + lbl_license.label = escape_html(GPLv2LicenseText); + } + + if (authors.length > 0){ + add_header(_("Authors")); + foreach(string name in authors){ + add_line("%s\n".printf(name)); + } + add_line("\n"); + } + + if (contributors.length > 0){ + add_header(_("Code Contributions")); + foreach(string name in contributors){ + add_line("%s\n".printf(name)); + } + add_line("\n"); + } + + if (artists.length > 0){ + add_header(_("Artists")); + foreach(string name in artists){ + add_line("%s\n".printf(name)); + } + add_line("\n"); + } + + if (translators.length > 0){ + add_header(_("Translations")); + foreach(string name in translators){ + add_line("%s\n".printf(name)); + } + add_line("\n"); + } + + if (documenters.length > 0){ + add_header(_("Documentation")); + foreach(string name in documenters){ + add_line("%s\n".printf(name)); + } + add_line("\n"); + } + + if (third_party.length > 0){ + add_header(_("Icon Themes & Utilities")); + foreach(string name in third_party){ + add_line("%s\n".printf(name)); + } + add_line("\n"); + } + + if (donations.length > 0){ + add_header(_("Donations")); + foreach(string name in donations){ + add_line("%s\n".printf(name)); + } + add_line("\n"); + } + + if (vbox_lines.get_children().length() == 0){ + btn_credits.visible = false; + } + } + + private void add_line(string text, bool escape_html_chars = true){ + + if (text.split(":").length >= 2){ + var link = new LinkButton(escape_html(text.split(":")[0])); + vbox_lines.add(link); + + string val = text[text.index_of(":") + 1:text.length]; + if (val.contains("@")){ + link.uri = "mailto:" + val; + } + else if(val.has_prefix("http://") || val.has_prefix("https://")){ + link.uri = val; + } + else{ + link.uri = "http://" + val; + } + + link.activate_link.connect(()=>{ + return xdg_open(link.uri, username); + }); + } + else{ + var txt = text; + if (escape_html_chars){ + txt = escape_html(text); + } + + var lbl = new Gtk.Label(txt); + lbl.set_use_markup(true); + lbl.valign = Align.START; + lbl.wrap = true; + lbl.wrap_mode = Pango.WrapMode.WORD; + vbox_lines.add(lbl); + } + } + + private void add_header(string text){ + add_line("%s\n".printf(escape_html(text)), false); + } +} diff --git a/src/Utility/Gtk/CellRendererProgress2.vala b/src/Utility/Gtk/CellRendererProgress2.vala new file mode 100644 index 0000000..775cf67 --- /dev/null +++ b/src/Utility/Gtk/CellRendererProgress2.vala @@ -0,0 +1,18 @@ + public class CellRendererProgress2 : Gtk.CellRendererProgress{ + public override void render (Cairo.Context cr, Gtk.Widget widget, Gdk.Rectangle background_area, Gdk.Rectangle cell_area, Gtk.CellRendererState flags) { + if (text == "--") + return; + + int diff = (int) ((cell_area.height - height)/2); + + // Apply the new height into the bar, and center vertically: + Gdk.Rectangle new_area = Gdk.Rectangle() ; + new_area.x = cell_area.x; + new_area.y = cell_area.y + diff; + new_area.width = width - 5; + new_area.height = height; + + base.render(cr, widget, background_area, new_area, flags); + } + } + diff --git a/src/Utility/Gtk/CustomMessageDialog.vala b/src/Utility/Gtk/CustomMessageDialog.vala new file mode 100644 index 0000000..0c6e5e3 --- /dev/null +++ b/src/Utility/Gtk/CustomMessageDialog.vala @@ -0,0 +1,185 @@ +/* + * CustomMessageDialog.vala + * + * Copyright 2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + + +using Gtk; +using Gee; + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.JsonHelper; +using TeeJee.ProcessHelper; +using TeeJee.GtkHelper; +using TeeJee.System; +using TeeJee.Misc; + +public class CustomMessageDialog : Gtk.Dialog { + + private Gtk.Box vbox_main; + private Gtk.Label lbl_msg; + private Gtk.ScrolledWindow sw_msg; + private Gtk.Button btn_ok; + private Gtk.Button btn_cancel; + private Gtk.Button btn_yes; + private Gtk.Button btn_no; + + private string msg_title; + private string msg_body; + private Gtk.MessageType msg_type; + private Gtk.ButtonsType buttons_type; + + public CustomMessageDialog( + string _msg_title, string _msg_body, + Gtk.MessageType _msg_type, Window? parent, Gtk.ButtonsType _buttons_type) { + + set_transient_for(parent); + set_modal(true); + + msg_title = _msg_title; + msg_body = _msg_body; + msg_type = _msg_type; + buttons_type = _buttons_type; + + init_window(); + + //lbl_msg.label += string.nfill(4000, 'n'); + + lbl_msg.expand = true; + sw_msg.expand = true; + sw_msg.vscrollbar_policy = PolicyType.NEVER; + + //log_debug("0: label=%dx%d".printf(lbl_msg.get_allocated_width(), lbl_msg.get_allocated_height())); + //log_debug("0: scroll=%dx%d".printf(sw_msg.get_allocated_width(), sw_msg.get_allocated_height())); + + sw_msg.set_size_request(500, 150); // sets minimum size + + //log_debug("0: label=%dx%d".printf(lbl_msg.get_allocated_width(), lbl_msg.get_allocated_height())); + //log_debug("0: scroll=%dx%d".printf(sw_msg.get_allocated_width(), sw_msg.get_allocated_height())); + + show_all(); + + //log_debug("1: label=%dx%d".printf(lbl_msg.get_allocated_width(), lbl_msg.get_allocated_height())); + //log_debug("1: scroll=%dx%d".printf(sw_msg.get_allocated_width(), sw_msg.get_allocated_height())); + + if (lbl_msg.get_allocated_height() > 400){ + sw_msg.vscrollbar_policy = PolicyType.AUTOMATIC; + sw_msg.set_size_request(500, 400); + //gtk_do_events(); + //this.set_position(WindowPosition.CENTER); + } + + //log_debug("1: label=%dx%d".printf(lbl_msg.get_allocated_width(), lbl_msg.get_allocated_height())); + //log_debug("1: scroll=%dx%d".printf(sw_msg.get_allocated_width(), sw_msg.get_allocated_height())); + } + + public void init_window () { + title = ""; + + window_position = WindowPosition.CENTER_ON_PARENT; + icon = get_app_icon(16); + resizable = false; + deletable = false; + skip_taskbar_hint = true; + skip_pager_hint = true; + + //vbox_main + vbox_main = get_content_area () as Gtk.Box; + vbox_main.margin = 6; + + //hbox_contents + var hbox_contents = new Gtk.Box(Orientation.HORIZONTAL, 6); + hbox_contents.margin = 6; + vbox_main.add (hbox_contents); + + string icon_name = "dialog-info"; + + switch(msg_type){ + case Gtk.MessageType.INFO: + icon_name = "dialog-info"; + break; + case Gtk.MessageType.WARNING: + icon_name = "dialog-warning"; + break; + case Gtk.MessageType.QUESTION: + icon_name = "dialog-question"; + break; + case Gtk.MessageType.ERROR: + icon_name = "dialog-error"; + break; + } + + // image ---------------- + + var img = new Image.from_icon_name(icon_name, Gtk.IconSize.DIALOG); + img.margin_right = 12; + hbox_contents.add(img); + + // label ------------------- + + var text = "%s\n\n%s".printf( + escape_html(msg_title), + escape_html(msg_body)); + lbl_msg = new Gtk.Label(text); + lbl_msg.xalign = 0.0f; + lbl_msg.yalign = 0.0f; + lbl_msg.max_width_chars = 70; + lbl_msg.wrap = true; + lbl_msg.wrap_mode = Pango.WrapMode.WORD_CHAR; + lbl_msg.use_markup = true; + lbl_msg.margin_right = 25; + + //sw_msg + sw_msg = new Gtk.ScrolledWindow(null, null); + //sw_msg.set_shadow_type (ShadowType.ETCHED_IN); + sw_msg.add (lbl_msg); + sw_msg.hscrollbar_policy = PolicyType.NEVER; + sw_msg.vscrollbar_policy = PolicyType.NEVER; + //sw_msg.set_size_request(500, 400); + hbox_contents.add(sw_msg); + + // actions ------------------------- + + var action_area = get_action_area () as Gtk.Box; + action_area.margin_top = 12; + + switch(buttons_type){ + case Gtk.ButtonsType.OK: + btn_ok = (Gtk.Button) add_button (_("OK"), Gtk.ResponseType.OK); + btn_ok.grab_focus(); + break; + case Gtk.ButtonsType.OK_CANCEL: + btn_ok = (Gtk.Button) add_button (_("OK"), Gtk.ResponseType.OK); + btn_cancel = (Gtk.Button) add_button (_("Cancel"), Gtk.ResponseType.CANCEL); + btn_ok.grab_focus(); + break; + case Gtk.ButtonsType.YES_NO: + btn_yes = (Gtk.Button) add_button (_("Yes"), Gtk.ResponseType.YES); + btn_no = (Gtk.Button) add_button (_("No"), Gtk.ResponseType.NO); + btn_yes.grab_focus(); + break; + + } + } +} + + diff --git a/src/Utility/Gtk/DonationWindow.vala b/src/Utility/Gtk/DonationWindow.vala new file mode 100644 index 0000000..36cc355 --- /dev/null +++ b/src/Utility/Gtk/DonationWindow.vala @@ -0,0 +1,145 @@ +/* + * DonationWindow.vala + * + * Copyright 2012-2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +using Gtk; + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.JsonHelper; +using TeeJee.ProcessHelper; +using TeeJee.System; +using TeeJee.Misc; +using TeeJee.GtkHelper; + +public class DonationWindow : Dialog { + + private string username = ""; + + public DonationWindow() { + + set_title(_("Donate")); + window_position = WindowPosition.CENTER_ON_PARENT; + set_destroy_with_parent (true); + set_modal (true); + set_deletable(true); + set_skip_taskbar_hint(false); + set_default_size (500, 20); + icon = get_app_icon(16); + + //vbox_main + var vbox_main = get_content_area(); + vbox_main.margin = 6; + vbox_main.spacing = 6; + //vbox_main.homogeneous = false; + + //get_action_area().visible = false; + + string msg = _("Did you find this application useful?\n\nYou can buy me a coffee or make a donation via PayPal to show your support.\n\nThis application includes a few extra features for people who have contributed to the project through donations, translations, etc. You can make a donation for $10 or more via PayPal to receive the plugins by email. Your contributions will help keep the project alive and support future development.\n\nThanks,\nTony George"); + + var label = new Gtk.Label(msg); + label.wrap = true; + label.wrap_mode = Pango.WrapMode.WORD; + label.max_width_chars = 50; + label.xalign = 0.0f; + label.margin_bottom = 6; + + var scrolled = new Gtk.ScrolledWindow(null, null); + scrolled.hscrollbar_policy = PolicyType.NEVER; + scrolled.vscrollbar_policy = PolicyType.NEVER; + scrolled.add (label); + vbox_main.add(scrolled); + + /*var hbox = new Gtk.Box(Orientation.HORIZONTAL, 6); + hbox.margin_top = 24; + vbox_main.pack_start(hbox, false, false, 0); + + var bbox = new Gtk.ButtonBox(Orientation.HORIZONTAL); + //bbox.set_layout(Gtk.ButtonBoxStyle.EXPAND); + bbox.set_spacing(6); + bbox.set_homogeneous(false); + hbox.add(bbox); + * */ + + if (get_user_id_effective() == 0){ + username = get_username(); + } + + // donation_features + var button = new Gtk.LinkButton.with_label("", _("Donation Features")); + button.set_tooltip_text("https://github.com/teejee2008/polo/wiki/Donation-Features"); + vbox_main.add(button); + button.clicked.connect(() => { + xdg_open("https://github.com/teejee2008/polo/wiki/Donation-Features", username); + }); + + // donate paypal + button = new Gtk.LinkButton.with_label("", _("Donate with PayPal")); + button.set_tooltip_text("Donate to: teejeetech@gmail.com"); + vbox_main.add(button); + button.clicked.connect(() => { + xdg_open("https://www.paypal.com/cgi-bin/webscr?business=teejeetech@gmail.com&cmd=_xclick¤cy_code=USD&amount=10&item_name=Polo%20Donation", username); + }); + + // patreon + button = new Gtk.LinkButton.with_label("", _("Become a Patron")); + button.set_tooltip_text("https://www.patreon.com/bePatron?u=3059450"); + vbox_main.add(button); + button.clicked.connect(() => { + xdg_open("https://www.patreon.com/bePatron?u=3059450", username); + }); + + // issue tracker + button = new Gtk.LinkButton.with_label("", _("Issue Tracker ~ Report Issues, Request Features, Ask Questions")); + button.set_tooltip_text("https://github.com/teejee2008/polo/issues"); + vbox_main.add(button); + button.clicked.connect(() => { + xdg_open("https://github.com/teejee2008/polo/issues", username); + }); + + // wiki + button = new Gtk.LinkButton.with_label("", _("Wiki ~ Documentation & Help")); + button.set_tooltip_text("https://github.com/teejee2008/polo/wiki"); + vbox_main.add(button); + button.clicked.connect(() => { + xdg_open("https://github.com/teejee2008/polo/wiki", username); + }); + + // website + button = new Gtk.LinkButton.with_label("", _("Website ~ teejeetech.in")); + button.set_tooltip_text("http://www.teejeetech.in"); + vbox_main.add(button); + button.clicked.connect(() => { + xdg_open("http://www.teejeetech.in", username); + }); + + // close window + button = new Gtk.LinkButton.with_label("", _("Close Window")); + vbox_main.add(button); + button.clicked.connect(() => { + this.destroy(); + }); + + this.show_all(); + } +} + diff --git a/src/Utility/Gtk/ExtendedTreeView.vala b/src/Utility/Gtk/ExtendedTreeView.vala new file mode 100644 index 0000000..9caa41a --- /dev/null +++ b/src/Utility/Gtk/ExtendedTreeView.vala @@ -0,0 +1,128 @@ + +/* + * ExtendedTreeView.vala + * + * Copyright 2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + + +using Gtk; +using TeeJee.Logging; + +public class ExtendedTreeView : Gtk.TreeView{ + + private Gtk.TreePath? blocked_selection_path = null; + + public ExtendedTreeView (){ + /* Allow multiple selections */ + //Gtk.TreeSelection selection = this.get_selection (); + //selection.set_mode (Gtk.SelectionMode.MULTIPLE); + + //this.button_press_event.connect (on_button_press_event); + //this.button_release_event.connect (on_button_release_event); + } + + private bool on_button_press_event (Gdk.EventButton event){ + + log_debug("on_button_press_event"); + + /*if (event.button == 1) + return block_selection (event);*/ + + bool control_pressed = (event.state & Gdk.ModifierType.CONTROL_MASK) != 0; + bool shift_pressed = (event.state & Gdk.ModifierType.SHIFT_MASK) != 0; + bool mouse_left_pressed = (event.state & Gdk.ModifierType.BUTTON1_MASK) != 0; + + if (control_pressed){ log_debug("control_pressed"); } + if (shift_pressed){ log_debug("shift_pressed"); } + if (mouse_left_pressed){ log_debug("mouse_left_pressed"); } + + if (control_pressed){ + //set_as_drag_source(true); + this.get_selection().set_select_function ((sel, mod, path, cursel) => { return false; }); + //return block_selection(event); + } + + //if (control_pressed){ + // return true; + //} + + /*switch (keyval) { + case Gdk.Key.D: + + return true; + break; + }*/ + + + // not handled + return false; + } + + private bool on_button_release_event (Gdk.EventButton event){ + + log_debug("on_button_release_event"); + + /* re-enable selection */ + Gtk.TreeSelection selection = this.get_selection (); + selection.set_select_function ((sel, mod, path, cursel) => { return true; }); + + Gtk.TreePath? path; + Gtk.TreeViewColumn? column; + bool valid = this.get_path_at_pos ((int)event.x, (int)event.y, out path, out column, null, null); + + if (valid && + this.blocked_selection_path != null && + path.compare (this.blocked_selection_path) == 0 && // equal paths + !(event.x == 0.0 && event.y == 0.0)) // a strange case + { + this.set_cursor (path, column, false); + } + + this.blocked_selection_path = null; + + // not handled + return false; + } + + private bool block_selection (Gdk.EventButton event){ + + /* Here we intercept mouse clicks on selected items, so that we can + drag multiple items without the click selecting only one item. */ + + Gtk.TreePath? path; + bool valid = this.get_path_at_pos ((int)event.x, (int)event.y, out path, null, null, null); + Gtk.TreeSelection selection = this.get_selection (); + + if (valid && + event.type == Gdk.EventType.BUTTON_PRESS && + ! (bool)(event.state & (Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)) && + selection.path_is_selected (path)) + { + /* Disable the selection */ + selection.set_select_function ((sel, mod, path, cursel) => { return false; }); + this.blocked_selection_path = path; + } + + // not handled + return false; + } +} + diff --git a/src/Utility/Gtk/GtkHelper.vala b/src/Utility/Gtk/GtkHelper.vala new file mode 100644 index 0000000..1e4c97a --- /dev/null +++ b/src/Utility/Gtk/GtkHelper.vala @@ -0,0 +1,1270 @@ + + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.JsonHelper; +using TeeJee.ProcessHelper; +using TeeJee.System; +using TeeJee.Misc; + +namespace TeeJee.GtkHelper{ + + using Gtk; + + // messages ----------- + + public void show_err_log(Gtk.Window parent, bool disable_log = true){ + if ((err_log != null) && (err_log.length > 0)){ + gtk_messagebox(_("Error"), err_log, parent, true); + } + + if (disable_log){ + err_log_disable(); + } + } + + public void gtk_do_events (){ + + /* Do pending events */ + + while(Gtk.events_pending ()) + Gtk.main_iteration (); + } + + public void gtk_set_busy (bool busy, Gtk.Window win) { + + /* Show or hide busy cursor on window */ + + Gdk.Cursor? cursor = null; + + if (busy){ + cursor = new Gdk.Cursor.from_name(Gdk.Display.get_default(), "wait"); + } + else{ + cursor = new Gdk.Cursor.from_name(Gdk.Display.get_default(), "default"); + } + + var window = win.get_window(); + + if (window != null) { + window.set_cursor (cursor); + } + + gtk_do_events(); + } + + public void set_pointer_cursor_for_eventbox(Gtk.EventBox ebox){ + + var cursor = new Gdk.Cursor.from_name(Gdk.Display.get_default(), "pointer"); + + if (ebox.get_realized()){ + ebox.get_window().set_cursor(cursor); + } + else{ + ebox.realize.connect(()=>{ + ebox.get_window().set_cursor(cursor); + }); + } + } + + public void gtk_messagebox( + string title, string message, Gtk.Window? parent_win, bool is_error = false){ + + /* Shows a simple message box */ + + var type = Gtk.MessageType.INFO; + if (is_error){ + type = Gtk.MessageType.ERROR; + } + else{ + type = Gtk.MessageType.INFO; + } + + /*var dlg = new Gtk.MessageDialog.with_markup(null, Gtk.DialogFlags.MODAL, type, Gtk.ButtonsType.OK, message); + dlg.title = title; + dlg.set_default_size (200, -1); + if (parent_win != null){ + dlg.set_transient_for(parent_win); + dlg.set_modal(true); + } + dlg.run(); + dlg.destroy();*/ + + var dlg = new CustomMessageDialog(title,message,type,parent_win, Gtk.ButtonsType.OK); + dlg.run(); + dlg.destroy(); + } + + public Gtk.ResponseType gtk_messagebox_yes_no( + string title, string message, Gtk.Window? parent_win, bool is_warning = false){ + + /* Shows a simple message box */ + + var type = Gtk.MessageType.INFO; + if (is_warning){ + type = Gtk.MessageType.WARNING; + } + + var dlg = new CustomMessageDialog(title,message,type,parent_win, Gtk.ButtonsType.YES_NO); + int response = dlg.run(); + dlg.destroy(); + + return (Gtk.ResponseType) response; + } + + public string? gtk_inputbox( + string title, string message, Gtk.Window? parent_win, bool mask_password = false, string default_text = ""){ + + /* Shows a simple input prompt */ + + //vbox_main + Gtk.Box vbox_main = new Gtk.Box(Orientation.VERTICAL, 0); + vbox_main.margin = 0; + + //lbl_input + Gtk.Label lbl_input = new Gtk.Label(title); + lbl_input.xalign = 0.0f; + lbl_input.label = message; + + //txt_input + Gtk.Entry txt_input = new Gtk.Entry(); + txt_input.margin_top = 3; + txt_input.set_visibility(!mask_password); + txt_input.text = default_text; + + //create dialog + var dlg = new Gtk.Dialog.with_buttons(title, parent_win, DialogFlags.MODAL); + dlg.title = title; + dlg.set_default_size (300, -1); + if (parent_win != null){ + dlg.set_transient_for(parent_win); + dlg.set_modal(true); + } + + //add widgets + var content = (Box) dlg.get_content_area (); + vbox_main.pack_start (lbl_input, false, true, 0); + vbox_main.pack_start (txt_input, false, true, 0); + content.add(vbox_main); + content.margin = 6; + + //add buttons + var actions = (Box) dlg.get_action_area (); + dlg.add_button(_("OK"),Gtk.ResponseType.OK); + dlg.add_button(_("Cancel"),Gtk.ResponseType.CANCEL); + //actions.margin = 6; + actions.margin_top = 12; + + //keyboard shortcuts + txt_input.key_press_event.connect ((w, event) => { + if (event.keyval == 65293) { + dlg.response(Gtk.ResponseType.OK); + return true; + } + return false; + }); + + dlg.show_all(); + int response = dlg.run(); + string input_text = txt_input.text; + dlg.destroy(); + + if (response == Gtk.ResponseType.CANCEL){ + return null; + } + else{ + return input_text; + } + } + + public void wait_and_close_window(int milliseconds, Gtk.Window window){ + gtk_do_events(); + int millis = 0; + while(millis < milliseconds){ + sleep(200); + millis += 200; + gtk_do_events(); + } + window.destroy(); + } + + public void gtk_show(Gtk.Widget widget){ + widget.set_no_show_all(false); + widget.show_all(); + } + + public void gtk_hide(Gtk.Widget widget){ + widget.set_no_show_all(true); + widget.hide(); + } + + public void gtk_suppress_context_menu(Gtk.Widget widget){ + + // connect signal for shift+F10 + widget.popup_menu.connect(() => { + return true; // suppress right-click menu + }); + + // connect signal for right-click + widget.button_press_event.connect((w, event) => { + if (event.button == 3) { + return true; // suppress right-click menu + } + return false; + }); + } + + public TreeIter gtk_get_iter_next (Gtk.TreeModel model, Gtk.TreeIter iter_find){ + + bool return_next = false; + + TreeIter iter; + bool iterExists = model.get_iter_first (out iter); + while (iterExists){ + if (return_next){ + return iter; + } + else if (iter == iter_find){ + return_next = true; + } + iterExists = model.iter_next (ref iter); + } + + return iter_find; + } + + public TreeIter gtk_get_iter_prev (Gtk.TreeModel model, Gtk.TreeIter iter_find){ + + TreeIter iter_prev = iter_find; + + TreeIter iter; + bool iterExists = model.get_iter_first (out iter); + while (iterExists){ + if (iter == iter_find){ + return iter_prev; + } + iter_prev = iter; + iterExists = model.iter_next (ref iter); + } + + return iter_find; + } + + // combo --------- + + public bool gtk_combobox_set_value (ComboBox combo, int index, string val){ + + /* Conveniance function to set combobox value */ + + TreeIter iter; + string comboVal; + TreeModel model = (TreeModel) combo.model; + + bool iterExists = model.get_iter_first (out iter); + while (iterExists){ + model.get(iter, 1, out comboVal); + if (comboVal == val){ + combo.set_active_iter(iter); + return true; + } + iterExists = model.iter_next (ref iter); + } + + return false; + } + + public string gtk_combobox_get_value (ComboBox combo, int index, string default_value){ + + /* Conveniance function to get combobox value */ + + if ((combo.model == null) || (combo.active < 0)) { return default_value; } + + TreeIter iter; + string val = ""; + combo.get_active_iter (out iter); + TreeModel model = (TreeModel) combo.model; + model.get(iter, index, out val); + + return val; + } + + public GLib.Object gtk_combobox_get_selected_object ( + ComboBox combo, + int index, + GLib.Object default_value){ + + /* Conveniance function to get combobox value */ + + if ((combo.model == null) || (combo.active < 0)) { return default_value; } + + TreeIter iter; + GLib.Object val = null; + combo.get_active_iter (out iter); + TreeModel model = (TreeModel) combo.model; + model.get(iter, index, out val); + + return val; + } + + public int gtk_combobox_get_value_enum (ComboBox combo, int index, int default_value){ + + /* Conveniance function to get combobox value */ + + if ((combo.model == null) || (combo.active < 0)) { return default_value; } + + TreeIter iter; + int val; + combo.get_active_iter (out iter); + TreeModel model = (TreeModel) combo.model; + model.get(iter, index, out val); + + return val; + } + + // icon ------- + + public Gdk.Pixbuf? get_app_icon(int icon_size, string format = ".png"){ + + var img_icon = get_shared_icon(AppShortName, AppShortName + format,icon_size,"pixmaps"); + if (img_icon != null){ + return img_icon.pixbuf; + } + else{ + return null; + } + } + + public Gtk.Image? get_shared_icon( + string icon_name, + string fallback_icon_file_name, + int icon_size, + string icon_directory = AppShortName + "/images"){ + + Gdk.Pixbuf pix_icon = null; + Gtk.Image img_icon = null; + + if ((icon_name.length == 0) && (fallback_icon_file_name.length == 0)){ + return null; + } + + try { + if (icon_name.length > 0) { + + Gtk.IconTheme icon_theme = Gtk.IconTheme.get_default(); + + pix_icon = icon_theme.load_icon_for_scale ( + icon_name, Gtk.IconSize.MENU, icon_size, Gtk.IconLookupFlags.FORCE_SIZE); + } + } + catch (Error e) { + log_warning (e.message); + } + + if (fallback_icon_file_name.length == 0){ return null; } + + string fallback_icon_file_path = "/usr/share/%s/%s".printf(icon_directory, fallback_icon_file_name); + + if (pix_icon == null){ + try { + pix_icon = new Gdk.Pixbuf.from_file_at_size (fallback_icon_file_path, icon_size, icon_size); + } catch (Error e) { + log_warning (e.message); + } + } + + if (pix_icon == null){ + log_warning (_("Missing Icon") + ": '%s', '%s'".printf(icon_name, fallback_icon_file_path)); + } + else{ + img_icon = new Gtk.Image.from_pixbuf(pix_icon); + } + + return img_icon; + } + + public Gdk.Pixbuf? get_gicon( + GLib.Icon gicon, + int icon_size){ + + Gdk.Pixbuf pix_icon = null; + Gtk.Image img_icon = null; + + try { + Gtk.IconTheme icon_theme = Gtk.IconTheme.get_default(); + + pix_icon = icon_theme.lookup_by_gicon ( + gicon,icon_size , Gtk.IconLookupFlags.FORCE_SIZE).load_icon(); + + } catch (Error e) { + //log_error (e.message); + } + + return pix_icon; + } + + public Gdk.Pixbuf? get_shared_icon_pixbuf(string icon_name, + string fallback_file_name, + int icon_size, + string icon_directory = AppShortName + "/images"){ + + var img = get_shared_icon(icon_name, fallback_file_name, icon_size, icon_directory); + var pixbuf = (img == null) ? null : img.pixbuf; + return pixbuf; + } + + public Gtk.Image? gtk_image_from_pixbuf(Gdk.Pixbuf? pixbuf) { + + if (pixbuf != null){ + return new Gtk.Image.from_pixbuf(pixbuf); + } + else{ + return null; + } + } + + public int gtk_icon_size_to_index(Gtk.IconSize icon_size){ + + switch(icon_size){ + case Gtk.IconSize.MENU: + case Gtk.IconSize.BUTTON: + case Gtk.IconSize.SMALL_TOOLBAR: + return 1; // 16px + case Gtk.IconSize.LARGE_TOOLBAR: + return 2; // 24px + case Gtk.IconSize.DND: + return 3; // 32px + case Gtk.IconSize.DIALOG: + return 4; // 48px + default: + return 1; + } + } + + public Gtk.IconSize gtk_index_to_icon_size(int icon_size_index){ + + switch(icon_size_index){ + case 1: + return Gtk.IconSize.SMALL_TOOLBAR; + case 2: + return Gtk.IconSize.LARGE_TOOLBAR; + case 3: + return Gtk.IconSize.DND; + case 4: + return Gtk.IconSize.DIALOG; + default: + return Gtk.IconSize.SMALL_TOOLBAR; + } + } + + public Gtk.IconSize gtk_width_to_icon_size(int icon_width){ + + Gtk.IconSize icon_size = Gtk.IconSize.MENU; + + if (icon_width <= 16){ + icon_size = Gtk.IconSize.MENU; + } + else if (icon_width <= 24){ + icon_size = Gtk.IconSize.LARGE_TOOLBAR; + } + else if (icon_width <= 32){ + icon_size = Gtk.IconSize.DND; + } + else if (icon_width <= 48){ + icon_size = Gtk.IconSize.DIALOG; + } + else{ + icon_size = Gtk.IconSize.MENU; + } + + return icon_size; + } + + + + // styles ---------------- + + public static int CSS_AUTO_CLASS_INDEX = 0; + public static void gtk_apply_css(Gtk.Widget[] widgets, string css_style){ + var css_provider = new Gtk.CssProvider(); + var css = ".style_%d { %s }".printf(++CSS_AUTO_CLASS_INDEX, css_style); + try { + css_provider.load_from_data(css,-1); + } catch (GLib.Error e) { + warning(e.message); + } + + foreach(var widget in widgets){ + + widget.get_style_context().add_provider( + css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION); + + widget.get_style_context().add_class("style_%d".printf(CSS_AUTO_CLASS_INDEX)); + } + + /* + css_style sample format: + + padding-left: 1px; padding-right: 1px; + + https://developer.gnome.org/gtk3/stable/chap-css-overview.html + + */ + } + + public static void gtk_apply_css_globally(string css_style){ + var provider = new Gtk.CssProvider(); + var css = css_style; + + try { + provider.load_from_data(css,-1); + } + catch (GLib.Error e) { + warning(e.message); + } + + var screen = Gdk.Screen.get_default(); + Gtk.StyleContext.add_provider_for_screen(screen, provider, STYLE_PROVIDER_PRIORITY_USER); + + /* + css_style sample format: + + GtkLinkButton { padding-left: 1px; padding-right: 1px;} + + https://developer.gnome.org/gtk3/stable/chap-css-overview.html + + */ + } + + // treeview ----------------- + + public int gtk_treeview_model_count(TreeModel model){ + int count = 0; + TreeIter iter; + if (model.get_iter_first(out iter)){ + count++; + while(model.iter_next(ref iter)){ + count++; + } + } + return count; + } + + public void gtk_stripe_row(Gtk.CellRenderer cell, + bool odd_row, string odd_color = "#F4F6F7", string even_color = "#FFFFFF"){ + + if (cell is Gtk.CellRendererText){ + (cell as Gtk.CellRendererText).background = odd_row ? odd_color : even_color; + } + else if (cell is Gtk.CellRendererPixbuf){ + (cell as Gtk.CellRendererPixbuf).cell_background = odd_row ? odd_color : even_color; + } + } + + public void gtk_treeview_redraw(Gtk.TreeView treeview){ + var model = treeview.model; + treeview.model = null; + treeview.model = model; + } + + // menu + + public Gtk.SeparatorMenuItem gtk_menu_add_separator(Gtk.Menu menu){ + + Gdk.RGBA gray = Gdk.RGBA(); + gray.parse ("rgba(200,200,200,1)"); + + // separator + var menu_item = new Gtk.SeparatorMenuItem(); + //menu_item.override_color (StateFlags.NORMAL, gray); + menu.append(menu_item); + + return menu_item; + } + + public Gtk.MenuItem gtk_menu_add_item( + Gtk.Menu menu, string label, string tooltip, + Gtk.Image? icon_image, Gtk.SizeGroup? sg_icon = null, Gtk.SizeGroup? sg_label = null){ + + //log_debug("gtk_menu_add_item()"); + + var menu_item = new Gtk.MenuItem(); + + var box = new Gtk.Box(Orientation.HORIZONTAL, 3); + + // add icon + + if (icon_image == null){ + var dummy = new Gtk.Label(""); + box.add(dummy); + + if (sg_icon != null){ + sg_icon.add_widget(dummy); + } + } + else{ + box.add(icon_image); + + if (sg_icon != null){ + sg_icon.add_widget(icon_image); + } + } + + // add label + + var lbl = new Gtk.Label(label); + lbl.xalign = 0.0f; + lbl.margin_right = 6; + lbl.set_use_markup(true); + box.add(lbl); + + if (sg_label != null){ + sg_label.add_widget(lbl); + } + + box.set_tooltip_text(tooltip); + + menu_item.add(box); + menu.append(menu_item); + + menu_item.show_all(); + + //log_debug("gtk_menu_add_item(): done"); + + return menu_item; + } + + public Gtk.RadioMenuItem? gtk_menu_add_radio_item(Gtk.Menu menu, string label, string tooltip, Gtk.RadioMenuItem? group){ + var menu_item = new Gtk.RadioMenuItem.with_label(null, label); + menu_item.set_tooltip_text(tooltip); + if (group != null){ + menu_item.join_group(group); + } + menu.append(menu_item); + return menu_item; + } + + public Gtk.CheckMenuItem? gtk_menu_add_check_item(Gtk.Menu menu, string label, string tooltip){ + var menu_item = new Gtk.CheckMenuItem.with_label(label); + menu_item.set_tooltip_text(tooltip); + menu.append(menu_item); + return menu_item; + } + + // build ui + + public Gtk.Label gtk_box_add_header(Gtk.Box box, string text){ + var label = new Gtk.Label("" + text + ""); + label.set_use_markup(true); + label.xalign = 0.0f; + label.margin_bottom = 6; + box.add(label); + + return label; + } + + public Gtk.Box gtk_add_scrolled_box(Gtk.Box box){ + + var scrolled = new Gtk.ScrolledWindow(null, null); + scrolled.set_shadow_type (ShadowType.ETCHED_IN); + scrolled.hscrollbar_policy = PolicyType.NEVER; + scrolled.vscrollbar_policy = PolicyType.NEVER; + box.add(scrolled); + + var hbox = new Gtk.Box(Orientation.HORIZONTAL, 6); + scrolled.add(hbox); + + return hbox; + } + + public Gtk.EventBox gtk_add_event_box(Gtk.Box box){ + + var ebox = new Gtk.EventBox(); + box.add(ebox); + + set_pointer_cursor_for_eventbox(ebox); + + /* + var tt = _("Edit Path"); + img.set_tooltip_text(tt); + ebox.set_tooltip_text(tt); + + ebox.button_press_event.connect((event)=>{ + //current_view = view; + path_edit_mode = !path_edit_mode; + refresh(); + return true; + }); + */ + + return ebox; + } + + // misc + + public bool gtk_container_has_child(Gtk.Container container, Gtk.Widget widget){ + foreach(var child in container.get_children()){ + if (child == widget){ + return true; + } + } + return false; + } + + public Gee.ArrayList gtk_container_get_children(Gtk.Container container){ + var list = new Gee.ArrayList(); + foreach(var child in container.get_children()){ + list.add(child); + if (child is Gtk.Container){ + var decendants = gtk_container_get_children((Gtk.Container)child); + foreach(var decendant in decendants){ + list.add(decendant); + } + } + } + return list; + } + + public void gtk_container_remove_children(Gtk.Container container){ + container.forall ((element) => container.remove (element)); + } + + private void text_view_append(Gtk.TextView view, string text){ + TextIter iter; + view.buffer.get_end_iter(out iter); + view.buffer.insert(ref iter, text, text.length); + } + + private void text_view_prepend(Gtk.TextView view, string text){ + TextIter iter; + view.buffer.get_start_iter(out iter); + view.buffer.insert(ref iter, text, text.length); + } + + private void text_view_scroll_to_end(Gtk.TextView view){ + TextIter iter; + view.buffer.get_end_iter(out iter); + view.scroll_to_iter(iter, 0.0, false, 0.0, 0.0); + } + + private void text_view_scroll_to_start(Gtk.TextView view){ + TextIter iter; + view.buffer.get_start_iter(out iter); + view.scroll_to_iter(iter, 0.0, false, 0.0, 0.0); + } + + // file chooser ---------------- + + public Gee.ArrayList gtk_select_files(Gtk.Window? parent_window, + bool select_files = true, bool select_multiple = false, Gee.ArrayList? filters = null, Gtk.FileFilter? default_filter = null, string window_title = "", string default_path = ""){ + + + /* Example: + + var filters = new Gee.ArrayList(); + var filter = create_file_filter("All Files", { "*" }); + filters.add(filter); + filter = create_file_filter("ISO Image File (*.iso)", { "*.iso" }); + filters.add(filter); + var default_filter = filter; + + var selected_files = gtk_select_files(dummy_window, true, false, filters, default_filter); + string iso_file = (selected_files.size > 0) ? selected_files[0] : ""; + */ + + Gtk.FileChooserDialog chooser = null; + + if (select_files){ + chooser = new Gtk.FileChooserDialog((window_title.length > 0) ? window_title : _("Select File(s)"), parent_window, Gtk.FileChooserAction.OPEN, + "gtk-cancel", Gtk.ResponseType.CANCEL, "gtk-open", Gtk.ResponseType.ACCEPT); + } + else{ + chooser = new Gtk.FileChooserDialog((window_title.length > 0) ? window_title : _("Select Folder(s)"), parent_window, Gtk.FileChooserAction.SELECT_FOLDER, + "gtk-cancel", Gtk.ResponseType.CANCEL, "gtk-open", Gtk.ResponseType.ACCEPT); + } + + chooser.local_only = true; + chooser.set_modal (true); + chooser.set_select_multiple (select_multiple); + + if (default_path.length > 0){ + chooser.set_current_folder(default_path); + } + + if (filters != null){ + foreach(var filter in filters){ + chooser.add_filter(filter); + } + if (default_filter != null){ + chooser.filter = default_filter; + } + } + + var list = new Gee.ArrayList(); + + if (chooser.run() == Gtk.ResponseType.ACCEPT){ + //get file list + foreach (string item_path in chooser.get_filenames()){ + list.add(item_path); + } + } + + chooser.close(); + //dlg.destroy(); + gtk_do_events(); + + return list; + } + + + public Gtk.FileFilter create_file_filter(string group_name, string[] patterns) { + var filter = new Gtk.FileFilter (); + filter.set_filter_name(group_name); + foreach(string pattern in patterns) { + filter.add_pattern (pattern); + } + return filter; + } + + // utility ------------------ + + // add_notebook + private Gtk.Notebook add_notebook( + Gtk.Box box, bool show_tabs = true, bool show_border = true){ + + // notebook + var book = new Gtk.Notebook(); + book.margin = 0; + book.show_tabs = show_tabs; + book.show_border = show_border; + + box.pack_start(book, true, true, 0); + + return book; + } + + // add_tab + private Gtk.Box add_tab( + Gtk.Notebook book, string title, int margin = 12, int spacing = 6){ + + // label + var label = new Gtk.Label(title); + + // vbox + var vbox = new Gtk.Box(Gtk.Orientation.VERTICAL, spacing); + vbox.margin = margin; + book.append_page (vbox, label); + + return vbox; + } + + // add_treeview + private Gtk.TreeView add_treeview(Gtk.Box box, + Gtk.SelectionMode selection_mode = Gtk.SelectionMode.SINGLE){ + + // TreeView + var treeview = new Gtk.TreeView(); + treeview.get_selection().mode = selection_mode; + treeview.set_rules_hint (true); + treeview.show_expanders = true; + treeview.enable_tree_lines = true; + + // ScrolledWindow + var scrollwin = new Gtk.ScrolledWindow(null, null); + scrollwin.set_shadow_type (ShadowType.ETCHED_IN); + scrollwin.add (treeview); + scrollwin.expand = true; + box.add(scrollwin); + + return treeview; + } + + // add_column_text + private Gtk.TreeViewColumn add_column_text( + Gtk.TreeView treeview, string title, out Gtk.CellRendererText cell){ + + // TreeViewColumn + var col = new Gtk.TreeViewColumn(); + col.title = title; + + cell = new Gtk.CellRendererText(); + cell.xalign = 0.0f; + col.pack_start (cell, false); + treeview.append_column(col); + + return col; + } + + + // add_column_icon + private Gtk.TreeViewColumn add_column_icon( + Gtk.TreeView treeview, string title, out Gtk.CellRendererPixbuf cell){ + + // TreeViewColumn + var col = new Gtk.TreeViewColumn(); + col.title = title; + + cell = new Gtk.CellRendererPixbuf(); + cell.xpad = 2; + col.pack_start (cell, false); + treeview.append_column(col); + + return col; + } + + // add_column_icon_and_text + private Gtk.TreeViewColumn add_column_icon_and_text( + Gtk.TreeView treeview, string title, + out Gtk.CellRendererPixbuf cell_pix, out Gtk.CellRendererText cell_text){ + + // TreeViewColumn + var col = new Gtk.TreeViewColumn(); + col.title = title; + + cell_pix = new Gtk.CellRendererPixbuf(); + cell_pix.xpad = 2; + col.pack_start (cell_pix, false); + + cell_text = new Gtk.CellRendererText(); + cell_text.xalign = 0.0f; + col.pack_start (cell_text, false); + treeview.append_column(col); + + return col; + } + + // add_column_radio_and_text + private Gtk.TreeViewColumn add_column_radio_and_text( + Gtk.TreeView treeview, string title, + out Gtk.CellRendererToggle cell_radio, out Gtk.CellRendererText cell_text){ + + // TreeViewColumn + var col = new Gtk.TreeViewColumn(); + col.title = title; + + cell_radio = new Gtk.CellRendererToggle(); + cell_radio.xpad = 2; + cell_radio.radio = true; + cell_radio.activatable = true; + col.pack_start (cell_radio, false); + + cell_text = new Gtk.CellRendererText(); + cell_text.xalign = 0.0f; + col.pack_start (cell_text, false); + treeview.append_column(col); + + return col; + } + + // add_column_icon_radio_text + private Gtk.TreeViewColumn add_column_icon_radio_text( + Gtk.TreeView treeview, string title, + out Gtk.CellRendererPixbuf cell_pix, + out Gtk.CellRendererToggle cell_radio, + out Gtk.CellRendererText cell_text){ + + // TreeViewColumn + var col = new Gtk.TreeViewColumn(); + col.title = title; + + cell_pix = new Gtk.CellRendererPixbuf(); + cell_pix.xpad = 2; + col.pack_start (cell_pix, false); + + cell_radio = new Gtk.CellRendererToggle(); + cell_radio.xpad = 2; + cell_radio.radio = true; + cell_radio.activatable = true; + col.pack_start (cell_radio, false); + + cell_text = new Gtk.CellRendererText(); + cell_text.xalign = 0.0f; + col.pack_start (cell_text, false); + treeview.append_column(col); + + return col; + } + + // add_label_scrolled + private Gtk.Label add_label_scrolled( + Gtk.Box box, string text, + bool show_border = false, bool wrap = false, int ellipsize_chars = 40){ + + // ScrolledWindow + var scroll = new Gtk.ScrolledWindow(null, null); + scroll.hscrollbar_policy = PolicyType.NEVER; + scroll.vscrollbar_policy = PolicyType.ALWAYS; + scroll.expand = true; + box.add(scroll); + + var label = new Gtk.Label(text); + label.xalign = 0.0f; + label.yalign = 0.0f; + label.margin = 6; + label.set_use_markup(true); + scroll.add(label); + + if (wrap){ + label.wrap = true; + label.wrap_mode = Pango.WrapMode.WORD; + } + else { + label.wrap = false; + label.ellipsize = Pango.EllipsizeMode.MIDDLE; + label.max_width_chars = ellipsize_chars; + } + + if (show_border){ + scroll.set_shadow_type (ShadowType.ETCHED_IN); + } + else{ + label.margin_left = 0; + } + + return label; + } + + // add_text_view + private Gtk.TextView add_text_view( + Gtk.Box box, string text){ + + // ScrolledWindow + var scrolled = new Gtk.ScrolledWindow(null, null); + scrolled.hscrollbar_policy = PolicyType.NEVER; + scrolled.vscrollbar_policy = PolicyType.ALWAYS; + scrolled.expand = true; + box.add(scrolled); + + var view = new Gtk.TextView(); + view.wrap_mode = Gtk.WrapMode.WORD_CHAR; + view.accepts_tab = false; + view.editable = false; + view.cursor_visible = false; + view.buffer.text = text; + view.sensitive = false; + scrolled.add (view); + + return view; + } + + // add_label + private Gtk.Label add_label( + Gtk.Box box, string text, bool bold = false, + bool italic = false, bool large = false){ + + string msg = "%s".printf( + (bold ? " weight=\"bold\"" : ""), + (italic ? " style=\"italic\"" : ""), + (large ? " size=\"x-large\"" : ""), + text); + + var label = new Gtk.Label(msg); + label.set_use_markup(true); + label.xalign = 0.0f; + label.wrap = true; + label.wrap_mode = Pango.WrapMode.WORD; + box.add(label); + return label; + } + + private string format_text( + string text, + bool bold = false, bool italic = false, bool large = false){ + + string msg = "%s".printf( + (bold ? " weight=\"bold\"" : ""), + (italic ? " style=\"italic\"" : ""), + (large ? " size=\"x-large\"" : ""), + escape_html(text)); + + return msg; + } + + // add_label_header + private Gtk.Label add_label_header( + Gtk.Box box, string text, bool large_heading = false){ + + var label = add_label(box, escape_html(text), true, false, large_heading); + label.margin_bottom = 12; + return label; + } + + // add_label_subnote + private Gtk.Label add_label_subnote( + Gtk.Box box, string text){ + + var label = add_label(box, text, false, true); + label.margin_left = 6; + return label; + } + + // add_radio + private Gtk.RadioButton add_radio( + Gtk.Box box, string text, Gtk.RadioButton? another_radio_in_group){ + + Gtk.RadioButton radio = null; + + if (another_radio_in_group == null){ + radio = new Gtk.RadioButton(null); + } + else{ + radio = new Gtk.RadioButton.from_widget(another_radio_in_group); + } + + radio.label = text; + + box.add(radio); + + foreach(var child in radio.get_children()){ + if (child is Gtk.Label){ + var label = (Gtk.Label) child; + label.use_markup = true; + break; + } + } + + return radio; + } + + // add_checkbox + private Gtk.CheckButton add_checkbox( + Gtk.Box box, string text){ + + var chk = new Gtk.CheckButton.with_label(text); + chk.label = text; + box.add(chk); + + foreach(var child in chk.get_children()){ + if (child is Gtk.Label){ + var label = (Gtk.Label) child; + label.use_markup = true; + break; + } + } + + /* + chk.toggled.connect(()=>{ + chk.active; + }); + */ + + return chk; + } + + // add_spin + private Gtk.SpinButton add_spin( + Gtk.Box box, double min, double max, double val, + int digits = 0, double step = 1, double step_page = 1){ + + var adj = new Gtk.Adjustment(val, min, max, step, step_page, 0); + var spin = new Gtk.SpinButton(adj, step, digits); + spin.xalign = 0.5f; + box.add(spin); + + /* + spin.value_changed.connect(()=>{ + label.sensitive = spin.sensitive; + }); + */ + + return spin; + } + + // add_button + private Gtk.Button add_button( + Gtk.Box box, string text, string tooltip, + ref Gtk.SizeGroup? size_group, + Gtk.Image? icon = null){ + + var button = new Gtk.Button(); + box.add(button); + + button.set_label(text); + button.set_tooltip_text(tooltip); + + if (icon != null){ + button.set_image(icon); + button.set_always_show_image(true); + } + + if (size_group == null){ + size_group = new Gtk.SizeGroup(SizeGroupMode.HORIZONTAL); + } + + size_group.add_widget(button); + + return button; + } + + // add_toggle_button + private Gtk.ToggleButton add_toggle_button( + Gtk.Box box, string text, string tooltip, + ref Gtk.SizeGroup? size_group, + Gtk.Image? icon = null){ + + var button = new Gtk.ToggleButton(); + box.add(button); + + button.set_label(text); + button.set_tooltip_text(tooltip); + + if (icon != null){ + button.set_image(icon); + button.set_always_show_image(true); + } + + if (size_group == null){ + size_group = new Gtk.SizeGroup(SizeGroupMode.HORIZONTAL); + } + + size_group.add_widget(button); + + return button; + } + + // add_directory_chooser + private Gtk.Entry add_directory_chooser( + Gtk.Box box, string selected_directory, Gtk.Window parent_window){ + + // Entry + var entry = new Gtk.Entry(); + entry.hexpand = true; + //entry.margin_left = 6; + entry.secondary_icon_stock = "gtk-open"; + entry.placeholder_text = _("Enter path or browse for directory"); + box.add (entry); + + if ((selected_directory != null) && dir_exists(selected_directory)){ + entry.text = selected_directory; + } + + entry.icon_release.connect((p0, p1) => { + //chooser + var chooser = new Gtk.FileChooserDialog( + _("Select Path"), + parent_window, + FileChooserAction.SELECT_FOLDER, + "_Cancel", + Gtk.ResponseType.CANCEL, + "_Open", + Gtk.ResponseType.ACCEPT + ); + + chooser.select_multiple = false; + chooser.set_filename(selected_directory); + + if (chooser.run() == Gtk.ResponseType.ACCEPT) { + entry.text = chooser.get_filename(); + + //App.repo = new SnapshotRepo.from_path(entry.text, this); + //check_backup_location(); + } + + chooser.destroy(); + }); + + return entry; + } + + +} + diff --git a/src/Utility/Gtk/IconCache.vala b/src/Utility/Gtk/IconCache.vala new file mode 100644 index 0000000..61bdce8 --- /dev/null +++ b/src/Utility/Gtk/IconCache.vala @@ -0,0 +1,103 @@ + +/* + * IconCache.vala + * + * Copyright 2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +using TeeJee.Logging; + +public class IconCache : GLib.Object { + + public Gtk.TreeStore model = null; + //public FileItem file_item = null; + + private static Gee.HashMap cache = new Gee.HashMap(); + private static bool enabled = true; + + public static void add(string key, Gdk.Pixbuf pixbuf){ + + if (!enabled){ return; } + + if (!cache.has_key(key)){ + cache[key] = pixbuf; + } + } + + public static Gdk.Pixbuf? lookup(string key){ + + if (!enabled){ return null; } + + if (cache.has_key(key)){ + //log_debug("in cache: %s".printf(key)); + return cache[key]; + } + else{ + //log_debug("not in cache: %s".printf(key)); + } + + return null; + } + + + public static void add_icon_fileitem(Gdk.Pixbuf pixbuf, string file_path, DateTime? changed, int icon_size, + bool load_thumbnail, bool add_transparency, bool add_emblems){ + + if (!enabled){ return; } + + string key = icon_key_fileitem(file_path, changed, icon_size, load_thumbnail, add_transparency, add_emblems); + add(key, pixbuf); + } + + public static Gdk.Pixbuf? lookup_icon_fileitem(string file_path, DateTime? changed, int icon_size, + bool load_thumbnail, bool add_transparency, bool add_emblems){ + + if (!enabled){ return null; } + + string key = icon_key_fileitem(file_path, changed, icon_size, load_thumbnail, add_transparency, add_emblems); + return lookup(key); + } + + public static string icon_key_fileitem(string file_path, DateTime? changed, int icon_size, + bool load_thumbnail, bool add_transparency, bool add_emblems){ + + string txt = ""; + txt += file_path; + txt += (changed == null) ? "" : changed.to_string(); + txt += icon_size.to_string(); + txt += load_thumbnail ? "1" : "0"; + txt += add_transparency ? "1" : "0"; + txt += add_emblems ? "1" : "0"; + return txt; + } + + public static void enable(){ + enabled = true; + cache = new Gee.HashMap(); + } + + public static void disable(){ + enabled = false; + cache = new Gee.HashMap(); + } +} + + + diff --git a/src/Utility/Gtk/IconManager.vala b/src/Utility/Gtk/IconManager.vala new file mode 100644 index 0000000..ddcd322 --- /dev/null +++ b/src/Utility/Gtk/IconManager.vala @@ -0,0 +1,392 @@ +/* + * IconManager.vala + * + * Copyright 2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + + +using Gtk; +using Gee; + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.JsonHelper; +using TeeJee.ProcessHelper; +using TeeJee.GtkHelper; +using TeeJee.System; +using TeeJee.Misc; + +public class IconManager : GLib.Object { + + public static Gtk.IconTheme theme; + + public static Gee.ArrayList search_paths = new Gee.ArrayList(); + + public static void init(string[] args, string app_name){ + + log_debug("IconManager: init()"); + + search_paths = new Gee.ArrayList(); + + string binpath = file_resolve_executable_path(args[0]); + log_debug("bin_path: %s".printf(binpath)); + + // check absolute location + string path = "/usr/share/%s/images".printf(app_name); + if (dir_exists(path)){ + search_paths.add(path); + log_debug("found images directory: %s".printf(path)); + } + + // check relative location + string base_path = file_parent(file_parent(file_parent(binpath))); + if (base_path != "/"){ + log_debug("base_path: %s".printf(base_path)); + path = path_combine(base_path, path); + if (dir_exists(path)){ + search_paths.add(path); + log_debug("found images directory: %s".printf(path)); + } + } + + refresh_icon_theme(); + } + + public static void refresh_icon_theme(){ + theme = Gtk.IconTheme.get_default(); + foreach(string path in search_paths){ + theme.append_search_path(path); + } + } + + public static Gdk.Pixbuf? lookup(string icon_name, int icon_size, bool symbolic = false, bool use_hardcoded = false){ + + Gdk.Pixbuf? pixbuf = null; + + if (icon_name.length == 0){ return null; } + + if (!use_hardcoded){ + try { + pixbuf = theme.load_icon_for_scale(icon_name, icon_size, 1, Gtk.IconLookupFlags.FORCE_SIZE); + if (pixbuf != null){ return pixbuf; } + } + catch (Error e) { + log_debug(e.message); + } + } + + foreach(string search_path in search_paths){ + + foreach(string ext in new string[] { ".svg", ".png", ".jpg", ".gif"}){ + + string img_file = path_combine(search_path, icon_name + ext); + + if (file_exists(img_file)){ + + pixbuf = load_pixbuf_from_file_at_scale(img_file, icon_size); + if (pixbuf != null){ return pixbuf; } + } + } + } + + return pixbuf; + } + + public static Gtk.Image? lookup_image(string icon_name, int icon_size, bool symbolic = false, bool use_hardcoded = false){ + + if (icon_name.length == 0){ return null; } + + Gdk.Pixbuf? pix = lookup(icon_name, icon_size, symbolic, use_hardcoded); + + if (pix == null){ + pix = generic_icon_image_missing(icon_size); + } + + return new Gtk.Image.from_pixbuf(pix); + } + + public static Gdk.Pixbuf? lookup_gicon(GLib.Icon? gicon, int icon_size){ + + Gdk.Pixbuf? pixbuf = null; + + if (gicon == null){ return null; } + + try { + pixbuf = theme.lookup_by_gicon(gicon, icon_size, Gtk.IconLookupFlags.FORCE_SIZE).load_icon(); + } + catch (Error e) { + log_debug(e.message); + } + + return pixbuf; + } + + public static Gtk.Image? lookup_animation(string gif_name){ + + if (gif_name.length == 0){ return null; } + + foreach(string search_path in search_paths){ + + foreach(string ext in new string[] { ".gif" }){ + + string img_file = path_combine(search_path, gif_name + ext); + + if (file_exists(img_file)){ + + return new Gtk.Image.from_file(img_file); + } + } + } + + return null; + } + + public static Gdk.Pixbuf? add_emblem (Gdk.Pixbuf pixbuf, string icon_name, int emblem_size, + bool emblem_symbolic, Gtk.CornerType corner_type) { + + if (icon_name.length == 0){ return pixbuf; } + + Gdk.Pixbuf? emblem = null; + + var SMALL_EMBLEM_COLOR = Gdk.RGBA(); + SMALL_EMBLEM_COLOR.parse("#000000"); + SMALL_EMBLEM_COLOR.alpha = 1.0; + + var EMBLEM_PADDING = 1; + + try { + var icon_info = theme.lookup_icon (icon_name, emblem_size, Gtk.IconLookupFlags.FORCE_SIZE); + if (emblem_symbolic){ + emblem = icon_info.load_symbolic(SMALL_EMBLEM_COLOR); + } + else{ + emblem = icon_info.load_icon(); + } + } catch (GLib.Error e) { + log_error("get_icon_emblemed(): %s".printf(e.message)); + return pixbuf; + } + + if (emblem == null) + return pixbuf; + + var offset_x = EMBLEM_PADDING; + + if ((corner_type == Gtk.CornerType.BOTTOM_RIGHT) || (corner_type == Gtk.CornerType.TOP_RIGHT)){ + offset_x = pixbuf.width - emblem.width - EMBLEM_PADDING ; + } + + var offset_y = EMBLEM_PADDING; + + if ((corner_type == Gtk.CornerType.BOTTOM_LEFT) || (corner_type == Gtk.CornerType.BOTTOM_RIGHT)){ + offset_y = pixbuf.height - emblem.height - EMBLEM_PADDING ; + } + + var emblemed = pixbuf.copy(); + + emblem.composite(emblemed, + offset_x, offset_y, + emblem_size, emblem_size, + offset_x, offset_y, + 1.0, 1.0, + Gdk.InterpType.BILINEAR, 255); + + return emblemed; + } + + public static Gdk.Pixbuf? add_overlay(Gdk.Pixbuf pixbuf_base, Gdk.Pixbuf pixbuf_overlay) { + + int offset_x = (pixbuf_base.width - pixbuf_overlay.width) / 2 ; + + var offset_y = (pixbuf_base.height - pixbuf_overlay.height) / 2 ; + + var emblemed = pixbuf_base.copy(); + + pixbuf_overlay.composite(emblemed, + offset_x, offset_y, + pixbuf_overlay.width, pixbuf_overlay.height, + offset_x, offset_y, + 1.0, 1.0, + Gdk.InterpType.BILINEAR, 255); + + return emblemed; + } + + public static Gdk.Pixbuf? resize_icon(Gdk.Pixbuf pixbuf_image, int icon_size) { + + //log_debug("resize_icon()"); + + var pixbuf_empty = new Gdk.Pixbuf(Gdk.Colorspace.RGB, true, 8, icon_size, icon_size); + pixbuf_empty.fill(0x00000000); + + //log_debug("pixbuf_empty: %d, %d".printf(pixbuf_empty.width, pixbuf_empty.height)); + + var pixbuf_resized = add_overlay(pixbuf_empty, pixbuf_image); + + //log_debug("pixbuf_resized: %d, %d".printf(pixbuf_resized.width, pixbuf_resized.height)); + + copy_pixbuf_options(pixbuf_image, pixbuf_resized); + + return pixbuf_resized; + } + + public static Gdk.Pixbuf? add_transparency (Gdk.Pixbuf pixbuf, int opacity = 130) { + + var trans = pixbuf.copy(); + trans.fill((uint32) 0xFFFFFF00); + + //log_debug("add_transparency"); + + int width = pixbuf.get_width(); + int height = pixbuf.get_height(); + pixbuf.composite(trans, 0, 0, width, height, 0, 0, 1.0, 1.0, Gdk.InterpType.BILINEAR, opacity); + + return trans; + } + + public static Gdk.Pixbuf? load_pixbuf_from_file(string file_path){ + + Gdk.Pixbuf? pixbuf = null; + + try{ + // load without scaling + pixbuf = new Gdk.Pixbuf.from_file(file_path); + + // return + if (pixbuf != null){ return pixbuf; } + } + catch (Error e){ + // ignore + } + + return null; + } + + public static Gdk.Pixbuf? load_pixbuf_from_file_at_scale(string file_path, int icon_size){ + + Gdk.Pixbuf? pixbuf = null; + + int width, height; + Gdk.Pixbuf.get_file_info(file_path, out width, out height); + + if ((width <= icon_size) && (height <= icon_size)){ + + try{ + // load without scaling + pixbuf = new Gdk.Pixbuf.from_file(file_path); + + // pad to requested size + pixbuf = resize_icon(pixbuf, icon_size); + + // return + if (pixbuf != null){ return pixbuf; } + } + catch (Error e){ + // ignore + } + } + else { + try{ + + if (file_path.down().has_suffix(".gif")){ + + pixbuf = new Gdk.Pixbuf.from_file(file_path); + + int ow, oh; + get_dimensions_fit_to_box(width, height, icon_size, icon_size, out ow, out oh); + pixbuf = pixbuf.scale_simple(ow, oh, Gdk.InterpType.HYPER); + } + else{ + + // load with scaling - scale down to requested box + pixbuf = new Gdk.Pixbuf.from_file_at_scale(file_path, icon_size, icon_size, true); + } + + // pad to requested size + pixbuf = resize_icon(pixbuf, icon_size); + + // return + if (pixbuf != null){ return pixbuf; } + } + catch (Error e){ + // ignore + } + } + + return null; + } + + public static void copy_pixbuf_options(Gdk.Pixbuf source, Gdk.Pixbuf target){ + + var map = source.get_options(); + foreach(string key in map.get_keys()){ + target.set_option(key, map[key]); + } + } + + public static void get_dimensions_fit_to_box(int in_width, int in_height, int req_width, int req_height, out int out_width, out int out_height){ + + out_width = in_width; + out_height = in_height; + + if (out_width > req_width){ + out_width = req_width; + out_height = (int) (((out_width * 1.0) / in_width) * in_height); + } + + if (out_height > req_height){ + out_height = req_height; + out_width = (int) (((out_height * 1.0) / in_height) * in_width); + } + } + + public static Gdk.Pixbuf? generic_icon_image(int icon_size) { + return lookup("image-x-generic", icon_size, false); + } + + public static Gdk.Pixbuf? generic_icon_image_missing(int icon_size) { + return lookup("image-missing", icon_size, false); + } + + public static Gdk.Pixbuf? generic_icon_video(int icon_size) { + return lookup("video-x-generic", icon_size, false); + } + + public static Gdk.Pixbuf? generic_icon_file(int icon_size) { + return lookup("text-x-preview", icon_size, false); + } + + public static Gdk.Pixbuf? generic_archive_file(int icon_size) { + return lookup("package-x-generic", icon_size, false); + } + + public static Gdk.Pixbuf? generic_icon_directory(int icon_size) { + return lookup("folder", icon_size, false); + } + + public static Gdk.Pixbuf? generic_icon_iso(int icon_size) { + return lookup("media-cdrom", icon_size, false); + } + + public static Gdk.Pixbuf? generic_icon_pdf(int icon_size) { + return lookup("application-pdf", icon_size, false); + } + +} diff --git a/src/Utility/Gtk/LoadingWindow.vala b/src/Utility/Gtk/LoadingWindow.vala new file mode 100644 index 0000000..5483380 --- /dev/null +++ b/src/Utility/Gtk/LoadingWindow.vala @@ -0,0 +1,120 @@ +/* + * LoadingWindow.vala + * + * Copyright 2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + + +using Gtk; +using Gee; + +using TeeJee.Logging; +using TeeJee.FileSystem; +using TeeJee.JsonHelper; +using TeeJee.ProcessHelper; +using TeeJee.GtkHelper; +using TeeJee.System; +using TeeJee.Misc; + +public class LoadingWindow : Gtk.Window { + + private Gtk.Box vbox_main; + private Gtk.Label lbl_msg; + + private string msg_title; + private string msg_body; + private bool show_ok; + + public LoadingWindow(Gtk.Window? window, string _msg_title, string _msg_body, bool _show_ok) { + + this.set_transient_for(window); + this.set_modal(true); + this.set_type_hint(Gdk.WindowTypeHint.SPLASHSCREEN); + this.set_skip_taskbar_hint(true); + this.set_skip_pager_hint(true); + + this.window_position = WindowPosition.CENTER; + this.icon = get_app_icon(16); + this.resizable = false; + this.deletable = false; + + msg_title = _msg_title; + msg_body = _msg_body; + show_ok = _show_ok; + + init_window(); + + //show_all(); + } + + public void init_window () { + + title = ""; + + // vbox_main + vbox_main = new Gtk.Box(Orientation.HORIZONTAL, 6); + vbox_main.margin = 6; + add(vbox_main); + + // hbox_contents + var hbox_contents = new Gtk.Box(Orientation.HORIZONTAL, 6); + hbox_contents.margin = 6; + vbox_main.add (hbox_contents); + + // image ---------------- + + var spinner = new Gtk.Spinner(); + spinner.margin_right = 12; + spinner.set_size_request(48,48); + hbox_contents.add(spinner); + spinner.start(); + + // label ------------------- + + var text = "%s\n\n%s".printf( + escape_html(msg_title), + escape_html(msg_body)); + lbl_msg = new Gtk.Label(text); + lbl_msg.xalign = 0.0f; + lbl_msg.max_width_chars = 70; + lbl_msg.wrap = true; + lbl_msg.wrap_mode = Pango.WrapMode.WORD_CHAR; + lbl_msg.use_markup = true; + hbox_contents.add(lbl_msg); + + // actions ------------------------- + + var action_area = new Gtk.Box(Orientation.HORIZONTAL, 6); + action_area.margin_top = 12; + vbox_main.add(action_area); + + if (show_ok){ + + var button = new Gtk.Button.with_label(_("OK")); + action_area.add(button); + + button.clicked.connect(()=>{ + this.close(); + }); + } + } +} + + diff --git a/src/Utility/LicenseText.vala b/src/Utility/LicenseText.vala new file mode 100644 index 0000000..0846def --- /dev/null +++ b/src/Utility/LicenseText.vala @@ -0,0 +1,342 @@ + +public const string GPLv2LicenseText = """ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 2 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, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This 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. +"""; diff --git a/src/Utility/TeeJee.JsonHelper.vala b/src/Utility/TeeJee.JsonHelper.vala new file mode 100644 index 0000000..6c5b021 --- /dev/null +++ b/src/Utility/TeeJee.JsonHelper.vala @@ -0,0 +1,103 @@ + +/* + * TeeJee.JsonHelper.vala + * + * Copyright 2017 Tony George + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +using Json; + +namespace TeeJee.JsonHelper{ + + using TeeJee.Logging; + + /* Convenience functions for reading and writing JSON files */ + + public string json_get_string(Json.Object jobj, string member, string def_value){ + if (jobj.has_member(member)){ + return jobj.get_string_member(member); + } + else{ + log_debug ("Member not found in JSON object: " + member); + return def_value; + } + } + + public double json_get_double(Json.Object jobj, string member, double def_value){ + var text = json_get_string(jobj, member, def_value.to_string()); + double double_value; + if (double.try_parse(text, out double_value)){ + return double_value; + } + else{ + return def_value; + } + } + + public bool json_get_bool(Json.Object jobj, string member, bool def_value){ + if (jobj.has_member(member)){ + return bool.parse(jobj.get_string_member(member)); + } + else{ + log_debug ("Member not found in JSON object: " + member); + return def_value; + } + } + + public int json_get_int(Json.Object jobj, string member, int def_value){ + if (jobj.has_member(member)){ + return int.parse(jobj.get_string_member(member)); + } + else{ + log_debug ("Member not found in JSON object: " + member); + return def_value; + } + } + + public int64 json_get_int64(Json.Object jobj, string member, int64 def_value){ + if (jobj.has_member(member)){ + return int64.parse(jobj.get_string_member(member)); + } + else{ + log_debug ("Member not found in JSON object: " + member); + return def_value; + } + } + + public Gee.ArrayList json_get_array( + Json.Object jobj, + string member, + Gee.ArrayList def_value){ + + if (jobj.has_member(member)){ + var jarray = jobj.get_array_member(member); + var list = new Gee.ArrayList(); + foreach(var node in jarray.get_elements()){ + list.add(node.get_string()); + } + return list; + } + else{ + log_debug ("Member not found in JSON object: " + member); + return def_value; + } + } + +} diff --git a/src/aptik-gtk-uninstall b/src/aptik-gtk-uninstall new file mode 100755 index 0000000..92f6ab9 --- /dev/null +++ b/src/aptik-gtk-uninstall @@ -0,0 +1,125 @@ +#!/bin/bash + +app_name='aptik' +app_fullname='Aptik GUI' + +Reset='\e[0m' +Red='\e[1;31m' +Green='\e[1;32m' +Yellow='\e[1;33m' + +CHECK_COLOR_SUPPORT() { + colors=`tput colors` + if [ $colors -gt 1 ]; then + COLORS_SUPPORTED=0 + else + COLORS_SUPPORTED=1 + fi +} + +MSG_INFO() { + add_newline='' + if [ "$2" == 0 ]; then + add_newline='-n' + fi + + if [ $COLORS_SUPPORTED -eq 0 ]; then + echo -e ${add_newline} "[${Yellow}*${Reset}] ${Green}$1${Reset}" + else + echo -e ${add_newline} "[*] $1" + fi +} + +MSG_WARNING() { + add_newline='' + if [ "$2" == 0 ]; then + add_newline='-n' + fi + + if [ $COLORS_SUPPORTED -eq 0 ]; then + echo -e ${add_newline} "[${Red}!${Reset}] ${Yellow}$1${Reset}" + else + echo -e ${add_newline} "[!] $1" + fi +} + +MSG_ERROR() { + add_newline='' + if [ "$2" == 0 ]; then + add_newline='-n' + fi + + if [ $COLORS_SUPPORTED -eq 0 ]; then + echo -e ${add_newline} "[${Red}X${Reset}] ${Yellow}$1${Reset}" + else + echo -e ${add_newline} "[X] $1" + fi +} + +CD_PUSH() { + cd_backup=`pwd` +} + +CD_POP() { + if [ ! -z "${cd_backup}" ]; then + cd "${cd_backup}" + fi +} + +EXIT(){ + CD_POP + exit $1 +} + +WAIT_FOR_INPUT() { + echo "" + echo "Press any key to exit..." + read dummy +} + +GET_SCRIPT_PATH(){ + SCRIPTPATH="$(cd "$(dirname "$0")" && pwd)" + SCRIPTNAME=`basename $0` +} + +RUN_AS_ADMIN() { + if [ ! `id -u` -eq 0 ]; then + GET_SCRIPT_PATH + if command -v sudo >/dev/null 2>&1; then + sudo "${SCRIPTPATH}/${SCRIPTNAME}" + EXIT $? + elif command -v su >/dev/null 2>&1; then + su -c "${SCRIPTPATH}/${SCRIPTNAME}" + EXIT $? + else + echo "" + MSG_ERROR "** Uninstaller must be run as Admin (using 'sudo' or 'su') **" + echo "" + EXIT 1 + fi + fi +} + +CD_PUSH +CHECK_COLOR_SUPPORT +RUN_AS_ADMIN + +if [ ! -z "${app_name}" ]; then + rm -f "/usr/bin/${app_name}-gtk" + rm -f "/usr/bin/${app_name}-uninstall" + rm -f "/usr/share/applications/${app_name}.desktop" + rm -f "/usr/share/pixmaps/${app_name}.svg" + rm -rf "/usr/share/${app_name}" + rm -rf "/usr/share/doc/${app_name}" + rm -f /usr/share/locale/*/LC_MESSAGES/${app_name}.mo +fi + +if [ $? -eq 0 ]; then + echo "${app_fullname} was uninstalled successfully." + EXIT 0 +else + echo "Uninstalled completed (some files could not be removed)" + EXIT 1 +fi + +CD_POP diff --git a/src/aptik-gtk.desktop b/src/aptik-gtk.desktop new file mode 100644 index 0000000..1abbf10 --- /dev/null +++ b/src/aptik-gtk.desktop @@ -0,0 +1,12 @@ +[Desktop Entry] +Name=Aptik GTK +MimeType= +Exec=aptik-gtk +Type=Application +GenericName=System Migration Utility +Terminal=false +Icon=aptik-gtk +Comment=System Migration Utility +X-KDE-StartupNotify=false +Categories=System; +Name[en_IN]=Aptik GTK diff --git a/src/makefile b/src/makefile new file mode 100644 index 0000000..3b4a30a --- /dev/null +++ b/src/makefile @@ -0,0 +1,70 @@ +SHELL=/bin/bash +CFLAGS=--std=c99 + +prefix=/usr +bindir=$(prefix)/bin +sharedir=$(prefix)/share +localedir=$(sharedir)/locale +launcherdir=$(sharedir)/applications +mandir=$(sharedir)/man +man1dir=$(mandir)/man1 + +app_name=aptik-gtk +app_fullname='Aptik NG GTK' + +all: + # aptik-gtk + valac -X -D'GETTEXT_PACKAGE="${app_name}"' --Xcc="-lm" --thread \ + *.vala Gtk/*.vala Utility/Console/*.vala Utility/Gtk/*.vala Utility/*.vala \ + -o ${app_name} \ + --pkg glib-2.0 \ + --pkg gio-unix-2.0 \ + --pkg posix \ + --pkg gee-0.8 \ + --pkg json-glib-1.0 \ + --pkg vte-2.91 \ + --pkg gtk+-3.0 + +clean: + rm -rfv ../release/{source,i386,amd64,armel,armhf} + rm -rfv ../release/*.{run,deb} + rm -rfv *.c *.o *.mo + rm -fv ${app_name} + +install: + + #dirs + mkdir -p "$(DESTDIR)$(bindir)" + mkdir -p "$(DESTDIR)$(sharedir)" + mkdir -p "$(DESTDIR)$(mandir)" + mkdir -p "$(DESTDIR)$(man1dir)" + mkdir -p "$(DESTDIR)$(launcherdir)" + mkdir -p "$(DESTDIR)$(sharedir)/${app_name}" + mkdir -p "$(DESTDIR)$(sharedir)/pixmaps" + + #binary + install -m 0755 ${app_name} "$(DESTDIR)$(bindir)" + + #shared files + cp -dpr --no-preserve=ownership -t "$(DESTDIR)$(sharedir)/${app_name}" ./share/${app_name}/* + chmod --recursive 0755 $(DESTDIR)$(sharedir)/${app_name}/* + + #app icon + install -m 0755 ./share/pixmaps/${app_name}.svg "$(DESTDIR)$(sharedir)/pixmaps/" + +uninstall: + + #binary + rm -f "$(DESTDIR)$(bindir)/${app_name}" + rm -f "$(DESTDIR)$(bindir)/${app_name}-gtk" + rm -f "$(DESTDIR)$(bindir)/${app_name}-uninstall" + rm -f "$(DESTDIR)$(bindir)/${app_name}-launcher" + + #shared files + rm -rf "$(DESTDIR)$(sharedir)/${app_name}" + + #app icon + rm -f "$(DESTDIR)$(sharedir)/pixmaps/${app_name}.svg" + + #translations + rm -f $(DESTDIR)$(localedir)/*/LC_MESSAGES/${app_name}.mo diff --git a/src/share/aptik-gtk/images/backup.svg b/src/share/aptik-gtk/images/backup.svg new file mode 100644 index 0000000..85f37fe --- /dev/null +++ b/src/share/aptik-gtk/images/backup.svg @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/share/aptik-gtk/images/clock.png b/src/share/aptik-gtk/images/clock.png new file mode 100755 index 0000000000000000000000000000000000000000..6d5173bb168b089d525733175dcbeb45b0326c23 GIT binary patch literal 3062 zcmVs5QWhUNudE!A{;uvT|(R&z{=R1aHRyKiM0w=es>?{K0L?Sd(QWCys4qjRznT7 zFuhFw`1ttJ%F4>c_V#vaYisM8_Y8PCr`Ffk&nG4(7GcZu2;X0-cBXH7diwO>;2@jH zWXgp?A*j`AWZO1{VMuWtQ<5Y=obiUgYPCwmV$o-x(*FK_W@>8c7_pvW{&;l{4i3&8 z9v@$vC4ag~*o z;^xhp;>wjPqO7b8WfX*ZKXT~cZ}?Uqew{maZsI%dywmDg&J+Ld(xprA#fujotJFrI z7{mDG0OaTAi_4cU0|3g^|4Ls*0H|9J0e+oMr|TDOq0OYEq{p2*cMg)V{O_qM|HnW6 z@zI0{6HZlBRQ!tZiU1uB2LjXr0K0VQQvKg@g2XsSeNzAmF3Q;LcGoquU0z=P>$GXp zqW}N@|9|vU#J~9Biw#$;T6G6OqUR6{3;^7TrvP9^0J*ujA}1#Y*Ohon0BB3KtL7OQ zQ!-+EqT)aP_~W)acI+rX;0Ug+u1<+ZV3q(BgtW9Yq_0R#O%=(>$(RFNmX(#I#A^Yt z*=&dbiZ^0LCFeA-FT#^9Dd|Z7uF28vvo` zwbx#2Nr3jk$C(Qd@M1wbJv05vr=xaab*a^=co8S{sJo9!n~oEVBm z5d<320bm>k90V$!_C5=MWC3DBIouyVe*9^FJRSbrp+kp&yu7?$5m0q?wH5%H1r&lZ zD%`C1=@4K5AV$>1#QICejva%1S|?zU6A=;d5JAGR4*<*{aN^wpkdIz5fBt+H01PpQ zhlk&PCfA8MCpWy@!H2{z-AP`JIn2DzV;9KqkuwX)amH@ECMl5&k-1(_>>(&E2)&IZ1 zz`(0$91cANK(l~CfSHIk?fp%gHi^i{NU{*(0pJ%t;kBj~L_bbTS0AMJ4~qH;t5kV%ls0tJB@ zE8Hj^8>IE?*Q+N0O@C7W#@JDQ%$PA@x`!&CpE`BQj!KwuEdUs^fQ6tyutvmVsT>j# z0>51EvjCt0^-i8VX_MMMwNx*kozt-j(=@S4tlon`{8beG0$Tu^)<%z4RgmH+p5pi*Gcv(TSz!Cxn;z7g_ zaXu;P8Z`iPbmSx2=y^m98#Eq3Bmclq~cIhcDE*1j^4%}r5V91am$BoqF+Zja> z5VW&^g`hx`mx>2_RtgNcpr9a>qr$btQvf()L`Nd_(9qC&05I9f$4mhX9Xd1uPE-ZC z6|Nr!XV0Eh0N5;8wrrUQ4h}XN7Be`s6!J(-96o&5}O%5D$05}MAXaocVh-~Tq{?-Ll zxYyzp0K9lnS*!pk!w_I6K}-~?FeZ?gm>3u)K?Oh`0s{i&@ax>STG)#6G=*D>hhery z%*fvB*RLx*cmcytf_My~*HsoMipFKJE(Bc=_S9R#d1fya&5LIM(8r%jfBc=Ep3Xl8 zu@C|=mG%k%fuI_s5SVP>&ADMdBiwWGFeTmy04q#(A%vx{T#0?BW>Nht;2~JSaGcsD zY^k@EXhyiUcnSd5u`b}3!q_Ot(SK@VhABJ-4)~(Bg zMs_&0NDw-8e#Va$2#{vxH zaHv|VbtHzlP@W2fp&}f34uJ!~n|=EdQ6uLADx4S3_r8K4HQ_YqFIvaK&6+jqDVM)L z!7&9uAy|XZhf#aug0O`iM0rNIws^H6!ba{#9E*GOVr1sbnU~>|$pQuf1)*>DjRBqs zXT+f`SriRYSpa965EKZnVb~6D5;duJP{%XzOz+FZPk*moj>^whqp($l zV+uhNgvVB$nJR1t)>Gl0ipMY3{&*o04lQ229>#Zg@`>O;5Xz}O1n*(kwl78+u#oedzq|XH^i5wl5sx}J4Eb3;_XGX$A?5#M8lAxw6OD5a zCk;rpL*DxmJSrB>1g9i_S zx5i+}eD%f5E%S1b6BYElMT-^#VjU{m6@T7!UC++jc@#pPg`vAjudNQ(^XJd!o#|XM zt^_x@T~u!I2@|hgy|rs=n(!AtUL^Z>LF6a;>x1(W99u!2`hREKblS#q{e_soQ$&Zh zj!WjhfB#+*gVjfj7}0@n`OQ0a?06$V*YbZ6&8skUjazeG8#-^7$T!nUu;n#tlsA07 zZyq^vWP3TuE#?KlsgQDn&($V+v<0Cw-B>a&Wy-m7;lhPa5>rBp$V>DxA3uIv@2$(# zeD%c)_;i`igzMiKHf-2ZImks$a*KHZ95`^GG_iLzISkbl5}h#KkCR|ih%DK}2h=Ob zeF<@T!KYvbiXx^JLo6}HUbSk~D{O7lrncoE7dgo-F5Q3w3gu~Xbu4+L3#H#5BBSTc zo40V%q)A&?I6b0kd~jzb`2VdrGxNK{;`fY(=~5kaO=BMyLoCLeM`CM3TiVpN9ONRW z67l@aojbR*{cid4<&7ZJmRjh64B~n$WM{GrT{COetbGz^>nn$5{`v0RyAFI#TNcdE z-5{@hMojW|b=1WIEp)GA{TMlx`gKEsjgi@@$s?s#;(;r*fBq7yH zqSVeP?k92fZ!v@BdIrsH)ZiiZ=dK`kkjIMGK4aJBpgQWB#%()q%Rt@@=6Zhtz~~d00L^^N2w5h(EtDd07*qoM6N<$ Eg6mGP5&!@I literal 0 HcmV?d00001 diff --git a/src/share/aptik-gtk/images/config-users.svg b/src/share/aptik-gtk/images/config-users.svg new file mode 100644 index 0000000..a16601b --- /dev/null +++ b/src/share/aptik-gtk/images/config-users.svg @@ -0,0 +1,307 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/share/aptik-gtk/images/config.svg b/src/share/aptik-gtk/images/config.svg new file mode 100644 index 0000000..072b3a4 --- /dev/null +++ b/src/share/aptik-gtk/images/config.svg @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/share/aptik-gtk/images/donate.svg b/src/share/aptik-gtk/images/donate.svg new file mode 100755 index 0000000..28be2f6 --- /dev/null +++ b/src/share/aptik-gtk/images/donate.svg @@ -0,0 +1,458 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/share/aptik-gtk/images/download.svg b/src/share/aptik-gtk/images/download.svg new file mode 100644 index 0000000..3426e47 --- /dev/null +++ b/src/share/aptik-gtk/images/download.svg @@ -0,0 +1,368 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + diff --git a/src/share/aptik-gtk/images/drive-harddisk.png b/src/share/aptik-gtk/images/drive-harddisk.png new file mode 100755 index 0000000000000000000000000000000000000000..3f42392a72952fccb491ad7606b0729a0de84b90 GIT binary patch literal 2640 zcmV-W3a|BvP)6asIw+`rA#-yFYbKoqNwc=ib|}VZ(+E8#Zj%a6O`>P)7?m0TfcG z>o_5S^FU{nO7s*uawFHD@Bu91cV7u3rH=6L3vc}?g}ROnA9(-!Ze{lFtB{5TY*>Lb zEZ`7-JNq){cg}I*jTl!Wrff=ee*|n_3X<^-YE??^i#0Dld$w8{Xw57T3+~bbfMGU zY9D$wn}h-Wyh8WVw}5p*N=dIDfBB6@omOjW={nwc;|-?aH2u!ac-MMCQcC(O3O@@n zwSc|74i7)_7_Ys44##nnwpFj!IeFrPeEH5Vt*!7OLj~;Zb-3r=Z!sK>GHI{Z>+#}W zU*hlQcKGT2KV*Bm{mzAQATtF#{K#Vrha;?FiAHk^A=EYwY&tAFL}tIFF;N@f-?AM@wJfAGiOJ@o%?zIlOvUAV|? zw|-*r%=08qKJ^S=`26jQXV3ih58QnELp16&?*7KN-?mL51OWS;l>(MZdDnVD$A#S1 z0blv*H?R5p(VsnW)w5@xd;ZYBfBCDYmGmhOHWrXGxmm!KbHG8Kf8j-RUE`LIe{}Ke zNB2L(-Cw(tM<0KZ=l=LY7G2DQjRoY)+RXt6dGMj1FJ0!iv9W-h*(e}qHVVj@we*4j z9{vIlBOyIdhZp_L7pB1>AAR7kTNG zvkZqLF1yP?;+ z@F7PFaNRM3!4QD0cAHwQmRDDDB^L#Z$76=WSorPhSon~G0uBm)dwZK|wVHJo){0CO zFqupkjpB`2H{7sIrE+}>A2OVT!)Zvb7w=MTHJcmZ&&W&x{r-R`no=&8X=JbvJ1%6R z0M~W#CliDrXs_|AG!Igp1Fm(JDvF}TxZmDtFLtXPH&mSyOVt9db(YE z4x{SqTdE2;ebbpk<|*Zb>2!)|n%K6zQr+Y6m~OXA5L}&02>gJ+4;YO{m_36=qk&y2 zt<>I?T={Nkp>!SKdL97v6<505Zg+OvDBkgGSr(>gqU-SpI-O4OeIF?$eh{#`w@0m3 zrO{Y_Z%dg1q6qxS1b}k6lDM9O!Y`G}6s@ao2M|IagrHa~;z`MPG@{=h0IaFn}gOBg$nQiC?y>GqbQ==?Z$PK z%NVA4%ltSU?f;)&ib_s$Y9`g&!UrJIa6cIuY1i@Nc zfieXIvz-s7nd~Yd*NqeRmSvH|tJJi(EX2xOSClDWI*rXf>G&`Gcmg+<7<#T`URL@t zaUH5rrhq7lkN4|ZG6l?su(_+51TiZ+uWMQ6@1PRp!8iqr(jzmUdXx7-o0V7h66zE% z>vK{EWIl9Fr^&y~!JDY@g*(6>R98jP_D^{ie zeb(zB;rKg`9Z4w@Sy2?lWe?W1Ec3XNuB!{7D^q|m8$#ych-I-$Hl|?^h9Q%Qw{&?a zJ;E@=FpR_s@F%eaCH3Tvf-(inuOyH%nF2ITqtR#pFdB`Q8j5`1XFQJA5zS^Z@gyoI zu>~0llSs-GP$4M)!pWvm*G4gw$F_t7*xao>-E z!hC>+Wm$Nh$8b1Y3@1rwG@4je5yx=|f?zScTnoc6Xf~TGCxGS`OBJkw(sh8+giNtm zjE98bU?l}W?8y|1MO@d#9lNn*&EidlFenrX*d-g=PA4TfAI9ur@g4qhHIypAG);sq z@FzZ_(P-tQyryZCN+n7uryH+iG#ugkK0+5O#iEXa(olq^X_RJh`L5zi`qCnbBAjmA z*HXExbohY`VnMcTqYE85nau9+TyF-0K9k7=p$lwV?eGH`?To8d;-tLO=`6-?{qbTC?rAv!VWJ%*k%aYmV+-j|g&~-e| zV}F1BF461k@8d~{E_ABZ><)}%rT|^n7pEWl{oW$sz7BL9hhD#rra_}tUj!1fAk#y7 zrfE{I*U>bMPN%aLo{{4?bQ}jw)2P+zOYOc$gUnA!T9!qnT8Wk5IPC51<}xQlQN-@< zF3wE&m1=d7#Ltpk4(ZuN8(r7w_xkkv13Wq5y*IoE!_1~TzVCDS@@1ryvoF7vi|`@G zbHY}^qS0(3gkT~i7cO3)+wCf~hG-hmbsR2U{0~w}gb*|v&D?|!IiHj_4TDyz$zU+V z^E^784ugK5db2^bTt!Q1GK{7XgW-T)w~If^auw}js%<1C_p1stO{Z3?QM7G_g8_aJ zu(!L1<2Y2x6{?jAg@j+Il#=0a$Z#}VY)vr?gKD*^JjQcWa#z5df@#ufwUAOW8jlG4 zfL^ahuh&BefnBt*iWX+U#1tmF5DRy4I*piyA%5uNPkf{&aXojD8-Q5w<#IXK;pSSb zjRNLamW5?m_`Z)PCDMzNEW=U!B`<@}b*y3$t60QTm{eJXwf!MC(=;(nlWL_x7=%px zII|XpAz>I2MbpLhM_t#@HGwX4gb)~pLBTAfmP}XqLvE=n;NW4lv^pycfo-go;aUY1 z?=&ZMH}u5GQy7M^RzKvnDk|UUUH?OFsz~dH+&1@y=1dwE@G(;OUEO1f1pcy01!=em yE>LF;U0TIRU&wl~6r19%<#yc4R0000 literal 0 HcmV?d00001 diff --git a/src/share/aptik-gtk/images/edit-select-all.png b/src/share/aptik-gtk/images/edit-select-all.png new file mode 100755 index 0000000000000000000000000000000000000000..fd7d85dbf6d9e6b00293f5d4a87ff7e57efd96d5 GIT binary patch literal 479 zcmeAS@N?(olHy`uVBq!ia0vp^1|ZDA1|-9oezpTCmSQK*5Dp-y;YjHK@;M7UB8wRq zq}PKmW1Q4P8K9tKiEBhjaDG}zd16s2LwR|*US?i)adKios$PCk`s{Z$QVa}?F`h1t zAsLNtXBhe&b`Ws=zplw=mkUQ{f#`FYbwUf6ShECp0}7bEj}(dD4ClPVaw%YmvxA|@ zk^@0DyT9d$d4HZ|Vtnua=W?4#jE({=6ExN-_+DNi&MVJ2i$UV8gD}GykpMZK@9!t6 z{9L8|rqKVFX#HEi*@DVUdH1f%vpm?gF5vU|MJts9zfG`u>czwJ;6&q;WgF5rhp*t$ z6pf$jA3y8mO7+uXhM9Y}yfpNDz`ySZ^MRbQZ#lP z>snf3$7m=p>zeU}Z+zRAe&+0Gyl_H}qgR5X_f6x4Eq)Ejx1&#m7ENOK&YxdrUb-%Q z8CXfhedeo@g|^(27~0?a=FWAPrkf=1#PC2<|JXL$Z};7{#-00oXxmw7HO@7AR^K?M z9ezM6z~QA^w{1#+S#|3^`|IDUFEX&qVt93<*MzUC*{Ravh5egnHo(AG_J^T + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + diff --git a/src/share/aptik-gtk/images/item-blue.png b/src/share/aptik-gtk/images/item-blue.png new file mode 100644 index 0000000000000000000000000000000000000000..72e0e5777b4db708f4a77ee741cb4af9bf37cc82 GIT binary patch literal 594 zcmV-Y0SqxtVnoGlm)*Dw zDEJLRr7y(1G%>lP_fGC(9>+zJE^_T!4;&bVIX})E4)Cvo&0kax8Y%9NcNnKV5GvD0 zO)~6NL9tqG_rAOmsJ{MM)*SU)rDEmo`f8@=qyPW|5ucPN{s2pN|!MMF4=D&9IiW(Pp1;%R(A=+Qtvp0mCUza6496-142Aa84yB2 zIO<6_ORL#f>BqA=`w|G_+kr~M4K$dANlrgV1dt}US|goVfDEIx1R#}y=NrhFz$^x4 z(HsE45PVIDq(ZU-X}a(>^%+tX@TWLsR35ct>iM+wB`4c*{%~smg zKOoIqx&`_txVc0E4p{>2P|-!LB58ymK73sJe&ybGZ-?@vsm+`-9S(dyob&x2;J%Ce zJBY{QiCV38Sg+ULZEbBm1pwQ&f1aM6e(rQSCt(=!J86btJUKo-9=2L7XEvKD#+YJ^ zsjI6i)oQhzqobpNVHl79*2JPl)3k?;M&p}ln!BY^DM1K<5CTF7#9}ez^LZ_uPG`2a zw-3(G&rhV3;VnS5TK!;}=F4KSm~dSeoO1{vz&S?{1n_+yhG7uKSkkhr)pR<&000^R zDwWFN-rio4F$ULl;rl*3&x7ZA@O>Yy>w+c3|lu}T- zW&;4El#o(F(=_P1zPkYsLLge5QVK!{2>BC|QVL2bNGaE+Z2&CGn$G9*7rL%PDfM3f zAq30i5{t!RvXO$6l4dfQYA%=4Zf~!{Xf(QPx7%-&QnzDNN`=GWu$j$f4{X~`#N+V?0Khqi zZQJPg`@bfW$z`+ItOY?}N4kwyrj#c3_xE3yN~QOyRO&eZtX8WZyrybhDv}uAGi-rWG3W!RKiY_#j#DtCf1T`W% zqif?<_r@KGiGM)1E+ipt&^GpzX|bX71b%7lbCIy5=M&IXR2xe7rBP z-$C{^v=GtHkH@AjO&E8LB#r=pwT<8NudJumgZIv*;GS~R@Wu@@^Q6*zlWwAMMw+Mwv5V(1Bt#2fG!wgjdHlrnv%{zKnzszbtKiZ{AUt?M6^_4-1BrfO z*0!SMO4TZ@1@8cW?g9qKqSJ!|15wk?!f|alo(IQuchd9VxHe2Xi=p)K*wDr3o#y7v zTcYUIbq%#f8I%ATr66SIMM^0MDIt}Im>x$chQ2m{&lDW54wreL8UZDw1t67z6bdSA z!S@x~0CiKW6*fxgE(4Iv1*Nnpkpdv41f>y}W)ZcD_|>KY7leir>`E%t74}#IoO1+1 zAmAJ<2oMMfs1CecC^#Qq+mEXyzR&`wZ}R1MFK!6I;|U`|8I$lC2V)XJKp?n=Z`m#J zqPPbUHZ zq0kSe_1mdo{a(0}_5(m*%hlpn_GB~1o+;UC<^7Mp4xJQ1#7Me{00000NkvXXu0mjf DPZ$=4 literal 0 HcmV?d00001 diff --git a/src/share/aptik-gtk/images/item-pink.png b/src/share/aptik-gtk/images/item-pink.png new file mode 100644 index 0000000000000000000000000000000000000000..881de8a71f992d53b5bcbf80c2ac5ee4b10d0b59 GIT binary patch literal 598 zcmV-c0;&CpP)# zfFL4mZ~ZITm#uqm?#oMooku%OIR9?y_SAH3v3`X$7yv+Y1(Mwpo_)(Y2*`t_*Goqe z!1nSMBXRJ#wpg2~+^K}JFJKA_0Eo&VSfhk=Z)lUbppovS zU=3DQPM-nMc)=~7amqm@3PD8Rlmmi4H*_A}dg#=E-k>N7yTh)b5ruLJnaPlu49Y3ch~hZynZE2FRq6H33kT`> z!n0;b!nZY6Z_ZtvEwf5#lrH6H=k4M|{yHQic)0OtqjTvfKb?O!?(zXCBN#^?rAng~?DHf^CTrR~gg=FNL^UDQILam`I$@^W9!FZbMc zfU_=kx}hEL9qB1(Ek(z>pqDzRRSS$FiAZV&-Nz zn1}-a+`WBNK7F>gf8>f!b33zDE=qj>U17$DYggB^Gq=)_=?O*Fihyf%AA{$h#!@)Q zZTR0;R`QR2=Chp01pu`Nco2`hyfZy@KQS?>ch=S*51No|2eRcr)SKYN5<;VC#+zp7 zu-R(o?9LYePg zFDqbh_v>H`U>M-5$*rVU?6NFgCT z3Ez{Dfq>2t{aMUoiTb|6f z%|A7_a(o|E;hHt+lolJmX4}5kAEaYXOurtC z&)qPFUPM%58~_^9-TLb6y;Bwa00000NkvXXu0mjfV%8LD literal 0 HcmV?d00001 diff --git a/src/share/aptik-gtk/images/item-yellow.png b/src/share/aptik-gtk/images/item-yellow.png new file mode 100644 index 0000000000000000000000000000000000000000..da12bb671a3ff603da0189231f184171d1b45bdb GIT binary patch literal 593 zcmV-X0D>244F0xt(t)jqk z5k##ES_HKZX%j>cEdmLGHWGm)6oT|Ylpm!jlQ`IXWHWEZnR)Nt+u}8nBd$I0=UmRc z|KH^t4s3Ra+JeuEdG@3+aIVL^8rkNw0;ICupHGJ?gU?^72ad$v5D;mk<^GMpNc+L# zEz$PAkiV`KfO27h*~y{e)Wo}mD|brq^fHU<0H%+?liR_son05(ns;^?*eOsY_tFS} zFG4c$T8+MWJbV7u$|2jK4B)8(`ntW>d%KUEj>URRtQl~MAZ?Hpuq`P4VoSq*Q7$Y7 zGnu9Q#GD!fFsgvwqrri_(PKfZIoDtpYGi>m&%S79=u}7Wa@FUp9vXw}3j0G)PJ$31 zjQ={+pcQC~aG;s(bwt+zWW@t^&izRk8vqnq zFidi(d6u%`N7c8A(oz`F#?pzlmL?xg5ws1es*0Pnm$C6Lg-0)c-~FC+#@7JmmgJ|7 z-JS~pVQ<}0A2M)kTsh!Kkb=qS1^HnzofsU>Us4*m2B0+Z?R5EBv|gRbX7Xl(sr`PT z&=s3Zy1?lBr1kOJpTy0fY`j=j%j*_tbtr}~;|D_hy@$isn!=tv0BK9ky!dS08<{FT fluFyRp3RNFPNeEktbP{m00000NkvXXu0mjf&D9%4 literal 0 HcmV?d00001 diff --git a/src/share/aptik-gtk/images/lock.svg b/src/share/aptik-gtk/images/lock.svg new file mode 100644 index 0000000..6794afa --- /dev/null +++ b/src/share/aptik-gtk/images/lock.svg @@ -0,0 +1,93 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + diff --git a/src/share/aptik-gtk/images/package-x-generic.png b/src/share/aptik-gtk/images/package-x-generic.png new file mode 100644 index 0000000000000000000000000000000000000000..33fe8d2429decfcfb95c9319a916fa3775fbd00f GIT binary patch literal 976 zcmV;>126oEP)~E31Qd?>|hLIdRn&%)r|> zuSH3avG{p*f#*jtoV8+dzkEI2e%>koTq+@7orw`4{}2R;lp^I70A`>~0pdh9WSAjq0S#F@PO#d=!18jNvPNJ5!aktO z0)TR5$d<<%PH-1HVGtTi0K!Xe*9X=LC;$}9CO2e!OA2@;shVR4`}9sqp*N+ zgh7RHL<*^JqaCoH1(30b;ukP>5=4fqLu{6q&8M)22G1|@49TA}aFO?()13)oco^h7 zLwa+KC_e5z#|L>KAjAODn`;z#HfT;~6!1^z3nBwIKLQu`pW8}?yf7GW4L3hRp4@^% z31HtP;2b~(VfU}j$~e#hKm=F^PWwO7xMK-0ip|~^MS2UfUcpTlz31%A-^eSs;XWWw zR>;!Z!7^LB!qxg88jh0HCG2E|0R8|Q&+>+w@%r!8V7{fSdc1c>$VH1%p8+;ZTsx(Z zFleI%(wpmHlO8e*8asiTErXL7UuMW9+$=`6UZKd-!7{hk*dD0%0Zj5N!Qb;Az0YsL z*a@yKE`eC?;b_AEbgMzX5>&4SH5wvi_!~(>#P82ZVJ8m|HGz>dMg6<4UJcexP=v>Z zjDin9XGbV35!#E4T0fv3?^O*x6dCcRs5e%9HmI=#Ix|7FFsQHu+M|HNJ3=Z7=&A;# zpVF3WYMCS?xA`0O-wzmz50FktfhyuCgu&L=^wXwDAv*FZ*G-uXK?B0000M-)mE(9UES*1cDG%3-Ll)Yg4RYVh*fc012tuioKZ)V#D$Q! z?R-^&c&-^34&25jfpPinWs4>*|I(s|6j>T)ro9^1j;#L8`X8-aweAqNsgnRSj}ogH zfu3syh6T~R0I>YFo9;I&d;m~nscc#OjrS+}qTVcXmo=QX3Sfj-0YFjY3F-EsDDuSq zeVvauZx!(8f(r^b#~8ImxMJQSr=B1=f@opRgc|tp!}Zb8qBRe z-n(zh>*3L$GYSfLj83ZARY7!KB2fTLLsS%b`K%>}4t%)wVD{-{ALX-_OpJ#i6TWneDa|gRg>->H@4`?n{TYWxN-YOn|u6W zOF?O;v%CF{u7PdSMV3y&pB4Ud&pz@)hs`>z{}cW|@crfYu6WuX4r&5;dvnvemfG4{ z@r0T)76usynmqA(oo?ywFW)lx(n}^+mlhXYCkWJ&31^1E0&ShgH~eYm-tGVK@@sp8 zfv^q$U?dKKADvzz9cyT4F!~Gs#b5mJL9fSsW&eKqqOm<+`_A95_~cM~lv38+vhC7c z*)T_0P{7%RpF)2n5JG(%%moe$0MuP`W!{~)U0*l8b3Rnodl9I?^nP0`v-D8t_5dm z7>PvpedBx2e1GrWL*Z;FAp-@BeB=*AZ!om=y-gpitFF0ZUU5P0O*nVw5!Tt&^F~wS zpSE1J;PS;eZr9wAG|J{oNK*li(aOtq&R_z~pE9Y;_OquS9_xT7Mh_@i``kcI+2U*U7kp=mnQxCTwvkVqIX7y~mHI8Saw2qB;Xg+M7R76Fnd zL6Id$k_bXZ&*PpAC78Ck(`r0Z3_^;MHvhY$B7Dv{Vrl|`U?2Sc5JHhCVrm?Tgbu?n zz!(F^r@KH74#pS^!$2aTBc{d?j>OOxjv=1VKnQ^-3Rzc%WD)bOzGC*w4|cU~_WAtc zMI|StuJ*k?GkuuisAAqCC(-Gg{2aIR(l3AXkJ%PJV+_G?6yb0bjDI?i1WF;x0z^@S zC8~c&~+X0ID^5A)4x+H!0E8U?X-c?>@GQd(b%3l|MH=SyL*Eg z7uhy5ZVOX0py;A0g^ZB=N5A{mS4hX!LDy`czvzFw&D1UNWEL4d=qz~!*P zVV5CWBuJtFL7*(?Y;P;14FXrjO=MQdr_Fq@;Bp^HrtKUppQzq#6@%@^&xC*+F@N9TzYvc7_m^a2| zmCHNBUTzKu=F*d7GHq!Q* zuH!^^0J^S2paODp9FS!Rqqtif1VR8w5}?Q;;)&#<9gW3dwOR%(?q@=8FtqiquRijm zFBsA&GdlKeU;Bw!UeY@H``h>WQcBqH&d8OZ={k;|^usU=NRo(Lj|22`81=(}QVN^Z zf_OrQt{aF%RoHCuh?LM93~l}LeUCiZ-5b;>GdfzfuWtch+Lop5d-1pL^%ah-kfVvX zW5YXJ8|$u{JI<;orNcd+G&_DU#vofH}bCU!Htd#tnCUeSJnA+>AtVLd_Wq z4$BP-YdxpDnu8FH#Sw}`K>&E&w$F93H48!jkJ}0Yf?!_+F?Hx@#^S=RfPG zb|2G9GNGA?0thi^DFA%+%S&z_sxQVkdIHHqp~Im-7=`_PwjqiFoQ`B1a8Dov#)dRS z^qxCzt_J`ZWLzfq#A!!GRL!n0G^nQ3U2|n#L7r#PP|pOzk<*7Po09p7Gt?LT_|Vbz zO&{;s+j6+0C)~ViZ!Z8;&6tuieoU@&=Jd+SveM!OE{E;nOz2n@3nH-ubX`X<9D&E} z81zg*fp_u3Yv#SW;SXDURkNE5nz!RbI<(SOfI+n}0B}eB!W%H;=w}FrA^?CKr!@o9 zLwLvWuD4dMTKCe%%{zuX=tbFH4TW6ForZPe7F%UwaD1+a@<+7KqdGp=1300GG ztm8ZU{sYDkU7eYZ*#-dM@l+L4g8XmX^QFqFsS_6u{GD@-ZeI`_962sKgmjMhfl%Y$ zt$6m)_qTrJBaEs{5clnCdab#qz17!qe1G)h$%7hNS~yx-_{oz8wVvbqqyF~2K3`{R zo40hjN(}Da(|Vw9`_A3(T~RZ0oK=xc#~O*Eh?tr{LNnlU+6H+~DWz7cD1W$h$F6Q> zvqb$Jtt0k=rZA*rs;cTO+{Pw>=-x9$7QeLe$-BpwjQP^Q|Hoo+ob&}C3Ig)HgYD

z|_lbnZ^ZPeD|_N6PMq1)BR@S^Eu~e@92iX8S=d@ zlO9gOpa0dG`+mLVoi>4?t9kp{T}Z>fGO*Li%NEUK0?l7`>%wvOEMNM(nT6RfIJ*5I zP(o2MCg1cWj;h8Ft#0_;Gb>lEJ46i9*}CJkJ^gA z1k>*2j^kZ#{d&ziZD1r`Stjj9=E4U6Uf>Ar1|#v+uWmSc{ABmrW*Q3ufj|W?&Y)?U zY2u0^Pgque8X=(t}c#=tr#q8OH@Rh69y#xSE6c3oS`Den$ zjT?2Hl7j&7ixk&icS-qB4M zQ}=Ic=*%`>2bzA{0Y>8QZEWm{MB}^7v`xK>rt8^eEBgvaB$5MH6wEEY2ag`x1OSF8 zbs;;ZXCSyCpbG#FpQ1HV2sHUFnwHhn005()0R7bEIyJdiecZgS6#$S(n2M`010Gj> z0I+jcORJf7skJQiZrMcE6~Iq9uLQwd*N57=f&kzIMlF@eW*AWbIMUwTYo=XlFfnrh z4b#(cDEcbbz)6zJu{7-7z*c&e^?Zf3te}2 z_o&?%r23ZS?8E|P16fx`V6h~bG`nRhD=l6C0HQ(iF*;>*h;E<& z0LmwnoG}e)AW~7*lJtLI21sJkfvTH4HM$)3=~vC4oyRFtCeNua&Ng4=)l0{Ka`~#- z*#&l+Y$~ii^)8ah)BQ*=NCAW~6-d_GNvA_aPAVWCH+yK|%;2FRLKLD)$&H5jyYTR^b0Z9@e z5DJ5_)3$S@C@RdWyW`e{<3PFG)#sXy?3g0b6?aVs z7V{f4RgE9~)hoYy8UP5So3!-4-+WFGgh7eaUA|sKV=A0>1$LXc zJ-3?B+rIVikG{SC;ITeNg|_|M*6c(2z9BNH=9Vb}=Oq>8rS_jb^}s(X7Rgi`Pb3;g zIHJOCvm$?p&68mmfrlRb$=9~**nQ@(bVlMrba3gkLCbn~cZ*Tzo_?H&nnXaP;cms+ zI!?r{y{g*fak~cDQ$h$LQ5A;4Oe;VXsQZeVnd9F4pUv-U@r0|OXtJwna*^-Ikt3$| zwY9aiqOEAw48mEF(_y7QfBK4-Q*nt-N~aSP`u9PdoR1Fw~u}Rk46l0R}Um>CAM(g~#ox zdEvRofAH|*KYM2X!DBcP@ysi)UV89A({DR)_SrzntCx;B5$6-Z47sAb)c(|?-+0L5 zc2%2V0)VD7=!OAG1z3lOiU5EQceFMEfDYPnpy{{mW@)5lW6SI6WXZ2w>2bO&ufOt> zRYR2)2n72O4E4bxiSXvw(;)*jt{+|XoAv*&`qd3b0RW7|4FO$5)4LTdCst9RssONW zpQ1zspN+^$o?xILRd?d{`ns~aZoAype-R4w zXc>CUgba1Vc)cQb8=DfExtjRkgDVp8Vd| z?yH@9>9<8eFdY*FBu9T=M1?>o^7Gt7x*-l9>1cTQ)wg#6@bBOK#<6thq`k|inq7a9 zLA8tPuDLSr(FgzPMGUc{O3ea65Rm6_WE_|qiN<#yK6-4^&Rs37hdXHFs zlilNsbKRFrubetze8~d4O`e_!9nOKCKr$R_ziArOLY1KmD76JkOFr95RlM6FwM*0hhxHn|0LuY*|HW=OYRt#uViZIdHnV z{I4xu{_TG!jH<2MFW#JPt%yuc!ki1V4FH~Bz4q4t1~EV>L9WLI00{S~(Dm%!C}kVE z&d?W0n(|z)Yq(jhtLKfOp0QbFxa>A? za0G%ejKZBp*1#BtKNtZAhs$9fcIVT1vS&6D773o5;X^8$K1jYR1r22yK9i9G zs;U=PrYcQcIe+$`H6R5-2nzFZAc`V%-9T?Ba$YHcaiBLCg{~VA1rddLo-0hD;1Zs~>p_~8S&9{2n+Jx?it)oMW`szNsm#5EmO z#d6M5mQrR%({)fvaZ#ZMqIhPpSQVx8#)b3BHoV)oEfQ1h1;vw;?#}&bMRTO3fJrsC zOcgjkE&M#MdqnyRZO>(xs}3SDRD>5afJ7(_wDMTMRbyPOq8 zF1g{_xk)9c@wAm-S^?#=mP`~W%2GAfMk@T%1Sy5xra+Br&~+U#RRg7|dOl{kNe`SS zlLv#L7&zy!SR`Cj;63Ze9|%Q}ORm3WZrLB+-PYKrCT!l~D&EuC8Zgs`DT=dZ-E3o` zFvDiG3aeK>`H)%Rr$8xz!>#}fP!kEn6FStm4vQqFmCRuVn$8diMo!0hx*T@o=epCL zg;qr_x%TS0#p~YOxWzEE9Hn&n@lboqh;O4zQ4L!Z4+kd?e)B7{(iMIRgb;Ww;tQIJ8dVVAzY2)Jw4bfNv z#;I)=1%bvdrbM!Zk`I%YOW`7n=Y; zv~W{lkEX}Kw3=I{>YSI9l@=+_|76AEE{A=l**?yORMEajR7ETn|4jWjGoXaRYL#KP zDW|r)*ldz`JIx|V1tV!42nM&jwc(FHcYAW8PKRwW&fWLSSm()} z*Z=1aTmGx4DBrFq@`!HE29_>vZJhaemo84>)B4dPT@(Dhp{;k__x-1Q!B7H77Vp0A z_C-qz3v)mB;@vO2^7^VZCX07xyMp?8Q@(!THS_Y8-&(hD{J7$q=@6kV*??gffg?vd z*Z=n`Z*2Je#>S-EfFMDM5M<2A|36s1K85r?;80&*FYG?1l@NoLa>^6{aC@BMy|>>| zap|lnmzNe7EzH&j96sF9+O+bOwfj>aa3GATTwrbg4?f_K!thG)`GcG8x^KlZ{e?fU zZPo1N0)uK}2#A-TN~E4&J=6R26W@M06Rz(6{y*K33YsDy9E9{xL+EVY-f$8FLR|VQ zp}&)Hw1l7JDXaKY3Hdp0>Hfd{N=;v1EcWcbzPK|Qi?N}F|5=om*U8AW=8IsJ0I+St z3mY=wXwJgB76Qq*9rVPy&lWn8Qi9EDrQiAb@=F~y+4}6yUfk9d=+(0=d|*^|ACJ*# zHM=Tw&QI?s2;s~y#6$bHuQ@c*UZzwpxemyl0`@koeP^U?CeQxj1c9=NykAL!Cwji?Q0H=ol}3@hM3pT1u9y2?yvdUMbHxP(oMW7~3ZR_FfMmU$bo)pp zn56nTA93C)09;IF>NNcB88x0bY__?o#t;AMmEZkSvM*+;rvK-O^R|xdNHcZLieWNS z&KG=M&M(vWG*gF2;D!Z+nA))s##GA1lQb#}nVE6{7jOX=Z~+%^0T*xq=Mw)5fGwvC TAGsT^00000NkvXXu0mjfv7WmN literal 0 HcmV?d00001 diff --git a/src/share/aptik-gtk/images/preferences-theme.svg b/src/share/aptik-gtk/images/preferences-theme.svg new file mode 100644 index 0000000..8b1688c --- /dev/null +++ b/src/share/aptik-gtk/images/preferences-theme.svg @@ -0,0 +1,382 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/share/aptik-gtk/images/restore.svg b/src/share/aptik-gtk/images/restore.svg new file mode 100644 index 0000000..6760316 --- /dev/null +++ b/src/share/aptik-gtk/images/restore.svg @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/share/aptik-gtk/images/user-home.svg b/src/share/aptik-gtk/images/user-home.svg new file mode 100644 index 0000000..86b199c --- /dev/null +++ b/src/share/aptik-gtk/images/user-home.svg @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + diff --git a/src/share/aptik-gtk/images/x-system-software-sources.svg b/src/share/aptik-gtk/images/x-system-software-sources.svg new file mode 100644 index 0000000..7cec623 --- /dev/null +++ b/src/share/aptik-gtk/images/x-system-software-sources.svg @@ -0,0 +1,331 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/share/pixmaps/aptik-gtk.svg b/src/share/pixmaps/aptik-gtk.svg new file mode 100644 index 0000000..c73b76c --- /dev/null +++ b/src/share/pixmaps/aptik-gtk.svg @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +