[neon/backports-jammy/power-profiles-daemon/Neon/unstable] /: 0.1-3 (patches unapplied)
git-ubuntu importer
null at kde.org
Tue Sep 24 23:21:42 BST 2024
Git commit 48e676a7f5f2c416204f27e60f92056d7b2d9c45 by git-ubuntu importer, on behalf of Sebastien Bacher.
Committed on 08/03/2021 at 22:26.
Pushed by carlosdem into branch 'Neon/unstable'.
0.1-3 (patches unapplied)
Imported using git-ubuntu import.
A +12 -0 .editorconfig
A +674 -0 COPYING
A +4 -0 NEWS
A +140 -0 README.md
A +21 -0 data/meson.build
A +21 -0 data/net.hadess.PowerProfiles.conf.in
A +11 -0 data/net.hadess.PowerProfiles.service
A +25 -0 data/power-profiles-daemon.service.in
A +22 -0 debian/changelog
A +71 -0 debian/control
A +69 -0 debian/copyright
A +14 -0 debian/gbp.conf
A +0 -0 debian/patches/series
A +5 -0 debian/power-profiles-daemon.install
A +16 -0 debian/rules
A +1 -0 debian/source/format
A +9 -0 debian/tests/control
A +13 -0 debian/tests/installed-tests
A +3 -0 debian/watch
A +60 -0 docs/meson.build
A +88 -0 docs/power-profiles-daemon-docs.xml
A +32 -0 docs/power-profiles-daemon-sections.txt
A +3 -0 docs/power-profiles-daemon.types
A +1 -0 docs/version.xml.in
A +58 -0 meson.build
A +8 -0 meson_options.txt
A +53 -0 src/meson.build
A +76 -0 src/net.hadess.PowerProfiles.xml
A +608 -0 src/power-profiles-daemon.c [License: GPL (v3)]
A +7 -0 src/power-profiles-daemon.gresource.xml
A +14 -0 src/power-profiles-daemon.h [License: GPL (v3)]
A +141 -0 src/ppd-action-trickle-charge.c [License: GPL (v3)]
A +15 -0 src/ppd-action-trickle-charge.h [License: GPL (v3)]
A +159 -0 src/ppd-action.c [License: GPL (v3)]
A +41 -0 src/ppd-action.h [License: GPL (v3)]
A +49 -0 src/ppd-driver-balanced.c [License: GPL (v3)]
A +15 -0 src/ppd-driver-balanced.h [License: GPL (v3)]
A +180 -0 src/ppd-driver-fake.c [License: GPL (v3)]
A +15 -0 src/ppd-driver-fake.h [License: GPL (v3)]
A +288 -0 src/ppd-driver-intel-pstate.c [License: GPL (v3)]
A +15 -0 src/ppd-driver-intel-pstate.h [License: GPL (v3)]
A +211 -0 src/ppd-driver-lenovo-dytc.c [License: GPL (v3)]
A +15 -0 src/ppd-driver-lenovo-dytc.h [License: GPL (v3)]
A +49 -0 src/ppd-driver-power-saver.c [License: GPL (v3)]
A +15 -0 src/ppd-driver-power-saver.h [License: GPL (v3)]
A +254 -0 src/ppd-driver.c [License: GPL (v3)]
A +44 -0 src/ppd-driver.h [License: GPL (v3)]
A +40 -0 src/ppd-enums.c.in
A +24 -0 src/ppd-enums.h.in
A +43 -0 src/ppd-profile.c [License: GPL (v3)]
A +35 -0 src/ppd-profile.h [License: GPL (v3)]
A +56 -0 src/ppd-utils.c [License: GPL (v3)]
A +20 -0 src/ppd-utils.h [License: GPL (v3)]
A +506 -0 tests/integration-test
A +9 -0 tests/meson.build
https://invent.kde.org/neon/backports-jammy/power-profiles-daemon/-/commit/48e676a7f5f2c416204f27e60f92056d7b2d9c45
diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000..4a7ea30
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,12 @@
+root = true
+
+[*]
+indent_style = space
+indent_size = 2
+end_of_line = lf
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+
+[*.md]
+trim_trailing_whitespace = false
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. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/NEWS b/NEWS
new file mode 100644
index 0000000..ee04942
--- /dev/null
+++ b/NEWS
@@ -0,0 +1,4 @@
+0.1
+---
+
+This is the first version of power-profiles-daemon.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..9e5a192
--- /dev/null
+++ b/README.md
@@ -0,0 +1,140 @@
+power-profiles-daemon
+=====================
+
+Makes power profiles handling available over D-Bus.
+
+Installation
+------------
+```sh
+$ meson _build -Dprefix=/usr
+$ ninja -v -C _build install
+```
+It requires libgudev and systemd.
+
+Introduction
+------------
+
+power-profiles-daemon offers to modify system behaviour based upon user-selected
+power profiles. There are 3 different power profiles, a "balanced" default mode,
+a "power-saver" mode, as well as a "performance" mode. The first 2 of those are
+available on every system. The "performance" mode is only available on select
+systems and is implemented by different "drivers" based on the system or
+systems it targets.
+
+In addition to those 2 or 3 modes (depending on the system), "actions" can be hooked
+up to change the behaviour of a particular device. For example, this can be used
+to disable the fast-charging for some USB devices when in power-saver mode.
+
+GNOME's Settings and shell both include interfaces to select the current mode, but
+they are also expected to adjust the behaviour of the desktop depending on the mode,
+such as turning the screen off after inaction more aggressively when in power-saver
+mode.
+
+Note that power-profiles-daemon does not save the currently active profile across
+system restarts and will always start with the "balanced" profile selected.
+
+Debugging
+---------
+
+You can now check which mode is in use, and which ones are available by running:
+```
+gdbus introspect --system --dest net.hadess.PowerProfiles --object-path /net/hadess/PowerProfiles
+```
+
+You can change the selected profile by running (change `power-saver` for the
+chosen profile):
+```
+gdbus call --system --dest net.hadess.PowerProfiles --object-path /net/hadess/PowerProfiles --method org.freedesktop.DBus.Properties.Set 'net.hadess.PowerProfiles' 'SelectedProfile' "<'power-saver'>"
+```
+
+If that doesn't work, please file an issue, make sure any running power-profiles-daemon
+has been stopped:
+`systemctl stop power-profiles-daemon.service`
+and attach the output of:
+`G_MESSAGES_DEBUG=all /usr/libexec/power-profiles-daemon`
+running as ```root```.
+
+Testing
+-------
+
+If you don't have hardware that can support the performance mode, you can
+manually run the `power-profiles-daemon` binary as `root` with the environment
+variable `POWER_PROFILE_DAEMON_FAKE_DRIVER` set to 1. For example:
+```sh
+$ sudo POWER_PROFILE_DAEMON_FAKE_DRIVER=1 /usr/libexec/power-profiles-daemon
+```
+
+References
+----------
+
+- [Use Low Power Mode to save battery life on your iPhone (iOS)](https://support.apple.com/en-us/HT205234)
+- [lowPowerModeEnabled (iOS)](https://developer.apple.com/documentation/foundation/nsprocessinfo/1617047-lowpowermodeenabled?language=objc)
+- [React to Low Power Mode on iPhones (iOS)](https://developer.apple.com/library/archive/documentation/Performance/Conceptual/EnergyGuide-iOS/LowPowerMode.html#//apple_ref/doc/uid/TP40015243-CH31)
+- [[S]ettings that use less battery (Android)](https://support.google.com/android/answer/7664692?hl=en&visit_id=637297348326801871-2263015427&rd=1)
+- [EnergySaverStatus Enum (Windows)](https://docs.microsoft.com/en-us/uwp/api/windows.system.power.energysaverstatus?view=winrt-19041)
+
+Why power-profiles-daemon
+-------------------------
+
+The power-profiles-daemon project was created to help provide a solution for
+two separate use cases, for desktops, laptops, and other devices running a
+“traditional Linux desktop”.
+
+The first one is a "Low Power" mode, that users could toggle themselves, or
+have the system toggle for them, with the intent to save battery. Mobile
+devices running iOS and Android have had a similar feature available to
+end-users and application developers alike.
+
+The second use case was to allow a "Performance" mode on systems where the
+hardware maker would provide and design such a mode. The idea is that the
+Linux kernel would provide a way to access this mode which usually only
+exists as a configuration option in some machines' "UEFI Setup" screen.
+
+This second use case is the reason why we didn't implement the "Low Power"
+mode in UPower, [as was originally discussed](https://gitlab.freedesktop.org/upower/upower/-/issues/102).
+
+As the daemon would change kernel settings, we would need to run it as root,
+and make its API available over D-Bus, as has been customary for more than
+10 years. We would also design that API to be as easily usable to build
+graphical interfaces as possible.
+
+Why not...
+----------
+
+This section will contain explanations of why this new daemon was written
+rather than re-using, or modifying an existing one. Each project obviously
+has its own goals and needs, and those comparisons are not meant as a slight
+on the project.
+
+As the code bases for both those projects listed and power-profiles-daemon are
+ever evolving, the comments were understood to be correct when made.
+
+### [thermald](https://01.org/linux-thermal-daemon/documentation/introduction-thermal-daemon)
+
+thermald only works on Intel CPUs, and is very focused on allowing maximum
+performance based on a "maximum temperature" for the system. As such, it
+could be seen as complementary to power-profiles-daemon.
+
+### [tuned](https://github.com/redhat-performance/tuned/) and [TLP](https://linrunner.de/tlp/)
+
+Both projects have similar goals, allowing for tweaks to be applied, for
+a variety of workloads that goes far beyond the workloads and use cases
+that power-profiles-daemon targets.
+
+A fair number of the tweaks that could apply to devices running GNOME or
+another free desktop are either potentially destructive (eg. some of the
+SATA power-saving mode resulting in corrupted data), or working well
+enough to be put into place by default (eg. audio codec power-saving), even
+if some quirks might be needed on some hardware.
+
+Both are good projects to use if the intent is to experiment with particular
+settings to see if they'd be something that can be implemented by default,
+or to put some fine-grained policies in place on server-type workloads
+which are not as fluid and changing as desktop workloads can be.
+
+### [auto-cpufreq](https://github.com/AdnanHodzic/auto-cpufreq)
+
+It doesn't take user-intent into account, doesn't have a D-Bus interface and
+seems to want to work automatically by monitoring the CPU usage, which kind
+of goes against a user's wishes as a user might still want to conserve as
+much energy as possible under high-CPU usage.
diff --git a/data/meson.build b/data/meson.build
new file mode 100644
index 0000000..8904325
--- /dev/null
+++ b/data/meson.build
@@ -0,0 +1,21 @@
+data_conf = configuration_data()
+data_conf.set('libexecdir', libexecdir)
+
+configure_file(
+ input: 'power-profiles-daemon.service.in',
+ output: 'power-profiles-daemon.service',
+ configuration: data_conf,
+ install_dir: systemd_system_unit_dir,
+)
+
+configure_file(
+ input: 'net.hadess.PowerProfiles.conf.in',
+ output: 'net.hadess.PowerProfiles.conf',
+ configuration: data_conf,
+ install_dir: dbusconfdir
+)
+
+install_data(
+ 'net.hadess.PowerProfiles.service',
+ install_dir: dbusservicedir
+)
diff --git a/data/net.hadess.PowerProfiles.conf.in b/data/net.hadess.PowerProfiles.conf.in
new file mode 100644
index 0000000..a01d2d4
--- /dev/null
+++ b/data/net.hadess.PowerProfiles.conf.in
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?> <!-- -*- XML -*- -->
+
+<!DOCTYPE busconfig PUBLIC
+ "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+<busconfig>
+
+ <!-- Only root can own the service -->
+ <policy user="root">
+ <allow own="net.hadess.PowerProfiles"/>
+ </policy>
+
+ <!-- Anyone can talk to the main interface -->
+ <policy context="default">
+ <allow send_destination="net.hadess.PowerProfiles" send_interface="net.hadess.PowerProfiles"/>
+ <allow send_destination="net.hadess.PowerProfiles" send_interface="org.freedesktop.DBus.Introspectable"/>
+ <allow send_destination="net.hadess.PowerProfiles" send_interface="org.freedesktop.DBus.Properties"/>
+ <allow send_destination="net.hadess.PowerProfiles" send_interface="org.freedesktop.DBus.Peer"/>
+ </policy>
+
+</busconfig>
diff --git a/data/net.hadess.PowerProfiles.service b/data/net.hadess.PowerProfiles.service
new file mode 100644
index 0000000..724f631
--- /dev/null
+++ b/data/net.hadess.PowerProfiles.service
@@ -0,0 +1,11 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# This program is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 3 as published by
+# the Free Software Foundation.
+
+[D-BUS Service]
+Name=net.hadess.PowerProfiles
+Exec=/bin/false
+User=root
+SystemdService=power-profiles-daemon.service
diff --git a/data/power-profiles-daemon.service.in b/data/power-profiles-daemon.service.in
new file mode 100644
index 0000000..8fe56ce
--- /dev/null
+++ b/data/power-profiles-daemon.service.in
@@ -0,0 +1,25 @@
+[Unit]
+Description=Power Profiles daemon
+Conflicts=tuned.service tlp.service auto-cpufreq.service
+Before=multi-user.target display-manager.target
+
+[Service]
+Type=dbus
+BusName=net.hadess.PowerProfiles
+ExecStart=@libexecdir@/power-profiles-daemon
+Restart=on-failure
+#Uncomment this to enable debug
+#Environment="G_MESSAGES_DEBUG=all"
+
+# Lockdown
+ProtectSystem=strict
+ProtectControlGroups=true
+ProtectHome=true
+ProtectKernelModules=true
+PrivateTmp=true
+RestrictAddressFamilies=AF_UNIX AF_LOCAL AF_NETLINK
+MemoryDenyWriteExecute=true
+RestrictRealtime=true
+
+[Install]
+WantedBy=graphical.target
diff --git a/debian/changelog b/debian/changelog
new file mode 100644
index 0000000..acdc705
--- /dev/null
+++ b/debian/changelog
@@ -0,0 +1,22 @@
+power-profiles-daemon (0.1-3) experimental; urgency=medium
+
+ * Resolve the problems pointed during the NEW review
+ * debian/control:
+ - set an Uploaders to fix the lintian error no-human-maintainers
+ * debian/copyright:
+ - include a missing xml from the docs dir which is GFDL
+
+ -- Sebastien Bacher <seb128 at ubuntu.com> Fri, 05 Mar 2021 17:10:23 +0100
+
+power-profiles-daemon (0.1-2) experimental; urgency=medium
+
+ * debian/copyright:
+ - updated, the tests have different copyright and license
+
+ -- Sebastien Bacher <seb128 at ubuntu.com> Fri, 19 Feb 2021 17:01:27 +0100
+
+power-profiles-daemon (0.1-1) experimental; urgency=medium
+
+ * Initial release (Closes: #983108)
+
+ -- Sebastien Bacher <seb128 at ubuntu.com> Mon, 19 Feb 2018 16:03:29 +0100
diff --git a/debian/control b/debian/control
new file mode 100644
index 0000000..4fe1362
--- /dev/null
+++ b/debian/control
@@ -0,0 +1,71 @@
+Source: power-profiles-daemon
+Section: admin
+Priority: optional
+Maintainer: Debian freedesktop.org maintainers <pkg-freedesktop-maintainers at lists.alioth.debian.org>
+Uploaders: Sebastien Bacher <seb128 at ubuntu.com>
+Build-Depends: debhelper-compat (= 13),
+ libglib2.0-dev,
+ libgudev-1.0-dev,
+ libupower-glib-dev,
+ libudev-dev,
+ libumockdev-dev,
+ meson,
+ python3-dbus <!nocheck>,
+ python3-dbusmock <!nocheck>,
+ python3-gi <!nocheck>,
+ systemd,
+ umockdev <!nocheck>,
+Standards-Version: 4.5.1
+Vcs-Browser: https://salsa.debian.org/freedesktop-team/power-profiles-daemon
+Vcs-Git: https://salsa.debian.org/freedesktop-team/power-profiles-daemon.git
+Homepage: https://gitlab.freedesktop.org/hadess/power-profiles-daemon
+
+Package: power-profiles-daemon
+Architecture: linux-any
+Depends: ${misc:Depends}, ${shlibs:Depends}
+Description: Makes power profiles handling available over D-Bus.
+ power-profiles-daemon offers to modify system behaviour based upon
+ user-selected power profiles. There are 3 different power profiles, a
+ "balanced" default mode, a "power-saver" mode, as well as a "performance"
+ mode. The first 2 of those are available on every system. The "performance"
+ mode is only available on select systems and is implemented by different
+ "drivers" based on the system or systems it targets.
+ .
+ In addition to those 2 or 3 modes (depending on the system),
+ "actions" can be hooked up to change the behaviour of a particular device.
+ For example, this can be used to disable the fast-charging for some USB
+ devices when in power-saver mode.
+ .
+ Note that power-profiles-daemon does not save the currently active
+ profile across system restarts and will always start with the "balanced"
+ profile selected.
+
+Package: power-profiles-daemon-tests
+Architecture: any
+Depends: gir1.2-glib-2.0,
+ gir1.2-umockdev-1.0,
+ python3,
+ python3-dbus,
+ python3-dbusmock,
+ python3-gi,
+ umockdev,
+ ${misc:Depends},
+ ${shlibs:Depends}
+Description: Makes power profiles handling available over D-Bus.
+ power-profiles-daemon offers to modify system behaviour based upon
+ user-selected power profiles. There are 3 different power profiles, a
+ "balanced" default mode, a "power-saver" mode, as well as a "performance"
+ mode. The first 2 of those are available on every system. The "performance"
+ mode is only available on select systems and is implemented by different
+ "drivers" based on the system or systems it targets.
+ .
+ In addition to those 2 or 3 modes (depending on the system),
+ "actions" can be hooked up to change the behaviour of a particular device.
+ For example, this can be used to disable the fast-charging for some USB
+ devices when in power-saver mode.
+ .
+ Note that power-profiles-daemon does not save the currently active
+ profile across system restarts and will always start with the "balanced"
+ profile selected.
+ .
+ This package includes tests to be used on the installed system.
diff --git a/debian/copyright b/debian/copyright
new file mode 100644
index 0000000..93559db
--- /dev/null
+++ b/debian/copyright
@@ -0,0 +1,69 @@
+Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
+Upstream-Name: power-profiles-daemon
+Source: https://gitlab.freedesktop.org/hadess/power-profiles-daemon
+
+Files: *
+Copyright: 2020 Bastien Nocera <hadess at hadess.net>
+License: GPL-3
+
+Files: debian/*
+Copyright: 2021 Sebastien Bacher <seb128 at ubuntu.com>
+License: GPL-3
+
+Files: tests/integration-test
+Copyright: 2011 Martin Pitt <martin.pitt at ubuntu.com>
+ 2020 Bastien Nocera <hadess at hadess.net>
+License: GPL-2+
+
+Files: docs/power-profiles-daemon-docs.xml
+Copyright: 2020 Red Hat, Inc.
+License: GFDL-NIV-1.1+
+
+License: GPL-3
+ This program is free software: you can redistribute it and/or modify it
+ under the terms of the GNU General Public License version 3, as
+ published by the Free Software Foundation.
+ .
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranties of
+ MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR
+ PURPOSE. See the applicable version of the GNU Lesser General Public
+ License for more details.
+ .
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+ .
+ On Debian systems, the complete text of the GNU General Public License
+ can be found in `/usr/share/common-licenses/GPL-3'
+
+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 <https://www.gnu.org/licenses/>
+ .
+ On Debian systems, the complete text of the GNU General
+ Public License version 2 can be found in "/usr/share/common-licenses/GPL-2".
+
+License: GFDL-NIV-1.1+
+ Permission is granted to copy, distribute and/or modify this
+ document under the terms of the GNU Free Documentation License,
+ Version 1.1 or any later version published by the Free Software
+ Foundation with no Invariant Sections, no Front-Cover Texts,
+ and no Back-Cover Texts.
+ .
+ You may obtain a copy of the GNU Free Documentation License
+ from the Free Software Foundation by visiting <http://www.fsf.org/>
+ or by writing to: The Free Software Foundation, Inc.,
+ 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ .
+ On Debian systems, the complete text of the GNU Free Documentation
+ License can be found in "/usr/share/common-licenses/GFDL".
diff --git a/debian/gbp.conf b/debian/gbp.conf
new file mode 100644
index 0000000..39195a3
--- /dev/null
+++ b/debian/gbp.conf
@@ -0,0 +1,14 @@
+[DEFAULT]
+pristine-tar = True
+debian-branch = debian/master
+upstream-branch = upstream/latest
+upstream-vcs-tag = %(version)s
+
+[buildpackage]
+sign-tags = True
+
+[dch]
+multimaint-merge = True
+
+[pq]
+patch-numbers = False
diff --git a/debian/patches/series b/debian/patches/series
new file mode 100644
index 0000000..e69de29
diff --git a/debian/power-profiles-daemon.install b/debian/power-profiles-daemon.install
new file mode 100644
index 0000000..942791d
--- /dev/null
+++ b/debian/power-profiles-daemon.install
@@ -0,0 +1,5 @@
+etc/dbus-1
+lib/systemd
+usr/libexec
+usr/share
+
diff --git a/debian/rules b/debian/rules
new file mode 100755
index 0000000..ea0384d
--- /dev/null
+++ b/debian/rules
@@ -0,0 +1,16 @@
+#!/usr/bin/make -f
+
+export DEB_BUILD_MAINT_OPTIONS = hardening=+all
+export DEB_LDFLAGS_MAINT_APPEND = -Wl,-z,defs -Wl,--as-needed
+
+%:
+ dh $@
+
+override_dh_missing:
+ dh_missing --fail-missing
+
+override_dh_install:
+ # install the test but renamed
+ mkdir -p debian/power-profiles-daemon-tests/usr/libexec
+ cp tests/integration-test debian/power-profiles-daemon-tests/usr/libexec/power-profiles-daemon-integration-test
+ dh_install
diff --git a/debian/source/format b/debian/source/format
new file mode 100644
index 0000000..163aaf8
--- /dev/null
+++ b/debian/source/format
@@ -0,0 +1 @@
+3.0 (quilt)
diff --git a/debian/tests/control b/debian/tests/control
new file mode 100644
index 0000000..d0e35a5
--- /dev/null
+++ b/debian/tests/control
@@ -0,0 +1,9 @@
+Tests: installed-tests
+Depends: dpkg-dev,
+ gir1.2-umockdev-1.0,
+ python3-dbus,
+ python3-dbusmock,
+ python3-gi,
+ umockdev,
+ @
+Restrictions: needs-root allow-stderr isolation-machine
diff --git a/debian/tests/installed-tests b/debian/tests/installed-tests
new file mode 100755
index 0000000..f81fcc9
--- /dev/null
+++ b/debian/tests/installed-tests
@@ -0,0 +1,13 @@
+#!/bin/sh
+set -eu
+
+export G_MESSAGES_DEBUG=all
+export XDG_RUNTIME_DIR="$AUTOPKGTEST_TMP"
+
+printf "Running as: "; id -a
+printf "passwd entry: "; getent passwd "$(id -u)" || echo "(exit status $?)"
+printf "group entry: "; getent group "$(id -g)" || echo "(exit status $?)"
+echo "Environment:"
+env | LC_ALL=C sort -u
+
+/usr/libexec/power-profiles-daemon-integration-test -v
diff --git a/debian/watch b/debian/watch
new file mode 100644
index 0000000..506172d
--- /dev/null
+++ b/debian/watch
@@ -0,0 +1,3 @@
+version=4
+https://gitlab.freedesktop.org/hadess/power-profiles-daemon/tags \
+ .*/@PACKAGE@@ANY_VERSION@@ARCHIVE_EXT@
diff --git a/docs/meson.build b/docs/meson.build
new file mode 100644
index 0000000..b8b10ab
--- /dev/null
+++ b/docs/meson.build
@@ -0,0 +1,60 @@
+content_files = files()
+
+version_conf = configuration_data()
+version_conf.set('VERSION', meson.project_version())
+
+content_files += configure_file(
+ input: 'version.xml.in',
+ output: 'version.xml',
+ configuration: version_conf,
+)
+
+content_files += gnome.gdbus_codegen(
+ meson.project_name(),
+ sources: meson.source_root() / 'src' / 'net.hadess.PowerProfiles.xml',
+ interface_prefix: 'net.hadess',
+ namespace: 'PowerProfiles',
+ docbook: 'docs',
+ build_by_default: true,
+)
+
+private_headers = [
+ 'power-profiles-daemon.h',
+ 'ppd-action-trickle-charge.h',
+ 'ppd-driver-balanced.h',
+ 'ppd-driver-fake.h',
+ 'ppd-driver-intel-pstate.h',
+ 'ppd-driver-lenovo-dytc.h',
+ 'ppd-driver-power-saver.h',
+ 'ppd-utils.h',
+ 'power-profiles-daemon-resources.h',
+]
+
+gnome.gtkdoc(
+ meson.project_name(),
+ main_xml: meson.project_name() + '-docs.xml',
+ content_files: content_files,
+ dependencies: libpower_profiles_daemon_dep,
+ gobject_typesfile: [join_paths(meson.current_source_dir(), 'power-profiles-daemon.types')],
+ src_dir: [
+ meson.source_root() /'src',
+ meson.build_root() / 'src',
+ ],
+ ignore_headers: private_headers,
+)
+
+man1_dir = join_paths(get_option('prefix'), get_option('mandir'), 'man1')
+
+xsltproc = find_program('xsltproc', required : true)
+xsltproc_command = [
+ xsltproc,
+ '--nonet',
+ '--stringparam', 'man.output.quietly', '1',
+ '--stringparam', 'funcsynopsis.style', 'ansi',
+ '--stringparam', 'man.th.extra1.suppress', '1',
+ '--stringparam', 'man.authors.section.enabled', '0',
+ '--stringparam', 'man.copyright.section.enabled', '0',
+ '-o', '@OUTPUT@',
+ 'http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl',
+ '@INPUT@',
+]
diff --git a/docs/power-profiles-daemon-docs.xml b/docs/power-profiles-daemon-docs.xml
new file mode 100644
index 0000000..0a2c627
--- /dev/null
+++ b/docs/power-profiles-daemon-docs.xml
@@ -0,0 +1,88 @@
+<?xml version="1.0"?>
+<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
+ "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [
+<!ENTITY version SYSTEM "version.xml">
+]>
+<book id="index" xmlns:xi="http://www.w3.org/2003/XInclude">
+ <bookinfo>
+ <title>Power Profiles daemon Reference Manual</title>
+ <releaseinfo>Version &version;</releaseinfo>
+ <authorgroup>
+ <author>
+ <firstname>Bastien</firstname>
+ <surname>Nocera</surname>
+ <affiliation>
+ <address>
+ <email>hadess at hadess.net</email>
+ </address>
+ </affiliation>
+ </author>
+ </authorgroup>
+
+ <copyright>
+ <year>2020</year>
+ <holder>Red Hat, Inc.</holder>
+ </copyright>
+
+ <legalnotice>
+ <para>
+ Permission is granted to copy, distribute and/or modify this
+ document under the terms of the <citetitle>GNU Free
+ Documentation License</citetitle>, Version 1.1 or any later
+ version published by the Free Software Foundation with no
+ Invariant Sections, no Front-Cover Texts, and no Back-Cover
+ Texts. You may obtain a copy of the <citetitle>GNU Free
+ Documentation License</citetitle> from the Free Software
+ Foundation by visiting <ulink type="http"
+ url="http://www.fsf.org">their Web site</ulink> or by writing
+ to:
+
+ <address>
+ The Free Software Foundation, Inc.,
+ <street>59 Temple Place</street> - Suite 330,
+ <city>Boston</city>, <state>MA</state> <postcode>02111-1307</postcode>,
+ <country>USA</country>
+ </address>
+ </para>
+
+ <para>
+ Many of the names used by companies to distinguish their
+ products and services are claimed as trademarks. Where those
+ names appear in any GNOME documentation, and those trademarks
+ are made aware to the members of the GNOME Documentation
+ Project, the names have been printed in caps or initial caps.
+ </para>
+ </legalnotice>
+ </bookinfo>
+
+ <reference id="ref-dbus">
+ <title>D-Bus API Reference</title>
+ <partintro>
+ <para>
+ This part documents the D-Bus interface used to access the
+ Power Profiles daemon.
+ </para>
+ </partintro>
+ <xi:include href="docs-net.hadess.PowerProfiles.xml"/>
+ </reference>
+
+ <reference id="internal-api">
+ <title>Internal API</title>
+ <xi:include href="xml/ppd-profile.xml"/>
+ <xi:include href="xml/ppd-driver.xml"/>
+ <xi:include href="xml/ppd-action.xml"/>
+ </reference>
+
+ <index>
+ <title>Index</title>
+ </index>
+
+ <!-- License -->
+
+ <appendix id="license">
+ <title>License</title>
+ <para>
+<programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="../COPYING" parse="text"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting>
+ </para>
+ </appendix>
+</book>
diff --git a/docs/power-profiles-daemon-sections.txt b/docs/power-profiles-daemon-sections.txt
new file mode 100644
index 0000000..0ad1c3a
--- /dev/null
+++ b/docs/power-profiles-daemon-sections.txt
@@ -0,0 +1,32 @@
+<SECTION>
+<FILE>ppd-action</FILE>
+<TITLE>Profile Actions</TITLE>
+PpdActionClass
+PpdAction
+<SUBSECTION Private>
+PPD_TYPE_ACTION
+</SECTION>
+
+<SECTION>
+<FILE>ppd-driver</FILE>
+<TITLE>Profile Drivers</TITLE>
+PpdDriverClass
+PpdDriver
+<SUBSECTION Private>
+PPD_TYPE_DRIVER
+</SECTION>
+
+<SECTION>
+<FILE>ppd-profile</FILE>
+<TITLE>Constants</TITLE>
+PpdProfile
+PPD_PROFILE_ALL
+PPD_PROFILE_UNSET
+ppd_profile_to_str
+ppd_profile_from_str
+ppd_profile_has_single_flag
+<SUBSECTION Private>
+PPD_TYPE_PROFILE
+ppd_profile_get_type
+</SECTION>
+
diff --git a/docs/power-profiles-daemon.types b/docs/power-profiles-daemon.types
new file mode 100644
index 0000000..fc0dc74
--- /dev/null
+++ b/docs/power-profiles-daemon.types
@@ -0,0 +1,3 @@
+ppd_action_get_type
+ppd_driver_get_type
+ppd_profile_get_type
diff --git a/docs/version.xml.in b/docs/version.xml.in
new file mode 100644
index 0000000..d78bda9
--- /dev/null
+++ b/docs/version.xml.in
@@ -0,0 +1 @@
+ at VERSION@
diff --git a/meson.build b/meson.build
new file mode 100644
index 0000000..0a68a9e
--- /dev/null
+++ b/meson.build
@@ -0,0 +1,58 @@
+project('power-profiles-daemon', [ 'c' ],
+ version: '0.1',
+ license: 'GPLv3+',
+ default_options: [
+ 'buildtype=debugoptimized',
+ 'warning_level=1',
+ 'c_std=c99',
+ ],
+ meson_version: '>= 0.54.0')
+
+cc = meson.get_compiler('c')
+
+common_cflags = cc.get_supported_arguments([
+ '-fgnu89-inline',
+ '-fvisibility=hidden',
+ '-std=gnu99',
+ '-Wall',
+ '-Wundef',
+ '-Wunused',
+ '-Wstrict-prototypes',
+ '-Werror-implicit-function-declaration',
+ '-Wno-pointer-sign',
+ '-Wshadow'
+])
+
+prefix = get_option('prefix')
+libexecdir = prefix / get_option('libexecdir')
+bindir = get_option('bindir')
+dbusconfdir = get_option('sysconfdir') / 'dbus-1' / 'system.d'
+dbusservicedir = get_option('datadir') / 'dbus-1' / 'system-services'
+
+systemd_system_unit_dir = get_option('systemdsystemunitdir')
+if systemd_system_unit_dir == 'auto'
+ systemd_dep = dependency('systemd')
+ systemd_system_unit_dir = systemd_dep.get_pkgconfig_variable('systemdsystemunitdir')
+endif
+gio_dep = dependency('gio-2.0')
+gudev_dep = dependency('gudev-1.0', version: '>= 232')
+upower_dep = dependency('upower-glib')
+
+gnome = import('gnome')
+
+add_global_arguments('-D_GNU_SOURCE=1', language: 'c')
+
+subdir('src')
+subdir('data')
+
+if get_option('gtk_doc')
+ # Make COPYING available in the build root for docs
+ configure_file(
+ input: 'COPYING',
+ output: 'COPYING',
+ copy: true,
+ )
+ subdir('docs')
+endif
+
+subdir('tests')
diff --git a/meson_options.txt b/meson_options.txt
new file mode 100644
index 0000000..a3789f6
--- /dev/null
+++ b/meson_options.txt
@@ -0,0 +1,8 @@
+option('systemdsystemunitdir',
+ description: 'systemd unit directory',
+ type: 'string',
+ value: 'auto')
+option('gtk_doc',
+ type: 'boolean',
+ value: false,
+ description: 'Build docs')
diff --git a/src/meson.build b/src/meson.build
new file mode 100644
index 0000000..71625d7
--- /dev/null
+++ b/src/meson.build
@@ -0,0 +1,53 @@
+deps = [ gio_dep, gudev_dep, upower_dep ]
+
+resources = gnome.compile_resources(
+ 'power-profiles-daemon-resources', 'power-profiles-daemon.gresource.xml',
+ c_name: 'power_profiles_daemon',
+ source_dir: '.',
+ export: true
+)
+
+sources = [
+ 'ppd-profile.c',
+ 'ppd-utils.c',
+ 'ppd-action.c',
+ 'ppd-driver.c',
+ resources,
+]
+
+enums = 'ppd-enums'
+sources += gnome.mkenums(
+ enums,
+ sources: 'ppd-profile.h',
+ c_template: enums + '.c.in',
+ h_template: enums + '.h.in'
+)
+
+lib_libpower_profiles_daemon = shared_library(
+ 'libppd',
+ sources,
+ dependencies: deps,
+ install: false
+)
+
+libpower_profiles_daemon_dep = declare_dependency(
+ dependencies: deps,
+ link_with: lib_libpower_profiles_daemon,
+)
+
+sources += [
+ 'power-profiles-daemon.c',
+ 'ppd-action-trickle-charge.c',
+ 'ppd-driver-intel-pstate.c',
+ 'ppd-driver-lenovo-dytc.c',
+ 'ppd-driver-balanced.c',
+ 'ppd-driver-power-saver.c',
+ 'ppd-driver-fake.c',
+]
+
+executable('power-profiles-daemon',
+ sources,
+ dependencies: deps,
+ install: true,
+ install_dir: libexecdir
+)
diff --git a/src/net.hadess.PowerProfiles.xml b/src/net.hadess.PowerProfiles.xml
new file mode 100644
index 0000000..fce04a8
--- /dev/null
+++ b/src/net.hadess.PowerProfiles.xml
@@ -0,0 +1,76 @@
+<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
+"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
+
+<node>
+
+ <!--
+ net.hadess.PowerProfiles:
+ @short_description: Power Profiles daemon
+
+ The power-profiles-daemon API is meant to be used by parts of the OS or
+ desktop environment to switch system power profiles based on user choice,
+ or user intent.
+
+ OS components would typically use the "Profiles" property to construct
+ their UI (2 or 3 profiles available), and monitor the "ActiveProfile"
+ and the "PerformanceInhibited" properties to update that UI. The UI
+ would try to set the "ActiveProfile" property if the user selected
+ a different one.
+
+ Note that the reason why the project exists and how it is different from
+ existing projects is explained <ulink href=" https://gitlab.freedesktop.org/hadess/power-profiles-daemon/-/blob/master/README.md">
+ in the project's README file</ulink>.
+
+ The object path will be "/net/hadess/PowerProfiles".
+ -->
+ <interface name="net.hadess.PowerProfiles">
+ <!--
+ ActiveProfile:
+
+ The type of the currently active profile. It might change automatically
+ if the "performance" profile was selected but it got inhibited, in which
+ case the "PerformanceInhibited" property will reflect the reason.
+ -->
+ <property name="ActiveProfile" type="s" access="readwrite"/>
+
+ <!--
+ PerformanceInhibited:
+
+ This will be set if the performance power profile is unavailable, with
+ the value being used to identify the reason for unavailability. As new
+ reasons can be added, it is recommended that front-ends show a generic
+ reason if they do not recognise the value. Possible values are:
+ - "lap-detected" (the computer is sitting on the user's lap)
+ - "high-operating-temperature" (the computer is close to overheating)
+ - "" (the empty string, if not inhibited)
+ -->
+ <property name="PerformanceInhibited" type="s" access="read"/>
+
+ <!--
+ Profiles:
+
+ An array of key-pair values representing each profile. The key named
+ "Driver" (s) identifies the power-profiles-daemon backend code used to
+ implement the profile.
+
+ The key named "Profile" (s) will be one of:
+ - "power-saver" (battery saving profile)
+ - "balanced" (the default profile)
+ - "performance" (a profile that does not care about noise or battery consumption)
+
+ Only one of each type of profile will be listed, with the daemon choosing the
+ more appropriate "driver" for each profile type.
+ -->
+ <property name="Profiles" type="aa{sv}" access="read"/>
+
+ <!--
+ Actions:
+
+ An array of strings listing each one of the "actions" implemented in
+ the running daemon. This is used by API users to figure out whether
+ particular functionality is available in a version of the daemon.
+ -->
+ <property name="Actions" type="as" access="read"/>
+
+ </interface>
+</node>
diff --git a/src/power-profiles-daemon.c b/src/power-profiles-daemon.c
new file mode 100644
index 0000000..77c561d
--- /dev/null
+++ b/src/power-profiles-daemon.c
@@ -0,0 +1,608 @@
+/*
+ * Copyright (c) 2014-2016, 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#include <locale.h>
+
+#include "power-profiles-daemon-resources.h"
+#include "power-profiles-daemon.h"
+#include "ppd-driver.h"
+#include "ppd-action.h"
+#include "ppd-enums.h"
+
+#define POWER_PROFILES_DBUS_NAME "net.hadess.PowerProfiles"
+#define POWER_PROFILES_DBUS_PATH "/net/hadess/PowerProfiles"
+#define POWER_PROFILES_IFACE_NAME POWER_PROFILES_DBUS_NAME
+
+GMainLoop *main_loop = NULL;
+
+typedef struct {
+ GDBusNodeInfo *introspection_data;
+ GDBusConnection *connection;
+ guint name_id;
+ int ret;
+
+ PpdProfile active_profile;
+ GPtrArray *drivers;
+ GPtrArray *actions;
+} PpdApp;
+
+static PpdDriver *
+get_driver_for_profile (PpdApp *data,
+ PpdProfile profile)
+{
+ guint i;
+
+ g_return_val_if_fail (ppd_profile_has_single_flag (profile), NULL);
+
+ for (i = 0; i < data->drivers->len; i++) {
+ PpdDriver *driver = g_ptr_array_index (data->drivers, i);
+
+ if (ppd_driver_get_profiles (driver) & profile)
+ return driver;
+ }
+
+ return NULL;
+}
+
+#define GET_DRIVER(p) (get_driver_for_profile (data, p))
+#define ACTIVE_DRIVER (get_driver_for_profile (data, data->active_profile))
+
+/* profile drivers and actions */
+#include "ppd-action-trickle-charge.h"
+#include "ppd-driver-balanced.h"
+#include "ppd-driver-power-saver.h"
+#include "ppd-driver-lenovo-dytc.h"
+#include "ppd-driver-intel-pstate.h"
+#include "ppd-driver-fake.h"
+
+typedef GType (*GTypeGetFunc) (void);
+
+static GTypeGetFunc objects[] = {
+ /* Hardware specific profile drivers */
+ ppd_driver_fake_get_type,
+ ppd_driver_lenovo_dytc_get_type,
+ ppd_driver_intel_pstate_get_type,
+
+ /* Generic profile drivers */
+ ppd_driver_balanced_get_type,
+ ppd_driver_power_saver_get_type,
+
+ /* Actions */
+ ppd_action_trickle_charge_get_type,
+};
+
+typedef enum {
+ PROP_ACTIVE_PROFILE = 1 << 0,
+ PROP_INHIBITED = 1 << 1,
+ PROP_PROFILES = 1 << 2,
+ PROP_ACTIONS = 1 << 3,
+} PropertiesMask;
+
+#define PROP_ALL (PROP_ACTIVE_PROFILE | PROP_INHIBITED | PROP_PROFILES | PROP_ACTIONS)
+
+static const char *
+get_active_profile (PpdApp *data)
+{
+ return ppd_profile_to_str (data->active_profile);
+}
+
+static const char *
+get_performance_inhibited (PpdApp *data)
+{
+ PpdDriver *driver;
+ const char *ret;
+
+ driver = GET_DRIVER(PPD_PROFILE_PERFORMANCE);
+ if (!driver)
+ return "";
+ ret = ppd_driver_get_performance_inhibited (driver);
+ g_assert (ret != NULL);
+ return ret;
+}
+
+static GVariant *
+get_profiles_variant (PpdApp *data)
+{
+ GVariantBuilder builder;
+ guint i;
+
+ g_variant_builder_init (&builder, G_VARIANT_TYPE ("aa{sv}"));
+
+ for (i = 0; i < NUM_PROFILES; i++) {
+ PpdDriver *driver = GET_DRIVER(1 << i);
+ GVariantBuilder asv_builder;
+
+ if (driver == NULL)
+ continue;
+
+ g_variant_builder_init (&asv_builder, G_VARIANT_TYPE ("a{sv}"));
+ g_variant_builder_add (&asv_builder, "{sv}", "Profile",
+ g_variant_new_string (ppd_profile_to_str (1 << i)));
+ g_variant_builder_add (&asv_builder, "{sv}", "Driver",
+ g_variant_new_string (ppd_driver_get_driver_name (driver)));
+
+ g_variant_builder_add (&builder, "a{sv}", &asv_builder);
+ }
+
+ return g_variant_builder_end (&builder);
+}
+
+static GVariant *
+get_actions_variant (PpdApp *data)
+{
+ GVariantBuilder builder;
+ guint i;
+
+ g_variant_builder_init (&builder, G_VARIANT_TYPE ("as"));
+
+ for (i = 0; i < data->actions->len; i++) {
+ PpdAction *action = g_ptr_array_index (data->actions, i);
+
+ g_variant_builder_add (&builder, "s", ppd_action_get_action_name (action));
+ }
+
+ return g_variant_builder_end (&builder);
+}
+
+static void
+send_dbus_event (PpdApp *data,
+ PropertiesMask mask)
+{
+ GVariantBuilder props_builder;
+ GVariant *props_changed = NULL;
+
+ g_assert (data->connection);
+
+ if (mask == 0)
+ return;
+
+ g_assert ((mask & PROP_ALL) != 0);
+
+ g_variant_builder_init (&props_builder, G_VARIANT_TYPE ("a{sv}"));
+
+ if (mask & PROP_ACTIVE_PROFILE) {
+ g_variant_builder_add (&props_builder, "{sv}", "ActiveProfile",
+ g_variant_new_string (get_active_profile (data)));
+ }
+ if (mask & PROP_INHIBITED) {
+ g_variant_builder_add (&props_builder, "{sv}", "PerformanceInhibited",
+ g_variant_new_string (get_performance_inhibited (data)));
+ }
+ if (mask & PROP_PROFILES) {
+ g_variant_builder_add (&props_builder, "{sv}", "Profiles",
+ get_profiles_variant (data));
+ }
+ if (mask & PROP_ACTIONS) {
+ g_variant_builder_add (&props_builder, "{sv}", "Actions",
+ get_actions_variant (data));
+ }
+
+ props_changed = g_variant_new ("(s at a{sv}@as)", POWER_PROFILES_IFACE_NAME,
+ g_variant_builder_end (&props_builder),
+ g_variant_new_strv (NULL, 0));
+
+ g_dbus_connection_emit_signal (data->connection,
+ NULL,
+ POWER_PROFILES_DBUS_PATH,
+ "org.freedesktop.DBus.Properties",
+ "PropertiesChanged",
+ props_changed, NULL);
+}
+
+static void
+actions_activate_profile (GPtrArray *actions,
+ PpdProfile profile)
+{
+ guint i;
+
+ g_return_if_fail (actions != NULL);
+
+ for (i = 0; i < actions->len; i++) {
+ g_autoptr(GError) error = NULL;
+ PpdAction *action;
+ gboolean ret;
+
+ action = g_ptr_array_index (actions, i);
+
+ ret = ppd_action_activate_profile (action, profile, &error);
+ if (!ret)
+ g_warning ("Failed to activate action '%s' to profile %s: %s",
+ ppd_profile_to_str (profile),
+ ppd_action_get_action_name (action),
+ error->message);
+ }
+}
+
+static void
+activate_target_profile (PpdApp *data,
+ PpdProfile target_profile)
+{
+ guint i;
+
+ g_debug ("Setting active profile '%s' (current: '%s')",
+ ppd_profile_to_str (target_profile),
+ ppd_profile_to_str (data->active_profile));
+
+ for (i = 0; i < data->drivers->len; i++) {
+ PpdDriver *driver = g_ptr_array_index (data->drivers, i);
+ g_autoptr(GError) error = NULL;
+
+ if (!ppd_driver_activate_profile (driver, target_profile, &error)) {
+ g_warning ("Failed to activate driver '%s': %s",
+ ppd_driver_get_driver_name (driver),
+ error->message);
+ }
+ }
+
+ actions_activate_profile (data->actions, target_profile);
+
+ data->active_profile = target_profile;
+}
+
+static gboolean
+set_active_profile (PpdApp *data,
+ const char *profile,
+ GError **error)
+{
+ PpdProfile target_profile;
+
+ target_profile = ppd_profile_from_str (profile);
+ if (target_profile == PPD_PROFILE_UNSET) {
+ g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
+ "Invalid profile name '%s'", profile);
+ return FALSE;
+ }
+
+ if (target_profile == data->active_profile) {
+ g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
+ "Profile '%s' already active", profile);
+ return FALSE;
+ }
+
+ if (target_profile == PPD_PROFILE_PERFORMANCE &&
+ ppd_driver_is_performance_inhibited (GET_DRIVER (PPD_PROFILE_PERFORMANCE))) {
+ g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
+ "Profile '%s' is inhibited", profile);
+ return FALSE;
+ }
+
+ g_debug ("Transitioning active profile from '%s' to '%s'",
+ ppd_profile_to_str (data->active_profile), profile);
+ data->active_profile = target_profile;
+
+ activate_target_profile (data, target_profile);
+ send_dbus_event (data, PROP_ACTIVE_PROFILE);
+
+ return TRUE;
+}
+
+static void
+driver_performance_inhibited_changed_cb (GObject *gobject,
+ GParamSpec *pspec,
+ gpointer user_data)
+{
+ PpdApp *data = user_data;
+ PpdDriver *driver = PPD_DRIVER (gobject);
+ const char *prop_str = pspec->name;
+
+ if (g_strcmp0 (prop_str, "performance-inhibited") != 0) {
+ g_warning ("Ignoring '%s' property change on profile driver '%s'",
+ prop_str, ppd_driver_get_driver_name (driver));
+ return;
+ }
+
+ if (!(ppd_driver_get_profiles (driver) & PPD_PROFILE_PERFORMANCE)) {
+ g_warning ("Ignored 'performance-inhibited' change on non-performance driver '%s'",
+ ppd_driver_get_driver_name (driver));
+ return;
+ }
+
+ send_dbus_event (data, PROP_INHIBITED);
+ if (!ppd_driver_is_performance_inhibited (driver))
+ return;
+
+ activate_target_profile (data, PPD_PROFILE_BALANCED);
+ send_dbus_event (data, PROP_ACTIVE_PROFILE);
+}
+
+static GVariant *
+handle_get_property (GDBusConnection *connection,
+ const gchar *sender,
+ const gchar *object_path,
+ const gchar *interface_name,
+ const gchar *property_name,
+ GError **error,
+ gpointer user_data)
+{
+ PpdApp *data = user_data;
+
+ g_assert (data->connection);
+
+ if (g_strcmp0 (property_name, "ActiveProfile") == 0)
+ return g_variant_new_string (get_active_profile (data));
+ if (g_strcmp0 (property_name, "PerformanceInhibited") == 0)
+ return g_variant_new_string (get_performance_inhibited (data));
+ if (g_strcmp0 (property_name, "Profiles") == 0)
+ return get_profiles_variant (data);
+ if (g_strcmp0 (property_name, "Actions") == 0)
+ return get_actions_variant (data);
+ return NULL;
+}
+
+static gboolean
+handle_set_property (GDBusConnection *connection,
+ const gchar *sender,
+ const gchar *object_path,
+ const gchar *interface_name,
+ const gchar *property_name,
+ GVariant *value,
+ GError **error,
+ gpointer user_data)
+{
+ PpdApp *data = user_data;
+ const char *profile;
+
+ g_assert (data->connection);
+
+ if (g_strcmp0 (property_name, "ActiveProfile") != 0) {
+ g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
+ "No such property: %s", property_name);
+ return FALSE;
+ }
+
+ g_variant_get (value, "&s", &profile);
+ return set_active_profile (data, profile, error);
+}
+
+static const GDBusInterfaceVTable interface_vtable =
+{
+ NULL,
+ handle_get_property,
+ handle_set_property
+};
+
+static void
+name_lost_handler (GDBusConnection *connection,
+ const gchar *name,
+ gpointer user_data)
+{
+ g_debug ("power-profiles-daemon is already running, or it cannot own its D-Bus name. Verify installation.");
+ exit (0);
+}
+
+static void
+bus_acquired_handler (GDBusConnection *connection,
+ const gchar *name,
+ gpointer user_data)
+{
+ PpdApp *data = user_data;
+
+ g_dbus_connection_register_object (connection,
+ POWER_PROFILES_DBUS_PATH,
+ data->introspection_data->interfaces[0],
+ &interface_vtable,
+ data,
+ NULL,
+ NULL);
+
+ data->connection = g_object_ref (connection);
+}
+
+static gboolean
+has_required_drivers (PpdApp *data)
+{
+ PpdDriver *driver;
+
+ driver = GET_DRIVER (PPD_PROFILE_BALANCED);
+ if (!driver || !G_IS_OBJECT (driver))
+ return FALSE;
+ driver = GET_DRIVER (PPD_PROFILE_POWER_SAVER);
+ if (!driver || !G_IS_OBJECT (driver))
+ return FALSE;
+
+ return TRUE;
+}
+
+static gboolean
+profile_already_handled (PpdApp *data,
+ PpdDriver *driver,
+ PpdProfile profiles)
+{
+ guint i;
+
+ for (i = 0; i < NUM_PROFILES; i++) {
+ PpdDriver *existing_driver;
+
+ if (!(profiles & (1 << i)))
+ continue;
+
+ existing_driver = GET_DRIVER(1 << i);
+ if (existing_driver) {
+ g_debug ("Driver '%s' conflicts with already probed driver '%s' for profile %s",
+ ppd_driver_get_driver_name (driver),
+ ppd_driver_get_driver_name (existing_driver),
+ ppd_profile_to_str (1 << i));
+ return TRUE;
+ }
+ }
+
+ return FALSE;
+}
+
+static void
+name_acquired_handler (GDBusConnection *connection,
+ const gchar *name,
+ gpointer user_data)
+{
+ PpdApp *data = user_data;
+ guint i;
+
+ for (i = 0; i < G_N_ELEMENTS (objects); i++) {
+ GObject *object;
+
+ object = g_object_new (objects[i](), NULL);
+ if (PPD_IS_DRIVER (object)) {
+ PpdDriver *driver = PPD_DRIVER (object);
+ PpdProfile profiles;
+
+ g_debug ("Handling driver '%s'", ppd_driver_get_driver_name (driver));
+
+ profiles = ppd_driver_get_profiles (driver);
+ if (!(profiles & PPD_PROFILE_ALL)) {
+ g_warning ("Profile Driver '%s' implements invalid profiles '0x%X'",
+ ppd_driver_get_driver_name (driver),
+ profiles);
+ g_object_unref (object);
+ continue;
+ }
+
+ if (profile_already_handled (data, driver, profiles)) {
+ g_object_unref (object);
+ continue;
+ }
+
+ if (!ppd_driver_probe (driver)) {
+ g_debug ("probe() failed for driver %s, skipping",
+ ppd_driver_get_driver_name (driver));
+ g_object_unref (object);
+ continue;
+ }
+
+ g_ptr_array_add (data->drivers, driver);
+
+ g_signal_connect (G_OBJECT (driver), "notify::performance-inhibited",
+ G_CALLBACK (driver_performance_inhibited_changed_cb), data);
+ } else if (PPD_IS_ACTION (object)) {
+ PpdAction *action = PPD_ACTION (object);
+
+ g_debug ("Handling action '%s'", ppd_action_get_action_name (action));
+
+ if (!ppd_action_probe (action)) {
+ g_debug ("probe() failed for action '%s', skipping",
+ ppd_action_get_action_name (action));
+ g_object_unref (object);
+ continue;
+ }
+
+ g_ptr_array_add (data->actions, action);
+ } else {
+ g_assert_not_reached ();
+ }
+ }
+
+ if (!has_required_drivers (data)) {
+ g_warning ("Some non-optional profile drivers are missing, programmer error");
+ goto bail;
+ }
+
+ /* Set initial state */
+ activate_target_profile (data, data->active_profile);
+
+ send_dbus_event (data, PROP_ALL);
+
+ return;
+
+bail:
+ data->ret = 0;
+ g_debug ("Exiting because some non recoverable error occurred during startup");
+ g_main_loop_quit (main_loop);
+}
+
+static gboolean
+setup_dbus (PpdApp *data,
+ gboolean replace)
+{
+ GBytes *bytes;
+ GBusNameOwnerFlags flags;
+
+ bytes = g_resources_lookup_data ("/net/hadess/PowerProfiles/net.hadess.PowerProfiles.xml",
+ G_RESOURCE_LOOKUP_FLAGS_NONE,
+ NULL);
+ data->introspection_data = g_dbus_node_info_new_for_xml (g_bytes_get_data (bytes, NULL), NULL);
+ g_bytes_unref (bytes);
+ g_assert (data->introspection_data != NULL);
+
+ flags = G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT;
+ if (replace)
+ flags |= G_BUS_NAME_OWNER_FLAGS_REPLACE;
+
+ data->name_id = g_bus_own_name (G_BUS_TYPE_SYSTEM,
+ POWER_PROFILES_DBUS_NAME,
+ flags,
+ bus_acquired_handler,
+ name_acquired_handler,
+ name_lost_handler,
+ data,
+ NULL);
+
+ return TRUE;
+}
+
+static void
+free_app_data (PpdApp *data)
+{
+ if (data == NULL)
+ return;
+
+ if (data->name_id != 0) {
+ g_bus_unown_name (data->name_id);
+ data->name_id = 0;
+ }
+
+ g_ptr_array_free (data->actions, TRUE);
+ g_ptr_array_free (data->drivers, TRUE);
+
+ g_clear_pointer (&data->introspection_data, g_dbus_node_info_unref);
+ g_clear_object (&data->connection);
+ g_clear_pointer (&main_loop, g_main_loop_unref);
+ g_free (data);
+}
+
+int main (int argc, char **argv)
+{
+ PpdApp *data;
+ int ret = 0;
+ g_autoptr(GOptionContext) option_context = NULL;
+ g_autoptr(GError) error = NULL;
+ gboolean verbose = FALSE;
+ gboolean replace = FALSE;
+ const GOptionEntry options[] = {
+ { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Show extra debugging information", NULL },
+ { "replace", 'r', 0, G_OPTION_ARG_NONE, &replace, "Replace the running instance of power-profiles-daemon", NULL },
+ { NULL}
+ };
+
+ setlocale (LC_ALL, "");
+ option_context = g_option_context_new ("");
+ g_option_context_add_main_entries (option_context, options, NULL);
+
+ ret = g_option_context_parse (option_context, &argc, &argv, &error);
+ if (!ret) {
+ g_print ("Failed to parse arguments: %s\n", error->message);
+ return EXIT_FAILURE;
+ }
+
+ if (verbose)
+ g_setenv ("G_MESSAGES_DEBUG", "all", TRUE);
+
+ data = g_new0 (PpdApp, 1);
+ data->actions = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
+ data->drivers = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
+ data->active_profile = PPD_PROFILE_BALANCED;
+
+ /* Set up D-Bus */
+ setup_dbus (data, replace);
+
+ main_loop = g_main_loop_new (NULL, TRUE);
+ g_main_loop_run (main_loop);
+ ret = data->ret;
+ free_app_data (data);
+
+ return ret;
+}
diff --git a/src/power-profiles-daemon.gresource.xml b/src/power-profiles-daemon.gresource.xml
new file mode 100644
index 0000000..ae1ee65
--- /dev/null
+++ b/src/power-profiles-daemon.gresource.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<gresources>
+ <gresource prefix="/net/hadess/PowerProfiles">
+ <file preprocess="xml-stripblanks">net.hadess.PowerProfiles.xml</file>
+ </gresource>
+</gresources>
+
diff --git a/src/power-profiles-daemon.h b/src/power-profiles-daemon.h
new file mode 100644
index 0000000..53ca8f2
--- /dev/null
+++ b/src/power-profiles-daemon.h
@@ -0,0 +1,14 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#pragma once
+
+#include "ppd-profile.h"
+
+#define NUM_PROFILES 3
diff --git a/src/ppd-action-trickle-charge.c b/src/ppd-action-trickle-charge.c
new file mode 100644
index 0000000..3c573ca
--- /dev/null
+++ b/src/ppd-action-trickle-charge.c
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#include <gudev/gudev.h>
+
+#include "ppd-action-trickle-charge.h"
+#include "ppd-profile.h"
+#include "ppd-utils.h"
+
+#define CHARGE_TYPE_SYSFS_NAME "charge_type"
+
+struct _PpdActionTrickleCharge
+{
+ PpdAction parent_instance;
+
+ GUdevClient *client;
+ gboolean active;
+};
+
+G_DEFINE_TYPE (PpdActionTrickleCharge, ppd_action_trickle_charge, PPD_TYPE_ACTION)
+
+static GObject*
+ppd_action_trickle_charge_constructor (GType type,
+ guint n_construct_params,
+ GObjectConstructParam *construct_params)
+{
+ GObject *object;
+
+ object = G_OBJECT_CLASS (ppd_action_trickle_charge_parent_class)->constructor (type,
+ n_construct_params,
+ construct_params);
+ g_object_set (object,
+ "action-name", "trickle_charge",
+ NULL);
+
+ return object;
+}
+
+static void
+set_charge_type (PpdActionTrickleCharge *action,
+ const char *charge_type)
+{
+ GList *devices, *l;
+
+ devices = g_udev_client_query_by_subsystem (action->client, "power_supply");
+ if (devices == NULL)
+ return;
+
+ for (l = devices; l != NULL; l = l->next) {
+ GUdevDevice *dev = l->data;
+
+ if (!g_udev_device_has_sysfs_attr (dev, CHARGE_TYPE_SYSFS_NAME))
+ continue;
+
+ ppd_utils_write_sysfs (dev, CHARGE_TYPE_SYSFS_NAME, charge_type, NULL);
+
+ break;
+ }
+
+ g_list_free_full (devices, g_object_unref);
+}
+
+static gboolean
+ppd_action_trickle_charge_activate_profile (PpdAction *action,
+ PpdProfile profile,
+ GError **error)
+{
+ PpdActionTrickleCharge *self = PPD_ACTION_TRICKLE_CHARGE (action);
+
+ if (profile == PPD_PROFILE_POWER_SAVER) {
+ set_charge_type (self, "Trickle");
+ self->active = TRUE;
+ } else {
+ set_charge_type (self, "Fast");
+ self->active = FALSE;
+ }
+
+ return TRUE;
+}
+
+static void
+uevent_cb (GUdevClient *client,
+ gchar *action,
+ GUdevDevice *device,
+ gpointer user_data)
+{
+ PpdActionTrickleCharge *self = user_data;
+ const char *charge_type;
+
+ if (g_strcmp0 (action, "add") != 0)
+ return;
+
+ if (!g_udev_device_has_sysfs_attr (device, CHARGE_TYPE_SYSFS_NAME))
+ return;
+
+ charge_type = self->active ? "Trickle" : "Fast";
+ g_debug ("Updating charge type for '%s' to '%s'",
+ g_udev_device_get_sysfs_path (device),
+ charge_type);
+ ppd_utils_write_sysfs (device, CHARGE_TYPE_SYSFS_NAME, charge_type, NULL);
+}
+
+static void
+ppd_action_trickle_charge_finalize (GObject *object)
+{
+ PpdActionTrickleCharge *driver;
+
+ driver = PPD_ACTION_TRICKLE_CHARGE (object);
+ g_clear_object (&driver->client);
+ G_OBJECT_CLASS (ppd_action_trickle_charge_parent_class)->finalize (object);
+}
+
+static void
+ppd_action_trickle_charge_class_init (PpdActionTrickleChargeClass *klass)
+{
+ GObjectClass *object_class;
+ PpdActionClass *driver_class;
+
+ object_class = G_OBJECT_CLASS(klass);
+ object_class->constructor = ppd_action_trickle_charge_constructor;
+ object_class->finalize = ppd_action_trickle_charge_finalize;
+
+ driver_class = PPD_ACTION_CLASS(klass);
+ driver_class->activate_profile = ppd_action_trickle_charge_activate_profile;
+}
+
+static void
+ppd_action_trickle_charge_init (PpdActionTrickleCharge *self)
+{
+ const gchar * const subsystem[] = { "power_supply", NULL };
+
+ self->client = g_udev_client_new (subsystem);
+ g_signal_connect (G_OBJECT (self->client), "uevent",
+ G_CALLBACK (uevent_cb), self);
+}
diff --git a/src/ppd-action-trickle-charge.h b/src/ppd-action-trickle-charge.h
new file mode 100644
index 0000000..78ffd9b
--- /dev/null
+++ b/src/ppd-action-trickle-charge.h
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#pragma once
+
+#include "ppd-action.h"
+
+#define PPD_TYPE_ACTION_TRICKLE_CHARGE (ppd_action_trickle_charge_get_type())
+G_DECLARE_FINAL_TYPE(PpdActionTrickleCharge, ppd_action_trickle_charge, PPD, ACTION_TRICKLE_CHARGE, PpdAction)
diff --git a/src/ppd-action.c b/src/ppd-action.c
new file mode 100644
index 0000000..92ef128
--- /dev/null
+++ b/src/ppd-action.c
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#include "ppd-action.h"
+#include "ppd-enums.h"
+
+/**
+ * SECTION:ppd-action
+ * @Short_description: Profile Actions
+ * @Title: Profile Actions
+ *
+ * Profile actions are actions to run on profile change that do not affect
+ * the overall power usage, or performance level of the system, but instead
+ * of individual components.
+ *
+ * For example, an action might want to save energy when in the `power-saver`
+ * profile, and thus reduce the charging speed of a particular device. Or it
+ * could automatically reduce the speed of animations, or luminosity of an
+ * RGB keyboard.
+ *
+ * The list of actions that are currently running is available through the
+ * D-Bus API.
+ *
+ * Note that `power-profiles-daemon` can only accept #PpdAction<!-- -->s that
+ * will not make devices appear “broken” to users not in the know, so actions
+ * will never disable Wi-Fi or Bluetooth, or make some buttons stop working
+ * until power saving is turned off.
+ */
+
+typedef struct
+{
+ char *action_name;
+ PpdProfile profile;
+} PpdActionPrivate;
+
+enum {
+ PROP_0,
+ PROP_ACTION_NAME
+};
+
+#define PPD_ACTION_GET_PRIVATE(o) (ppd_action_get_instance_private (o))
+G_DEFINE_TYPE_WITH_PRIVATE (PpdAction, ppd_action, G_TYPE_OBJECT)
+
+static void
+ppd_action_set_property (GObject *object,
+ guint property_id,
+ const GValue *value,
+ GParamSpec *pspec)
+{
+ PpdAction *action = PPD_ACTION (object);
+ PpdActionPrivate *priv = PPD_ACTION_GET_PRIVATE (action);
+
+ switch (property_id) {
+ case PROP_ACTION_NAME:
+ g_assert (priv->action_name == NULL);
+ priv->action_name = g_value_dup_string (value);
+ break;
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec);
+ }
+}
+
+static void
+ppd_action_get_property (GObject *object,
+ guint property_id,
+ GValue *value,
+ GParamSpec *pspec)
+{
+ PpdAction *action = PPD_ACTION (object);
+ PpdActionPrivate *priv = PPD_ACTION_GET_PRIVATE (action);
+
+ switch (property_id) {
+ case PROP_ACTION_NAME:
+ g_value_set_string (value, priv->action_name);
+ break;
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec);
+ }
+}
+
+static void
+ppd_action_finalize (GObject *object)
+{
+ PpdActionPrivate *priv;
+
+ priv = PPD_ACTION_GET_PRIVATE (PPD_ACTION (object));
+ g_clear_pointer (&priv->action_name, g_free);
+
+ G_OBJECT_CLASS (ppd_action_parent_class)->finalize (object);
+}
+
+static void
+ppd_action_class_init (PpdActionClass *klass)
+{
+ GObjectClass *object_class;
+
+ object_class = G_OBJECT_CLASS(klass);
+ object_class->finalize = ppd_action_finalize;
+ object_class->get_property = ppd_action_get_property;
+ object_class->set_property = ppd_action_set_property;
+
+ /**
+ * PpdAction::action-name:
+ *
+ * A unique action name, only used for debugging.
+ */
+ g_object_class_install_property (object_class, PROP_ACTION_NAME,
+ g_param_spec_string("action-name",
+ "Action name",
+ "Action name",
+ NULL,
+ G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
+}
+
+static void
+ppd_action_init (PpdAction *self)
+{
+}
+
+gboolean
+ppd_action_probe (PpdAction *action)
+{
+ g_return_val_if_fail (PPD_IS_ACTION (action), FALSE);
+
+ if (!PPD_ACTION_GET_CLASS (action)->probe)
+ return TRUE;
+
+ return PPD_ACTION_GET_CLASS (action)->probe (action);
+}
+
+gboolean
+ppd_action_activate_profile (PpdAction *action,
+ PpdProfile profile,
+ GError **error)
+{
+ g_return_val_if_fail (PPD_IS_ACTION (action), FALSE);
+
+ if (!PPD_ACTION_GET_CLASS (action)->activate_profile)
+ return TRUE;
+
+ return PPD_ACTION_GET_CLASS (action)->activate_profile (action, profile, error);
+}
+
+const char *
+ppd_action_get_action_name (PpdAction *action)
+{
+ PpdActionPrivate *priv;
+
+ g_return_val_if_fail (PPD_IS_ACTION (action), NULL);
+
+ priv = PPD_ACTION_GET_PRIVATE (action);
+ return priv->action_name;
+}
diff --git a/src/ppd-action.h b/src/ppd-action.h
new file mode 100644
index 0000000..dd5870a
--- /dev/null
+++ b/src/ppd-action.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#pragma once
+
+#include <glib-object.h>
+#include "ppd-profile.h"
+
+#define PPD_TYPE_ACTION (ppd_action_get_type())
+G_DECLARE_DERIVABLE_TYPE(PpdAction, ppd_action, PPD, ACTION, GObject)
+
+/**
+ * PpdActionClass:
+ * @parent_class: The parent class.
+ * @probe: Called by the daemon on startup.
+ * @activate_profile: Called by the daemon when the profile changes.
+ *
+ * New profile actions should derive from #PpdAction and implement
+ * at least @activate_profile.
+ */
+struct _PpdActionClass
+{
+ GObjectClass parent_class;
+
+ gboolean (* probe) (PpdAction *action);
+ gboolean (* activate_profile) (PpdAction *action,
+ PpdProfile profile,
+ GError **error);
+};
+
+#ifndef __GTK_DOC_IGNORE__
+gboolean ppd_action_probe (PpdAction *action);
+gboolean ppd_action_activate_profile (PpdAction *action, PpdProfile profile, GError **error);
+const char *ppd_action_get_action_name (PpdAction *action);
+#endif
diff --git a/src/ppd-driver-balanced.c b/src/ppd-driver-balanced.c
new file mode 100644
index 0000000..6ddbac9
--- /dev/null
+++ b/src/ppd-driver-balanced.c
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#include "ppd-driver-balanced.h"
+
+struct _PpdDriverBalanced
+{
+ PpdDriver parent_instance;
+};
+
+G_DEFINE_TYPE (PpdDriverBalanced, ppd_driver_balanced, PPD_TYPE_DRIVER)
+
+static GObject*
+ppd_driver_balanced_constructor (GType type,
+ guint n_construct_params,
+ GObjectConstructParam *construct_params)
+{
+ GObject *object;
+
+ object = G_OBJECT_CLASS (ppd_driver_balanced_parent_class)->constructor (type,
+ n_construct_params,
+ construct_params);
+ g_object_set (object,
+ "driver-name", "balanced",
+ "profiles", PPD_PROFILE_BALANCED,
+ NULL);
+
+ return object;
+}
+
+static void
+ppd_driver_balanced_class_init (PpdDriverBalancedClass *klass)
+{
+ GObjectClass *object_class;
+
+ object_class = G_OBJECT_CLASS(klass);
+ object_class->constructor = ppd_driver_balanced_constructor;
+}
+
+static void
+ppd_driver_balanced_init (PpdDriverBalanced *self)
+{
+}
diff --git a/src/ppd-driver-balanced.h b/src/ppd-driver-balanced.h
new file mode 100644
index 0000000..ce829ad
--- /dev/null
+++ b/src/ppd-driver-balanced.h
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#pragma once
+
+#include "ppd-driver.h"
+
+#define PPD_TYPE_DRIVER_BALANCED (ppd_driver_balanced_get_type())
+G_DECLARE_FINAL_TYPE(PpdDriverBalanced, ppd_driver_balanced, PPD, DRIVER_BALANCED, PpdDriver)
diff --git a/src/ppd-driver-fake.c b/src/ppd-driver-fake.c
new file mode 100644
index 0000000..e7d5975
--- /dev/null
+++ b/src/ppd-driver-fake.c
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#include "ppd-driver-fake.h"
+
+#include <unistd.h>
+#include <stdio.h>
+#include <termios.h>
+
+extern GMainLoop *main_loop;
+
+struct _PpdDriverFake
+{
+ PpdDriver parent_instance;
+
+ struct termios old_tio;
+ gboolean inhibited;
+};
+
+G_DEFINE_TYPE (PpdDriverFake, ppd_driver_fake, PPD_TYPE_DRIVER)
+
+static GObject*
+ppd_driver_fake_constructor (GType type,
+ guint n_construct_params,
+ GObjectConstructParam *construct_params)
+{
+ GObject *object;
+
+ object = G_OBJECT_CLASS (ppd_driver_fake_parent_class)->constructor (type,
+ n_construct_params,
+ construct_params);
+ g_object_set (object,
+ "driver-name", "fake",
+ "profiles", PPD_PROFILE_PERFORMANCE,
+ NULL);
+
+ return object;
+}
+
+static void
+toggle_inhibition (PpdDriverFake *fake)
+{
+ fake->inhibited = !fake->inhibited;
+
+ g_object_set (G_OBJECT (fake),
+ "performance-inhibited", fake->inhibited ? "lap-detected" : NULL,
+ NULL);
+}
+
+static void
+keyboard_usage (void)
+{
+ g_print ("Valid keys are: i (toggle inhibition), q/x (quit)\n");
+}
+
+static gboolean
+check_keyboard (GIOChannel *source,
+ GIOCondition condition,
+ PpdDriverFake *fake)
+{
+ GIOStatus status;
+ char buf[1];
+
+ status = g_io_channel_read_chars (source, buf, 1, NULL, NULL);
+ if (status == G_IO_STATUS_ERROR ||
+ status == G_IO_STATUS_EOF) {
+ g_warning ("Error checking keyboard");
+ return FALSE;
+ }
+
+ if (status == G_IO_STATUS_AGAIN)
+ return TRUE;
+
+ switch (buf[0]) {
+ case 'i':
+ g_print ("Toggling inhibition\n");
+ toggle_inhibition (fake);
+ break;
+ case 'q':
+ case 'x':
+ g_main_loop_quit (main_loop);
+ break;
+ default:
+ keyboard_usage ();
+ return TRUE;
+ }
+
+ return TRUE;
+}
+
+static gboolean
+setup_keyboard (PpdDriverFake *fake)
+{
+ GIOChannel *channel;
+ struct termios new_tio;
+
+ tcgetattr(STDIN_FILENO, &fake->old_tio);
+ new_tio = fake->old_tio;
+ new_tio.c_lflag &=(~ICANON & ~ECHO);
+ tcsetattr(STDIN_FILENO, TCSANOW, &new_tio);
+
+ channel = g_io_channel_unix_new (STDIN_FILENO);
+ if (!channel) {
+ g_warning ("Failed to open stdin");
+ return FALSE;
+ }
+
+ if (g_io_channel_set_encoding (channel, NULL, NULL) != G_IO_STATUS_NORMAL) {
+ g_warning ("Failed to set stdin encoding to NULL");
+ return FALSE;
+ }
+
+ g_io_add_watch (channel, G_IO_IN, (GIOFunc) check_keyboard, fake);
+ return TRUE;
+}
+
+static gboolean
+envvar_set (const char *key)
+{
+ const char *value;
+
+ value = g_getenv (key);
+ if (value == NULL ||
+ *value == '0' ||
+ *value == 'f')
+ return FALSE;
+
+ return TRUE;
+}
+
+static gboolean
+ppd_driver_fake_probe (PpdDriver *driver)
+{
+ PpdDriverFake *fake;
+
+ if (!envvar_set ("POWER_PROFILE_DAEMON_FAKE_DRIVER"))
+ return FALSE;
+
+ fake = PPD_DRIVER_FAKE (driver);
+ if (!setup_keyboard (fake))
+ return FALSE;
+ keyboard_usage ();
+
+ return TRUE;
+}
+
+static void
+ppd_driver_fake_finalize (GObject *object)
+{
+ PpdDriverFake *fake;
+
+ fake = PPD_DRIVER_FAKE (object);
+ tcsetattr(STDIN_FILENO, TCSANOW, &fake->old_tio);
+ G_OBJECT_CLASS (ppd_driver_fake_parent_class)->finalize (object);
+}
+
+static void
+ppd_driver_fake_class_init (PpdDriverFakeClass *klass)
+{
+ GObjectClass *object_class;
+ PpdDriverClass *driver_class;
+
+ object_class = G_OBJECT_CLASS(klass);
+ object_class->constructor = ppd_driver_fake_constructor;
+ object_class->finalize = ppd_driver_fake_finalize;
+
+ driver_class = PPD_DRIVER_CLASS(klass);
+ driver_class->probe = ppd_driver_fake_probe;
+}
+
+static void
+ppd_driver_fake_init (PpdDriverFake *self)
+{
+}
diff --git a/src/ppd-driver-fake.h b/src/ppd-driver-fake.h
new file mode 100644
index 0000000..6ab2f82
--- /dev/null
+++ b/src/ppd-driver-fake.h
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#pragma once
+
+#include "ppd-driver.h"
+
+#define PPD_TYPE_DRIVER_FAKE (ppd_driver_fake_get_type())
+G_DECLARE_FINAL_TYPE(PpdDriverFake, ppd_driver_fake, PPD, DRIVER_FAKE, PpdDriver)
diff --git a/src/ppd-driver-intel-pstate.c b/src/ppd-driver-intel-pstate.c
new file mode 100644
index 0000000..4d21524
--- /dev/null
+++ b/src/ppd-driver-intel-pstate.c
@@ -0,0 +1,288 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#include <upower.h>
+
+#include "ppd-utils.h"
+#include "ppd-driver-intel-pstate.h"
+
+#define CPUFREQ_POLICY_DIR "/devices/system/cpu/cpufreq/"
+#define NO_TURBO_PATH "/devices/system/cpu/intel_pstate/no_turbo"
+
+struct _PpdDriverIntelPstate
+{
+ PpdDriver parent_instance;
+
+ UpClient *client;
+ PpdProfile activated_profile;
+ gboolean on_battery;
+ GList *devices; /* GList of paths */
+ GFileMonitor *no_turbo_mon;
+ char *no_turbo_path;
+};
+
+G_DEFINE_TYPE (PpdDriverIntelPstate, ppd_driver_intel_pstate, PPD_TYPE_DRIVER)
+
+static gboolean ppd_driver_intel_pstate_activate_profile (PpdDriver *driver,
+ PpdProfile profile,
+ GError **error);
+
+static GObject*
+ppd_driver_intel_pstate_constructor (GType type,
+ guint n_construct_params,
+ GObjectConstructParam *construct_params)
+{
+ GObject *object;
+
+ object = G_OBJECT_CLASS (ppd_driver_intel_pstate_parent_class)->constructor (type,
+ n_construct_params,
+ construct_params);
+ g_object_set (object,
+ "driver-name", "intel_pstate",
+ "profiles", PPD_PROFILE_PERFORMANCE | PPD_PROFILE_BALANCED | PPD_PROFILE_POWER_SAVER,
+ NULL);
+
+ return object;
+}
+
+static void
+on_battery_changed (GObject *gobject,
+ GParamSpec *pspec,
+ gpointer user_data)
+{
+ PpdDriverIntelPstate *pstate = user_data;
+ gboolean old_on_battery;
+
+ old_on_battery = pstate->on_battery;
+ pstate->on_battery = up_client_get_on_battery (pstate->client);
+
+ if (pstate->activated_profile == PPD_PROFILE_BALANCED) {
+ ppd_driver_intel_pstate_activate_profile (PPD_DRIVER (pstate),
+ pstate->activated_profile,
+ NULL);
+ }
+
+ g_debug ("Battery status changed from %s to %s",
+ old_on_battery ? "on battery" : "on mains",
+ pstate->on_battery ? "on battery" : "on mains");
+}
+
+static void
+update_no_turbo (PpdDriverIntelPstate *pstate)
+{
+ g_autofree char *contents = NULL;
+ gboolean turbo_disabled = FALSE;
+
+ if (g_file_get_contents (pstate->no_turbo_path, &contents, NULL, NULL)) {
+ if (g_strcmp0 (contents, "1") == 0)
+ turbo_disabled = TRUE;
+ }
+
+ g_object_set (G_OBJECT (pstate), "performance-inhibited",
+ turbo_disabled ? "high-operating-temperature" : NULL,
+ NULL);
+}
+
+static void
+no_turbo_changed (GFileMonitor *monitor,
+ GFile *file,
+ GFile *other_file,
+ GFileMonitorEvent event_type,
+ gpointer user_data)
+{
+ PpdDriverIntelPstate *pstate = user_data;
+ g_autofree char *path = NULL;
+
+ path = g_file_get_path (file);
+ g_debug ("File monitor change happened for '%s'", path);
+ update_no_turbo (pstate);
+}
+
+static GFileMonitor *
+monitor_no_turbo_prop (const char *path)
+{
+ g_autoptr(GFile) no_turbo = NULL;
+
+ if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
+ g_debug ("Not monitoring '%s' as it does not exist", path);
+ return NULL;
+ }
+
+ g_debug ("About to start monitoring '%s'", path);
+ no_turbo = g_file_new_for_path (path);
+ return g_file_monitor (no_turbo, G_FILE_MONITOR_NONE, NULL, NULL);
+}
+
+static char *
+get_no_turbo_path (void)
+{
+ const char *root;
+ g_autofree char *dir = NULL;
+
+ root = g_getenv ("UMOCKDEV_DIR");
+ if (!root || *root == '\0')
+ root = "/sys";
+
+ return g_build_filename (root, NO_TURBO_PATH, NULL);
+}
+
+static char *
+get_policy_dir (void)
+{
+ const char *root;
+ g_autofree char *dir = NULL;
+
+ root = g_getenv ("UMOCKDEV_DIR");
+ if (!root || *root == '\0')
+ root = "/sys";
+
+ return g_build_filename (root, CPUFREQ_POLICY_DIR, NULL);
+}
+
+static GDir *
+open_policy_dir (void)
+{
+ g_autofree char *dir = NULL;
+ dir = get_policy_dir ();
+ return g_dir_open (dir, 0, NULL);
+}
+
+static gboolean
+ppd_driver_intel_pstate_probe (PpdDriver *driver)
+{
+ PpdDriverIntelPstate *pstate = PPD_DRIVER_INTEL_PSTATE (driver);
+ g_autoptr(GDir) dir = NULL;
+ g_autofree char *policy_dir = NULL;
+ const char *dirname;
+ gboolean ret = FALSE;
+
+ dir = open_policy_dir ();
+ if (!dir)
+ goto out;
+
+ policy_dir = get_policy_dir ();
+ while ((dirname = g_dir_read_name (dir)) != NULL) {
+ g_autofree char *path = NULL;
+
+ path = g_build_filename (policy_dir,
+ dirname,
+ "energy_performance_preference",
+ NULL);
+ if (!g_file_test (path, G_FILE_TEST_EXISTS))
+ continue;
+
+ pstate->devices = g_list_prepend (pstate->devices, g_steal_pointer (&path));
+ ret = TRUE;
+ }
+
+ if (!ret)
+ goto out;
+
+ pstate->client = up_client_new ();
+ if (pstate->client) {
+ g_signal_connect (G_OBJECT (pstate->client), "notify::on-battery",
+ G_CALLBACK (on_battery_changed), pstate);
+ pstate->on_battery = up_client_get_on_battery (pstate->client);
+ }
+
+ /* Monitor the first "no_turbo" */
+ pstate->no_turbo_path = get_no_turbo_path ();
+ pstate->no_turbo_mon = monitor_no_turbo_prop (pstate->no_turbo_path);
+ if (pstate->no_turbo_mon) {
+ g_signal_connect (G_OBJECT (pstate->no_turbo_mon), "changed",
+ G_CALLBACK (no_turbo_changed), pstate);
+ }
+ update_no_turbo (pstate);
+
+out:
+ g_debug ("%s p-state settings",
+ ret ? "Found" : "Didn't find");
+ return ret;
+}
+
+static const char *
+profile_to_pref (PpdProfile profile,
+ gboolean on_battery)
+{
+ /* Note that we don't check "energy_performance_available_preferences"
+ * as all the values are always available */
+ switch (profile) {
+ case PPD_PROFILE_POWER_SAVER:
+ return "power";
+ case PPD_PROFILE_BALANCED:
+ if (on_battery)
+ return "balance_power";
+ return "balance_performance";
+ case PPD_PROFILE_PERFORMANCE:
+ return "performance";
+ }
+
+ g_assert_not_reached ();
+}
+
+static gboolean
+ppd_driver_intel_pstate_activate_profile (PpdDriver *driver,
+ PpdProfile profile,
+ GError **error)
+{
+ PpdDriverIntelPstate *pstate = PPD_DRIVER_INTEL_PSTATE (driver);
+ gboolean ret = TRUE;
+ const char *pref;
+ GList *l;
+
+ g_return_val_if_fail (pstate->devices != NULL, FALSE);
+
+ pref = profile_to_pref (profile, pstate->on_battery);
+
+ for (l = pstate->devices; l != NULL; l = l->next) {
+ const char *path = l->data;
+
+ ret = ppd_utils_write (path, pref, error);
+ if (!ret)
+ break;
+ }
+
+ if (ret)
+ pstate->activated_profile = profile;
+
+ return ret;
+}
+
+static void
+ppd_driver_intel_pstate_finalize (GObject *object)
+{
+ PpdDriverIntelPstate *driver;
+
+ driver = PPD_DRIVER_INTEL_PSTATE (object);
+ g_clear_list (&driver->devices, g_free);
+ g_clear_object (&driver->client);
+ g_clear_pointer (&driver->no_turbo_path, g_free);
+ g_clear_object (&driver->no_turbo_mon);
+ G_OBJECT_CLASS (ppd_driver_intel_pstate_parent_class)->finalize (object);
+}
+
+static void
+ppd_driver_intel_pstate_class_init (PpdDriverIntelPstateClass *klass)
+{
+ GObjectClass *object_class;
+ PpdDriverClass *driver_class;
+
+ object_class = G_OBJECT_CLASS(klass);
+ object_class->constructor = ppd_driver_intel_pstate_constructor;
+ object_class->finalize = ppd_driver_intel_pstate_finalize;
+
+ driver_class = PPD_DRIVER_CLASS(klass);
+ driver_class->probe = ppd_driver_intel_pstate_probe;
+ driver_class->activate_profile = ppd_driver_intel_pstate_activate_profile;
+}
+
+static void
+ppd_driver_intel_pstate_init (PpdDriverIntelPstate *self)
+{
+}
diff --git a/src/ppd-driver-intel-pstate.h b/src/ppd-driver-intel-pstate.h
new file mode 100644
index 0000000..42f8cf2
--- /dev/null
+++ b/src/ppd-driver-intel-pstate.h
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#pragma once
+
+#include "ppd-driver.h"
+
+#define PPD_TYPE_DRIVER_INTEL_PSTATE (ppd_driver_intel_pstate_get_type())
+G_DECLARE_FINAL_TYPE(PpdDriverIntelPstate, ppd_driver_intel_pstate, PPD, DRIVER_INTEL_PSTATE, PpdDriver)
diff --git a/src/ppd-driver-lenovo-dytc.c b/src/ppd-driver-lenovo-dytc.c
new file mode 100644
index 0000000..422349b
--- /dev/null
+++ b/src/ppd-driver-lenovo-dytc.c
@@ -0,0 +1,211 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#include <gudev/gudev.h>
+#include <gio/gio.h>
+
+#include "ppd-driver-lenovo-dytc.h"
+#include "ppd-utils.h"
+
+#define LAPMODE_SYSFS_NAME "dytc_lapmode"
+#define PERFMODE_SYSFS_NAME "dytc_perfmode"
+
+struct _PpdDriverLenovoDytc
+{
+ PpdDriver parent_instance;
+
+ GUdevClient *client;
+ GUdevDevice *device;
+ gboolean lapmode;
+};
+
+G_DEFINE_TYPE (PpdDriverLenovoDytc, ppd_driver_lenovo_dytc, PPD_TYPE_DRIVER)
+
+static GObject*
+ppd_driver_lenovo_dytc_constructor (GType type,
+ guint n_construct_params,
+ GObjectConstructParam *construct_params)
+{
+ GObject *object;
+
+ object = G_OBJECT_CLASS (ppd_driver_lenovo_dytc_parent_class)->constructor (type,
+ n_construct_params,
+ construct_params);
+ g_object_set (object,
+ "driver-name", "lenovo_dytc",
+ "profiles", PPD_PROFILE_PERFORMANCE | PPD_PROFILE_BALANCED | PPD_PROFILE_POWER_SAVER,
+ NULL);
+
+ return object;
+}
+
+static gboolean
+sysfs_attr_as_boolean (GUdevDevice *device,
+ const char *attribute)
+{
+ g_autofree char *contents = NULL;
+ g_autofree char *filename = NULL;
+
+ filename = g_build_filename (g_udev_device_get_sysfs_path (device), attribute, NULL);
+ if (!g_file_get_contents (filename, &contents, NULL, NULL))
+ return FALSE;
+
+ g_strdelimit (contents, "\n", '\0');
+ return (g_strcmp0 (contents, "1") == 0);
+}
+
+static const char *
+profile_to_perfmode_value (PpdProfile profile)
+{
+ switch (profile) {
+ case PPD_PROFILE_POWER_SAVER:
+ return "L";
+ case PPD_PROFILE_BALANCED:
+ return "M";
+ case PPD_PROFILE_PERFORMANCE:
+ return "H";
+ }
+
+ g_assert_not_reached ();
+}
+
+static void
+update_dytc_state (PpdDriverLenovoDytc *dytc)
+{
+ gboolean new_lapmode;
+
+ new_lapmode = sysfs_attr_as_boolean (dytc->device, LAPMODE_SYSFS_NAME);
+ if (new_lapmode != dytc->lapmode) {
+ dytc->lapmode = new_lapmode;
+ g_debug ("dytc_lapmode is now %s, so profile is %s",
+ dytc->lapmode ? "on" : "off",
+ dytc->lapmode ? "inhibited" : "uninhibited");
+ g_object_set (G_OBJECT (dytc),
+ "performance-inhibited", dytc->lapmode ? "lap-detected" : NULL,
+ NULL);
+ }
+}
+
+static void
+uevent_cb (GUdevClient *client,
+ gchar *action,
+ GUdevDevice *device,
+ gpointer user_data)
+{
+ PpdDriverLenovoDytc *dytc = user_data;
+
+ if (g_strcmp0 (action, "change") != 0)
+ return;
+
+ if (g_strcmp0 (g_udev_device_get_sysfs_path (device),
+ g_udev_device_get_sysfs_path (dytc->device)) != 0)
+ return;
+
+ update_dytc_state (dytc);
+}
+
+static gboolean
+ppd_driver_lenovo_dytc_activate_profile (PpdDriver *driver,
+ PpdProfile profile,
+ GError **error)
+{
+ PpdDriverLenovoDytc *dytc = PPD_DRIVER_LENOVO_DYTC (driver);
+
+ g_return_val_if_fail (dytc->client, FALSE);
+
+ if (profile == PPD_PROFILE_PERFORMANCE &&
+ dytc->lapmode) {
+ g_debug ("Can't switch to performance mode, lapmode is detected");
+ g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, "Mode is inhibited");
+ return FALSE;
+ }
+
+ if (!ppd_utils_write_sysfs (dytc->device, PERFMODE_SYSFS_NAME, profile_to_perfmode_value (profile), error)) {
+ g_debug ("Failed to write to perfmode: %s", (* error)->message);
+ return FALSE;
+ }
+
+ g_debug ("Successfully switched to profile %s", ppd_profile_to_str (profile));
+ return TRUE;
+}
+
+static gboolean
+ppd_driver_lenovo_dytc_probe (PpdDriver *driver)
+{
+ const gchar * const subsystem[] = { "platform", NULL };
+ GList *devices, *l;
+ gboolean ret = FALSE;
+ PpdDriverLenovoDytc *dytc = PPD_DRIVER_LENOVO_DYTC (driver);
+
+ g_return_val_if_fail (!dytc->client, FALSE);
+
+ dytc->client = g_udev_client_new (subsystem);
+ devices = g_udev_client_query_by_subsystem (dytc->client, "platform");
+ if (devices == NULL)
+ goto out;
+
+ for (l = devices; l != NULL; l = l->next) {
+ GUdevDevice *dev = l->data;
+
+ if (g_strcmp0 (g_udev_device_get_name (dev), "thinkpad_acpi") != 0)
+ continue;
+
+ if (!g_udev_device_get_sysfs_attr (dev, LAPMODE_SYSFS_NAME) ||
+ !g_udev_device_get_sysfs_attr (dev, PERFMODE_SYSFS_NAME))
+ break;
+
+ dytc->device = g_object_ref (dev);
+ ret = TRUE;
+ break;
+ }
+
+ if (ret) {
+ g_signal_connect (G_OBJECT (dytc->client), "uevent",
+ G_CALLBACK (uevent_cb), dytc);
+ update_dytc_state (dytc);
+ }
+
+out:
+ g_list_free_full (devices, g_object_unref);
+
+ g_debug ("%s a dytc_lapmode sysfs attribute to thinkpad_acpi",
+ ret ? "Found" : "Didn't find");
+ return ret;
+}
+
+static void
+ppd_driver_lenovo_dytc_finalize (GObject *object)
+{
+ PpdDriverLenovoDytc *driver;
+
+ driver = PPD_DRIVER_LENOVO_DYTC (object);
+ g_clear_object (&driver->device);
+ g_clear_object (&driver->client);
+ G_OBJECT_CLASS (ppd_driver_lenovo_dytc_parent_class)->finalize (object);
+}
+
+static void
+ppd_driver_lenovo_dytc_class_init (PpdDriverLenovoDytcClass *klass)
+{
+ GObjectClass *object_class;
+ PpdDriverClass *driver_class;
+
+ object_class = G_OBJECT_CLASS(klass);
+ object_class->constructor = ppd_driver_lenovo_dytc_constructor;
+ object_class->finalize = ppd_driver_lenovo_dytc_finalize;
+
+ driver_class = PPD_DRIVER_CLASS(klass);
+ driver_class->probe = ppd_driver_lenovo_dytc_probe;
+ driver_class->activate_profile = ppd_driver_lenovo_dytc_activate_profile;
+}
+
+static void
+ppd_driver_lenovo_dytc_init (PpdDriverLenovoDytc *self)
+{
+}
diff --git a/src/ppd-driver-lenovo-dytc.h b/src/ppd-driver-lenovo-dytc.h
new file mode 100644
index 0000000..64157cb
--- /dev/null
+++ b/src/ppd-driver-lenovo-dytc.h
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#pragma once
+
+#include "ppd-driver.h"
+
+#define PPD_TYPE_DRIVER_LENOVO_DYTC (ppd_driver_lenovo_dytc_get_type())
+G_DECLARE_FINAL_TYPE(PpdDriverLenovoDytc, ppd_driver_lenovo_dytc, PPD, DRIVER_LENOVO_DYTC, PpdDriver)
diff --git a/src/ppd-driver-power-saver.c b/src/ppd-driver-power-saver.c
new file mode 100644
index 0000000..d0ab9df
--- /dev/null
+++ b/src/ppd-driver-power-saver.c
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#include "ppd-driver-power-saver.h"
+
+struct _PpdDriverPowerSaver
+{
+ PpdDriver parent_instance;
+};
+
+G_DEFINE_TYPE (PpdDriverPowerSaver, ppd_driver_power_saver, PPD_TYPE_DRIVER)
+
+static GObject*
+ppd_driver_power_saver_constructor (GType type,
+ guint n_construct_params,
+ GObjectConstructParam *construct_params)
+{
+ GObject *object;
+
+ object = G_OBJECT_CLASS (ppd_driver_power_saver_parent_class)->constructor (type,
+ n_construct_params,
+ construct_params);
+ g_object_set (object,
+ "driver-name", "power-saver",
+ "profiles", PPD_PROFILE_POWER_SAVER,
+ NULL);
+
+ return object;
+}
+
+static void
+ppd_driver_power_saver_class_init (PpdDriverPowerSaverClass *klass)
+{
+ GObjectClass *object_class;
+
+ object_class = G_OBJECT_CLASS(klass);
+ object_class->constructor = ppd_driver_power_saver_constructor;
+}
+
+static void
+ppd_driver_power_saver_init (PpdDriverPowerSaver *self)
+{
+}
diff --git a/src/ppd-driver-power-saver.h b/src/ppd-driver-power-saver.h
new file mode 100644
index 0000000..7b1ee49
--- /dev/null
+++ b/src/ppd-driver-power-saver.h
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#pragma once
+
+#include "ppd-driver.h"
+
+#define PPD_TYPE_DRIVER_POWER_SAVER (ppd_driver_power_saver_get_type())
+G_DECLARE_FINAL_TYPE(PpdDriverPowerSaver, ppd_driver_power_saver, PPD, DRIVER_POWER_SAVER, PpdDriver)
diff --git a/src/ppd-driver.c b/src/ppd-driver.c
new file mode 100644
index 0000000..0bfc2bf
--- /dev/null
+++ b/src/ppd-driver.c
@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#include "ppd-driver.h"
+#include "ppd-enums.h"
+
+/**
+ * SECTION:ppd-driver
+ * @Short_description: Profile Drivers
+ * @Title: Profile Drivers
+ *
+ * Profile drivers are the implementation of the different profiles for
+ * the whole system. A driver will implement support for one or more
+ * profiles, usually one or both of the `performance` and `power-saver`
+ * profiles, for a particular system. Only one driver will be selected and
+ * running per profile.
+ *
+ * If no system-specific driver is available, some placeholder `balanced`
+ * and `power-saver` drivers will be put in place, and the `performance`
+ * profile will be unavailable.
+ *
+ * Common implementation of drivers might be:
+ * - a driver handling all three profiles, relying on a firmware feature
+ * exposed in the kernel,
+ * - a driver that only implements the `performance` profile on a particular
+ * system it has intimate knowledge of, leaving the `balanced` and
+ * `power-saver` profiles using placeholder
+ *
+ * When a driver implements the `performance` profile, it might set the
+ * #PpdDriver:performance-inhibited property if the profile isn't available for any
+ * reason, such as thermal limits being reached, or because a part of the
+ * user's body is too close for safety, for example.
+ */
+
+typedef struct
+{
+ char *driver_name;
+ PpdProfile profiles;
+ gboolean selected;
+ char *performance_inhibited;
+} PpdDriverPrivate;
+
+enum {
+ PROP_0,
+ PROP_DRIVER_NAME,
+ PROP_PROFILES,
+ PROP_PERFORMANCE_INHIBITED
+};
+
+#define PPD_DRIVER_GET_PRIVATE(o) (ppd_driver_get_instance_private (o))
+G_DEFINE_TYPE_WITH_PRIVATE (PpdDriver, ppd_driver, G_TYPE_OBJECT)
+
+static void
+ppd_driver_set_property (GObject *object,
+ guint property_id,
+ const GValue *value,
+ GParamSpec *pspec)
+{
+ PpdDriver *driver = PPD_DRIVER (object);
+ PpdDriverPrivate *priv = PPD_DRIVER_GET_PRIVATE (driver);
+
+ switch (property_id) {
+ case PROP_DRIVER_NAME:
+ g_assert (priv->driver_name == NULL);
+ priv->driver_name = g_value_dup_string (value);
+ break;
+ case PROP_PROFILES:
+ priv->profiles = g_value_get_flags (value);
+ break;
+ case PROP_PERFORMANCE_INHIBITED:
+ g_clear_pointer (&priv->performance_inhibited, g_free);
+ priv->performance_inhibited = g_value_dup_string (value);
+ break;
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec);
+ }
+}
+
+static void
+ppd_driver_get_property (GObject *object,
+ guint property_id,
+ GValue *value,
+ GParamSpec *pspec)
+{
+ PpdDriver *driver = PPD_DRIVER (object);
+ PpdDriverPrivate *priv = PPD_DRIVER_GET_PRIVATE (driver);
+
+ switch (property_id) {
+ case PROP_DRIVER_NAME:
+ g_value_set_string (value, priv->driver_name);
+ break;
+ case PROP_PROFILES:
+ g_value_set_flags (value, priv->profiles);
+ break;
+ case PROP_PERFORMANCE_INHIBITED:
+ g_value_set_string (value, priv->performance_inhibited);
+ break;
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec);
+ }
+}
+
+static void
+ppd_driver_finalize (GObject *object)
+{
+ PpdDriverPrivate *priv;
+
+ priv = PPD_DRIVER_GET_PRIVATE (PPD_DRIVER (object));
+ g_clear_pointer (&priv->driver_name, g_free);
+ g_clear_pointer (&priv->performance_inhibited, g_free);
+
+ G_OBJECT_CLASS (ppd_driver_parent_class)->finalize (object);
+}
+
+static void
+ppd_driver_class_init (PpdDriverClass *klass)
+{
+ GObjectClass *object_class;
+
+ object_class = G_OBJECT_CLASS(klass);
+ object_class->finalize = ppd_driver_finalize;
+ object_class->get_property = ppd_driver_get_property;
+ object_class->set_property = ppd_driver_set_property;
+
+ /**
+ * PpdDriver::driver-name:
+ *
+ * A unique driver name, only used for debugging.
+ */
+ g_object_class_install_property (object_class, PROP_DRIVER_NAME,
+ g_param_spec_string("driver-name",
+ "Driver name",
+ "Profile driver name",
+ NULL,
+ G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
+
+ /**
+ * PpdDriver::profiles:
+ *
+ * The bitmask of #PpdProfile<!-- -->s implemented by this driver.
+ */
+ g_object_class_install_property (object_class, PROP_PROFILES,
+ g_param_spec_flags("profiles",
+ "Profiles",
+ "Profiles implemented by this driver",
+ PPD_TYPE_PROFILE,
+ 0,
+ G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
+
+ /**
+ * PpdDriver:performance-inhibited:
+ *
+ * If set to a non-%NULL value, the reason why the performance profile is unavailable.
+ * The value must be one of the options listed in the D-Bus API reference.
+ */
+ g_object_class_install_property (object_class, PROP_PERFORMANCE_INHIBITED,
+ g_param_spec_string("performance-inhibited",
+ "Performance Inhibited",
+ "Why the performance profile is inhibited, if set",
+ NULL,
+ G_PARAM_READWRITE));
+}
+
+static void
+ppd_driver_init (PpdDriver *self)
+{
+}
+
+gboolean
+ppd_driver_probe (PpdDriver *driver)
+{
+ g_return_val_if_fail (PPD_IS_DRIVER (driver), FALSE);
+
+ if (!PPD_DRIVER_GET_CLASS (driver)->probe)
+ return TRUE;
+
+ return PPD_DRIVER_GET_CLASS (driver)->probe (driver);
+}
+
+gboolean
+ppd_driver_activate_profile (PpdDriver *driver,
+ PpdProfile profile,
+ GError **error)
+{
+ g_return_val_if_fail (PPD_IS_DRIVER (driver), FALSE);
+ g_return_val_if_fail (ppd_profile_has_single_flag (profile), FALSE);
+
+ if (!PPD_DRIVER_GET_CLASS (driver)->activate_profile)
+ return TRUE;
+
+ return PPD_DRIVER_GET_CLASS (driver)->activate_profile (driver, profile, error);
+}
+
+const char *
+ppd_driver_get_driver_name (PpdDriver *driver)
+{
+ PpdDriverPrivate *priv;
+
+ g_return_val_if_fail (PPD_IS_DRIVER (driver), NULL);
+
+ priv = PPD_DRIVER_GET_PRIVATE (driver);
+ return priv->driver_name;
+}
+
+PpdProfile
+ppd_driver_get_profiles (PpdDriver *driver)
+{
+ PpdDriverPrivate *priv;
+
+ g_return_val_if_fail (PPD_IS_DRIVER (driver), PPD_PROFILE_BALANCED);
+
+ priv = PPD_DRIVER_GET_PRIVATE (driver);
+ return priv->profiles;
+}
+
+gboolean
+ppd_driver_get_selected (PpdDriver *driver)
+{
+ PpdDriverPrivate *priv;
+
+ g_return_val_if_fail (PPD_IS_DRIVER (driver), FALSE);
+
+ priv = PPD_DRIVER_GET_PRIVATE (driver);
+ return priv->selected;
+}
+
+const char *
+ppd_driver_get_performance_inhibited (PpdDriver *driver)
+{
+ PpdDriverPrivate *priv;
+
+ g_return_val_if_fail (PPD_IS_DRIVER (driver), NULL);
+
+ priv = PPD_DRIVER_GET_PRIVATE (driver);
+ return priv->performance_inhibited ? priv->performance_inhibited : "";
+}
+
+gboolean
+ppd_driver_is_performance_inhibited (PpdDriver *driver)
+{
+ PpdDriverPrivate *priv;
+
+ g_return_val_if_fail (PPD_IS_DRIVER (driver), FALSE);
+
+ priv = PPD_DRIVER_GET_PRIVATE (driver);
+
+ return (priv->performance_inhibited != NULL);
+}
diff --git a/src/ppd-driver.h b/src/ppd-driver.h
new file mode 100644
index 0000000..b405fe4
--- /dev/null
+++ b/src/ppd-driver.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#pragma once
+
+#include <glib-object.h>
+#include "ppd-profile.h"
+
+#define PPD_TYPE_DRIVER (ppd_driver_get_type())
+G_DECLARE_DERIVABLE_TYPE(PpdDriver, ppd_driver, PPD, DRIVER, GObject)
+
+/**
+ * PpdDriverClass:
+ * @parent_class: The parent class.
+ * @probe: Called by the daemon on startup.
+ * @activate_profile: Called by the daemon for every profile change.
+ *
+ * New profile drivers should derive from #PpdDriver and implement
+ * at least one of probe() and @activate_profile.
+ */
+struct _PpdDriverClass
+{
+ GObjectClass parent_class;
+
+ gboolean (* probe) (PpdDriver *driver);
+ gboolean (* activate_profile) (PpdDriver *driver,
+ PpdProfile profile,
+ GError **error);
+};
+
+#ifndef __GTK_DOC_IGNORE__
+gboolean ppd_driver_probe (PpdDriver *driver);
+gboolean ppd_driver_activate_profile (PpdDriver *driver, PpdProfile profile, GError **error);
+const char *ppd_driver_get_driver_name (PpdDriver *driver);
+PpdProfile ppd_driver_get_profiles (PpdDriver *driver);
+const char *ppd_driver_get_performance_inhibited (PpdDriver *driver);
+gboolean ppd_driver_is_performance_inhibited (PpdDriver *driver);
+#endif
diff --git a/src/ppd-enums.c.in b/src/ppd-enums.c.in
new file mode 100644
index 0000000..b0bf330
--- /dev/null
+++ b/src/ppd-enums.c.in
@@ -0,0 +1,40 @@
+/*** BEGIN file-header ***/
+#include "ppd-enums.h"
+#include <glib-object.h>
+
+/*** END file-header ***/
+
+/*** BEGIN file-production ***/
+/* enumerations from "@basename@" */
+#include "@basename@"
+
+/*** END file-production ***/
+
+/*** BEGIN value-header ***/
+GType
+ at enum_name@_get_type (void)
+{
+ static GType the_type = 0;
+
+ if (the_type == 0)
+ {
+ static const G at Type@Value values[] = {
+/*** END value-header ***/
+
+/*** BEGIN value-production ***/
+ { @VALUENAME@,
+ "@VALUENAME@",
+ "@valuenick@" },
+/*** END value-production ***/
+
+/*** BEGIN value-tail ***/
+ { 0, NULL, NULL }
+ };
+ the_type = g_ at type@_register_static (
+ g_intern_static_string ("@EnumName@"),
+ values);
+ }
+ return the_type;
+}
+
+/*** END value-tail ***/
diff --git a/src/ppd-enums.h.in b/src/ppd-enums.h.in
new file mode 100644
index 0000000..825a6a2
--- /dev/null
+++ b/src/ppd-enums.h.in
@@ -0,0 +1,24 @@
+/*** BEGIN file-header ***/
+#pragma once
+
+#include <glib-object.h>
+
+G_BEGIN_DECLS
+
+/*** END file-header ***/
+
+/*** BEGIN file-production ***/
+/* Enumerations from "@basename@" */
+
+/*** END file-production ***/
+
+/*** BEGIN enumeration-production ***/
+#define PPD_TYPE_ at ENUMSHORT@ (@enum_name at _get_type())
+GType @enum_name at _get_type (void) G_GNUC_CONST;
+
+/*** END enumeration-production ***/
+
+/*** BEGIN file-tail ***/
+G_END_DECLS
+
+/*** END file-tail ***/
diff --git a/src/ppd-profile.c b/src/ppd-profile.c
new file mode 100644
index 0000000..3dce687
--- /dev/null
+++ b/src/ppd-profile.c
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#include "ppd-profile.h"
+#include "ppd-enums.h"
+
+const char *
+ppd_profile_to_str (PpdProfile profile)
+{
+ GFlagsClass *klass = g_type_class_ref (PPD_TYPE_PROFILE);
+ GFlagsValue *value = g_flags_get_first_value (klass, profile);
+ const gchar *name = value ? value->value_nick : "";
+ g_type_class_unref (klass);
+ return name;
+}
+
+PpdProfile
+ppd_profile_from_str (const char *str)
+{
+ GFlagsClass *klass = g_type_class_ref (PPD_TYPE_PROFILE);
+ GFlagsValue *value = g_flags_get_value_by_nick (klass, str);
+ PpdProfile profile = value ? value->value : PPD_PROFILE_UNSET;
+ g_type_class_unref (klass);
+ return profile;
+}
+
+gboolean
+ppd_profile_has_single_flag (PpdProfile profile)
+{
+ GFlagsClass *klass = g_type_class_ref (PPD_TYPE_PROFILE);
+ GFlagsValue *value = g_flags_get_first_value (klass, profile);
+ gboolean ret = FALSE;
+ if (value && value->value == profile)
+ ret = TRUE;
+ g_type_class_unref (klass);
+ return ret;
+}
diff --git a/src/ppd-profile.h b/src/ppd-profile.h
new file mode 100644
index 0000000..03c04eb
--- /dev/null
+++ b/src/ppd-profile.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#pragma once
+
+#include <glib.h>
+
+/**
+ * PpdProfile:
+ * @PPD_PROFILE_POWER_SAVER: "power-saver", the battery saving profile
+ * @PPD_PROFILE_BALANCED: balanced, the default profile
+ * @PPD_PROFILE_PERFORMANCE: as fast as possible, a profile that does
+ * not care about noise or battery consumption, only available
+ * on some systems.
+ *
+ * The different profiles available for users to select.
+ */
+typedef enum {
+ PPD_PROFILE_POWER_SAVER = 1 << 0,
+ PPD_PROFILE_BALANCED = 1 << 1,
+ PPD_PROFILE_PERFORMANCE = 1 << 2
+} PpdProfile;
+
+#define PPD_PROFILE_ALL (PPD_PROFILE_BALANCED | PPD_PROFILE_POWER_SAVER | PPD_PROFILE_PERFORMANCE)
+#define PPD_PROFILE_UNSET (0)
+
+const char *ppd_profile_to_str (PpdProfile profile);
+PpdProfile ppd_profile_from_str (const char *str);
+gboolean ppd_profile_has_single_flag (PpdProfile profile);
diff --git a/src/ppd-utils.c b/src/ppd-utils.c
new file mode 100644
index 0000000..d80e7cf
--- /dev/null
+++ b/src/ppd-utils.c
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#include "ppd-utils.h"
+#include <gio/gio.h>
+#include <stdio.h>
+#include <errno.h>
+
+gboolean ppd_utils_write (const char *filename,
+ const char *value,
+ GError **error)
+{
+ FILE *sysfsfp;
+ int ret;
+
+ g_return_val_if_fail (filename, FALSE);
+ g_return_val_if_fail (value, FALSE);
+
+ sysfsfp = fopen (filename, "w");
+ if (sysfsfp == NULL) {
+ g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
+ "Could not open '%s' for writing", filename);
+ g_debug ("Could not open for writing '%s'", filename);
+ return FALSE;
+ }
+ ret = fprintf (sysfsfp, "%s", value);
+ if (ret < 0) {
+ g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
+ "Error writing '%s'", filename);
+ g_debug ("Error writing '%s'", filename);
+ return FALSE;
+ }
+ fclose (sysfsfp);
+ return TRUE;
+}
+
+gboolean ppd_utils_write_sysfs (GUdevDevice *device,
+ const char *attribute,
+ const char *value,
+ GError **error)
+{
+ g_autofree char *filename = NULL;
+
+ g_return_val_if_fail (G_UDEV_IS_DEVICE (device), FALSE);
+ g_return_val_if_fail (attribute, FALSE);
+ g_return_val_if_fail (value, FALSE);
+
+ filename = g_build_filename (g_udev_device_get_sysfs_path (device), attribute, NULL);
+ return ppd_utils_write (filename, value, error);
+}
diff --git a/src/ppd-utils.h b/src/ppd-utils.h
new file mode 100644
index 0000000..bee7f5a
--- /dev/null
+++ b/src/ppd-utils.h
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2020 Bastien Nocera <hadess at hadess.net>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 3 as published by
+ * the Free Software Foundation.
+ *
+ */
+
+#pragma once
+
+#include <gudev/gudev.h>
+
+gboolean ppd_utils_write (const char *filename,
+ const char *value,
+ GError **error);
+gboolean ppd_utils_write_sysfs (GUdevDevice *device,
+ const char *attribute,
+ const char *value,
+ GError **error);
diff --git a/tests/integration-test b/tests/integration-test
new file mode 100755
index 0000000..54eec01
--- /dev/null
+++ b/tests/integration-test
@@ -0,0 +1,506 @@
+#!/usr/bin/python3
+
+# power-profiles-daemon integration test suite
+#
+# Run in built tree to test local built binaries, or from anywhere else to test
+# system installed binaries.
+#
+# Copyright: (C) 2011 Martin Pitt <martin.pitt at ubuntu.com>
+# (C) 2020 Bastien Nocera <hadess at hadess.net>
+#
+# 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.
+
+import os
+import sys
+import dbus
+import tempfile
+import subprocess
+import unittest
+import time
+
+try:
+ import gi
+ from gi.repository import GLib
+ from gi.repository import Gio
+except ImportError as e:
+ sys.stderr.write('Skipping tests, PyGobject not available for Python 3, or missing GI typelibs: %s\n' % str(e))
+ sys.exit(0)
+
+try:
+ gi.require_version('UMockdev', '1.0')
+ from gi.repository import UMockdev
+except ImportError:
+ sys.stderr.write('Skipping tests, umockdev not available (https://github.com/martinpitt/umockdev)\n')
+ sys.exit(0)
+
+try:
+ import dbusmock
+except ImportError:
+ sys.stderr.write('Skipping tests, python-dbusmock not available (http://pypi.python.org/pypi/python-dbusmock).\n')
+ sys.exit(0)
+
+
+PP = 'net.hadess.PowerProfiles'
+PP_PATH = '/net/hadess/PowerProfiles'
+
+class Tests(dbusmock.DBusTestCase):
+ @classmethod
+ def setUpClass(cls):
+ # run from local build tree if we are in one, otherwise use system instance
+ builddir = os.getenv('top_builddir', '.')
+ if os.access(os.path.join(builddir, 'src', 'power-profiles-daemon'), os.X_OK):
+ cls.daemon_path = os.path.join(builddir, 'src', 'power-profiles-daemon')
+ print('Testing binaries from local build tree (%s)' % cls.daemon_path)
+ cls.local_daemon = True
+ elif os.environ.get('UNDER_JHBUILD', False):
+ jhbuild_prefix = os.environ['JHBUILD_PREFIX']
+ cls.daemon_path = os.path.join(jhbuild_prefix, 'libexec', 'power-profiles-daemon')
+ print('Testing binaries from JHBuild (%s)' % cls.daemon_path)
+ cls.local_daemon = False
+ else:
+ cls.daemon_path = None
+ with open('/usr/lib/systemd/system/power-profiles-daemon.service') as f:
+ for line in f:
+ if line.startswith('ExecStart='):
+ cls.daemon_path = line.split('=', 1)[1].strip()
+ break
+ assert cls.daemon_path, 'could not determine daemon path from systemd .service file'
+ cls.local_daemon = False
+ print('Testing installed system binary (%s)' % cls.daemon_path)
+
+ # fail on CRITICALs on client side
+ GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_WARNING |
+ GLib.LogLevelFlags.LEVEL_ERROR |
+ GLib.LogLevelFlags.LEVEL_CRITICAL)
+
+ # set up a fake system D-BUS
+ cls.test_bus = Gio.TestDBus.new(Gio.TestDBusFlags.NONE)
+ cls.test_bus.up()
+ try:
+ del os.environ['DBUS_SESSION_BUS_ADDRESS']
+ except KeyError:
+ pass
+ os.environ['DBUS_SYSTEM_BUS_ADDRESS'] = cls.test_bus.get_bus_address()
+
+ cls.dbus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
+ cls.dbus_con = cls.get_dbus(True)
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.test_bus.down()
+ dbusmock.DBusTestCase.tearDownClass()
+
+ def setUp(self):
+ '''Set up a local umockdev testbed.
+
+ The testbed is initially empty.
+ '''
+ self.testbed = UMockdev.Testbed.new()
+
+ self.proxy = None
+ self.log = None
+ self.daemon = None
+
+ def tearDown(self):
+ del self.testbed
+ self.stop_daemon()
+
+ # on failures, print daemon log
+ errors = [x[1] for x in self._outcome.errors if x[1]]
+ if errors and self.log:
+ with open(self.log.name) as f:
+ sys.stderr.write('\n-------------- daemon log: ----------------\n')
+ sys.stderr.write(f.read())
+ sys.stderr.write('------------------------------\n')
+
+ #
+ # Daemon control and D-BUS I/O
+ #
+
+ def start_daemon(self):
+ '''Start daemon and create DBus proxy.
+
+ When done, this sets self.proxy as the Gio.DBusProxy for power-profiles-daemon.
+ '''
+ env = os.environ.copy()
+ env['G_DEBUG'] = 'fatal-criticals'
+ env['G_MESSAGES_DEBUG'] = 'all'
+ # note: Python doesn't propagate the setenv from Testbed.new(), so we
+ # have to do that ourselves
+ env['UMOCKDEV_DIR'] = self.testbed.get_root_dir()
+ self.log = tempfile.NamedTemporaryFile()
+ if os.getenv('VALGRIND') != None:
+ if self.local_daemon:
+ daemon_path = ['libtool', '--mode=execute', 'valgrind', self.daemon_path, '-v']
+ else:
+ daemon_path = ['valgrind', self.daemon_path, '-v']
+ else:
+ daemon_path = [self.daemon_path, '-v']
+
+ self.daemon = subprocess.Popen(daemon_path,
+ env=env, stdout=self.log,
+ stderr=subprocess.STDOUT)
+
+ # wait until the daemon gets online
+ timeout = 100
+ while timeout > 0:
+ time.sleep(0.1)
+ timeout -= 1
+ try:
+ self.get_dbus_property('ActiveProfile')
+ break
+ except GLib.GError:
+ pass
+ else:
+ self.fail('daemon did not start in 10 seconds')
+
+ self.proxy = Gio.DBusProxy.new_sync(
+ self.dbus, Gio.DBusProxyFlags.DO_NOT_AUTO_START, None, PP,
+ PP_PATH, PP, None)
+
+ self.assertEqual(self.daemon.poll(), None, 'daemon crashed')
+
+ def stop_daemon(self):
+ '''Stop the daemon if it is running.'''
+
+ if self.daemon:
+ try:
+ self.daemon.kill()
+ except OSError:
+ pass
+ self.daemon.wait()
+ self.daemon = None
+ self.proxy = None
+
+ def get_dbus_property(self, name):
+ '''Get property value from daemon D-Bus interface.'''
+
+ proxy = Gio.DBusProxy.new_sync(
+ self.dbus, Gio.DBusProxyFlags.DO_NOT_AUTO_START, None, PP,
+ PP_PATH, 'org.freedesktop.DBus.Properties', None)
+ return proxy.Get('(ss)', PP, name)
+
+ def set_dbus_property(self, name, value):
+ '''Set property value on daemon D-Bus interface.'''
+
+ proxy = Gio.DBusProxy.new_sync(
+ self.dbus, Gio.DBusProxyFlags.DO_NOT_AUTO_START, None, PP,
+ PP_PATH, 'org.freedesktop.DBus.Properties', None)
+ return proxy.Set('(ssv)', PP, name, value)
+
+ def have_text_in_log(self, text):
+ return self.count_text_in_log(text) > 0
+
+ def count_text_in_log(self, text):
+ with open(self.log.name) as f:
+ return f.read().count(text)
+
+ def read_sysfs_attr(self, device, attribute):
+ with open(os.path.join(self.testbed.get_root_dir() + device, attribute), 'rb') as f:
+ return f.read()
+ return None
+
+ def read_file(self, path):
+ with open(path, 'rb') as f:
+ return f.read()
+ return None
+
+ def assertEventually(self, condition, message=None, timeout=50):
+ '''Assert that condition function eventually returns True.
+
+ Timeout is in deciseconds, defaulting to 50 (5 seconds). message is
+ printed on failure.
+ '''
+ while timeout >= 0:
+ context = GLib.MainContext.default()
+ while context.iteration(False):
+ pass
+ if condition():
+ break
+ timeout -= 1
+ time.sleep(0.1)
+ else:
+ self.fail(message or 'timed out waiting for ' + str(condition))
+
+ #
+ # Actual test cases
+ #
+
+ def test_no_performance_driver(self):
+ '''no performance driver'''
+
+ self.start_daemon()
+ self.assertEqual(self.get_dbus_property('ActiveProfile'), 'balanced')
+ self.assertEqual(self.get_dbus_property('PerformanceInhibited'), '')
+
+ profiles = self.get_dbus_property('Profiles')
+ self.assertEqual(len(profiles), 2)
+ self.assertEqual(profiles[1]['Driver'], 'balanced')
+ self.assertEqual(profiles[0]['Driver'], 'power-saver')
+ self.assertEqual(profiles[1]['Profile'], 'balanced')
+ self.assertEqual(profiles[0]['Profile'], 'power-saver')
+
+ self.set_dbus_property('ActiveProfile', GLib.Variant.new_string('power-saver'))
+ self.assertEqual(self.get_dbus_property('ActiveProfile'), 'power-saver')
+
+ # process = subprocess.Popen(['gdbus', 'introspect', '--system', '--dest', 'net.hadess.PowerProfiles', '--object-path', '/net/hadess/PowerProfiles'])
+ # print (self.get_dbus_property('GPUs'))
+
+ self.stop_daemon()
+
+ def test_inhibited_transition(self):
+ '''Test that transitions work as expected when inhibited'''
+
+ tp_acpi = self.testbed.add_device('platform', 'thinkpad_acpi', None,
+ ['dytc_lapmode', '0', 'dytc_perfmode', 'H'],
+ [ 'DEVPATH', '/devices/platform/thinkpad_acpi' ]
+ )
+
+ self.start_daemon()
+
+ profiles = self.get_dbus_property('Profiles')
+ self.assertEqual(len(profiles), 3)
+ self.assertEqual(self.get_dbus_property('ActiveProfile'), 'balanced')
+
+ self.set_dbus_property('ActiveProfile', GLib.Variant.new_string('performance'))
+ self.assertEqual(self.get_dbus_property('ActiveProfile'), 'performance')
+
+ # Inhibit
+ self.testbed.set_attribute(tp_acpi, 'dytc_lapmode', '1')
+ self.testbed.uevent(tp_acpi, 'change')
+ self.assertEventually(lambda: self.have_text_in_log('dytc_lapmode is now on'))
+ self.assertEqual(self.get_dbus_property('PerformanceInhibited'), 'lap-detected')
+ self.assertEqual(self.get_dbus_property('ActiveProfile'), 'balanced')
+
+ # Switch to non-performance
+ self.set_dbus_property('ActiveProfile', GLib.Variant.new_string('power-saver'))
+ self.assertEqual(self.get_dbus_property('ActiveProfile'), 'power-saver')
+
+ def test_intel_pstate(self):
+ '''Intel P-State driver (no UPower)'''
+
+ # Create 2 CPUs with preferences
+ dir1 = os.path.join(self.testbed.get_root_dir(), "devices/system/cpu/cpufreq/policy0/")
+ os.makedirs(dir1)
+ with open(os.path.join(dir1, "energy_performance_preference") ,'w') as prefs:
+ prefs.write("performance")
+ dir2 = os.path.join(self.testbed.get_root_dir(), "devices/system/cpu/cpufreq/policy1/")
+ os.makedirs(dir2)
+ with open(os.path.join(dir2, "energy_performance_preference") ,'w') as prefs:
+ prefs.write("performance")
+
+ # Create no_turbo pref
+ pstate_dir = os.path.join(self.testbed.get_root_dir(), "devices/system/cpu/intel_pstate")
+ os.makedirs(pstate_dir)
+ with open(os.path.join(pstate_dir, "no_turbo") ,'w') as no_turbo:
+ no_turbo.write("0")
+
+ self.start_daemon()
+
+ profiles = self.get_dbus_property('Profiles')
+ self.assertEqual(len(profiles), 3)
+ self.assertEqual(profiles[0]['Driver'], 'intel_pstate')
+ self.assertEqual(profiles[0]['Profile'], 'power-saver')
+
+ contents = None
+ with open(os.path.join(dir2, "energy_performance_preference"), 'rb') as f:
+ contents = f.read()
+ self.assertEqual(contents, b'balance_performance')
+
+ # Set performance mode
+ self.set_dbus_property('ActiveProfile', GLib.Variant.new_string('performance'))
+ self.assertEqual(self.get_dbus_property('ActiveProfile'), 'performance')
+
+ contents = None
+ with open(os.path.join(dir2, "energy_performance_preference"), 'rb') as f:
+ contents = f.read()
+ self.assertEqual(contents, b'performance')
+
+ # Disable turbo
+ with open(os.path.join(pstate_dir, "no_turbo") ,'w') as no_turbo:
+ no_turbo.write("1")
+
+ self.assertEventually(lambda: self.have_text_in_log('File monitor change happened for '))
+ self.assertEqual(self.get_dbus_property('ActiveProfile'), 'balanced')
+ self.assertEqual(self.get_dbus_property('PerformanceInhibited'), 'high-operating-temperature')
+
+ self.stop_daemon()
+
+ # Verify that the Lenovo DYTC driver still gets preferred
+ tp_acpi = self.testbed.add_device('platform', 'thinkpad_acpi', None,
+ ['dytc_lapmode', '0', 'dytc_perfmode', 'H'],
+ [ 'DEVPATH', '/devices/platform/thinkpad_acpi' ]
+ )
+
+ self.start_daemon()
+
+ profiles = self.get_dbus_property('Profiles')
+ self.assertEqual(len(profiles), 3)
+ self.assertEqual(profiles[0]['Driver'], 'lenovo_dytc')
+
+ def test_intel_pstate_balance(self):
+ '''Intel P-State driver (balance)'''
+
+ # Create CPU with preference
+ dir1 = os.path.join(self.testbed.get_root_dir(), "devices/system/cpu/cpufreq/policy0/")
+ os.makedirs(dir1)
+ with open(os.path.join(dir1, "energy_performance_preference") ,'w') as prefs:
+ prefs.write("performance")
+
+ upowerd, obj_upower = self.spawn_server_template(
+ 'upower', {'DaemonVersion': '0.99', 'OnBattery': False}, stdout=subprocess.PIPE)
+
+ self.start_daemon()
+
+ profiles = self.get_dbus_property('Profiles')
+ self.assertEqual(len(profiles), 3)
+ self.assertEqual(profiles[0]['Driver'], 'intel_pstate')
+ self.assertEqual(profiles[0]['Profile'], 'power-saver')
+
+ contents = None
+ with open(os.path.join(dir1, "energy_performance_preference"), 'rb') as f:
+ contents = f.read()
+ self.assertEqual(contents, b'balance_performance')
+
+ # Unplug from the mains
+ obj_upower.Set('org.freedesktop.UPower', 'OnBattery', True)
+ obj_upower.EmitSignal('', 'Changed', '', [], dbus_interface='org.freedesktop.DBus.Mock')
+
+ contents = None
+ self.assertEventually(lambda: self.read_file(os.path.join(dir1, "energy_performance_preference")) == b'balance_power')
+
+ self.stop_daemon()
+
+ upowerd.terminate()
+ upowerd.wait()
+
+ def test_dytc_performance_driver(self):
+ '''Lenovo DYTC performance driver'''
+
+ tp_acpi = self.testbed.add_device('platform', 'thinkpad_acpi', None,
+ ['dytc_lapmode', '0', 'dytc_perfmode', 'H'],
+ [ 'DEVPATH', '/devices/platform/thinkpad_acpi' ]
+ )
+
+ self.start_daemon()
+
+ profiles = self.get_dbus_property('Profiles')
+ self.assertEqual(len(profiles), 3)
+ self.assertEqual(profiles[0]['Driver'], 'lenovo_dytc')
+ self.assertEqual(profiles[0]['Profile'], 'power-saver')
+ self.assertEqual(profiles[2]['Driver'], 'lenovo_dytc')
+ self.assertEqual(profiles[2]['Profile'], 'performance')
+ self.assertEqual(self.get_dbus_property('ActiveProfile'), 'balanced')
+
+ # Verify that perfmode got reset
+ self.assertEventually(lambda: self.read_sysfs_attr(tp_acpi, 'dytc_perfmode') == b'M')
+
+ # lapmode detected, but performance wasn't selected anyway
+ self.testbed.set_attribute(tp_acpi, 'dytc_lapmode', '1')
+ self.testbed.uevent(tp_acpi, 'change')
+ self.assertEventually(lambda: self.have_text_in_log('dytc_lapmode is now on'))
+
+ self.assertEqual(self.get_dbus_property('ActiveProfile'), 'balanced')
+ self.assertEqual(self.get_dbus_property('PerformanceInhibited'), 'lap-detected')
+
+ # Reset lapmode
+ self.testbed.set_attribute(tp_acpi, 'dytc_lapmode', '0')
+ self.testbed.uevent(tp_acpi, 'change')
+ self.assertEventually(lambda: self.have_text_in_log('dytc_lapmode is now off'))
+
+ # Set performance mode
+ self.set_dbus_property('ActiveProfile', GLib.Variant.new_string('performance'))
+ self.assertEqual(self.get_dbus_property('ActiveProfile'), 'performance')
+ self.assertEventually(lambda: self.read_sysfs_attr(tp_acpi, 'dytc_perfmode') == b'H')
+
+ # And turn on lapmode
+ self.testbed.set_attribute(tp_acpi, 'dytc_lapmode', '1')
+ self.testbed.uevent(tp_acpi, 'change')
+ self.assertEventually(lambda: self.have_text_in_log('dytc_lapmode is now on'))
+ self.assertEventually(lambda: self.read_sysfs_attr(tp_acpi, 'dytc_perfmode') == b'M')
+
+ self.assertEqual(self.get_dbus_property('ActiveProfile'), 'balanced')
+ self.assertEqual(self.get_dbus_property('PerformanceInhibited'), 'lap-detected')
+
+ # Turn off lapmode, profile stays balanced
+ self.testbed.set_attribute(tp_acpi, 'dytc_lapmode', '0')
+ self.testbed.uevent(tp_acpi, 'change')
+ self.assertEventually(lambda: self.have_text_in_log('dytc_lapmode is now off'))
+ self.assertEventually(lambda: self.read_sysfs_attr(tp_acpi, 'dytc_perfmode') == b'M')
+
+ # Switch to power-saver mode
+ self.set_dbus_property('ActiveProfile', GLib.Variant.new_string('power-saver'))
+ self.assertEqual(self.get_dbus_property('ActiveProfile'), 'power-saver')
+ self.assertEqual(self.get_dbus_property('PerformanceInhibited'), '')
+ self.assertEventually(lambda: self.read_sysfs_attr(tp_acpi, 'dytc_perfmode') == b'L')
+
+ def test_fake_driver(self):
+ '''Test that the fake driver works'''
+
+ os.environ['POWER_PROFILE_DAEMON_FAKE_DRIVER'] = '1'
+ self.start_daemon()
+ profiles = self.get_dbus_property('Profiles')
+ self.assertEqual(len(profiles), 3)
+ self.stop_daemon()
+
+ del os.environ['POWER_PROFILE_DAEMON_FAKE_DRIVER']
+ self.start_daemon()
+ profiles = self.get_dbus_property('Profiles')
+ self.assertEqual(len(profiles), 2)
+
+ def test_trickle_charge_mode(self):
+ '''Trickle power_supply charge type'''
+
+ idevice = self.testbed.add_device('usb', 'iDevice', None,
+ [],
+ [ 'ID_MODEL', 'iDevice', 'DRIVER', 'apple-mfi-fastcharge' ]
+ )
+ fastcharge = self.testbed.add_device('power_supply', 'MFi Fastcharge', idevice,
+ [ 'charge_type', 'Trickle', 'scope', 'Device' ],
+ []
+ )
+
+ self.start_daemon()
+
+ self.assertIn('trickle_charge', self.get_dbus_property('Actions'))
+
+ # Verify that charge-type got changed to Fast on startup
+ self.assertEqual(self.read_sysfs_attr(fastcharge, 'charge_type'), b'Fast')
+
+ # Verify that charge-type got changed to Trickle when power saving
+ self.set_dbus_property('ActiveProfile', GLib.Variant.new_string('power-saver'))
+ self.assertEqual(self.read_sysfs_attr(fastcharge, 'charge_type'), b'Trickle')
+
+ # FIXME no performance mode
+ # Verify that charge-type got changed to Fast in a non-default, non-power save mode
+ # self.set_dbus_property('ActiveProfile', GLib.Variant.new_string('performance'))
+ # self.assertEqual(self.read_sysfs_attr(fastcharge, 'charge_type'), 'Fast')
+
+ #
+ # Helper methods
+ #
+
+ @classmethod
+ def _props_to_str(cls, properties):
+ '''Convert a properties dictionary to uevent text representation.'''
+
+ prop_str = ''
+ if properties:
+ for k, v in properties.items():
+ prop_str += '%s=%s\n' % (k, v)
+ return prop_str
+
+if __name__ == '__main__':
+ # run ourselves under umockdev
+ if 'umockdev' not in os.environ.get('LD_PRELOAD', ''):
+ os.execvp('umockdev-wrapper', ['umockdev-wrapper'] + sys.argv)
+
+ unittest.main()
diff --git a/tests/meson.build b/tests/meson.build
new file mode 100644
index 0000000..baf4699
--- /dev/null
+++ b/tests/meson.build
@@ -0,0 +1,9 @@
+integration_test = find_program('integration-test')
+
+envs = environment()
+envs.set ('top_builddir', meson.build_root())
+
+test('power-profiles-daemon-integration-test',
+ integration_test,
+ env: envs
+ )
More information about the Neon-commits
mailing list