./ 0000755 0000041 0000041 00000000000 13151304741 011242 5 ustar www-data www-data ./CMakeLists.txt 0000644 0000041 0000041 00000005440 13151304741 014005 0 ustar www-data www-data project(indicator-power C CXX)
cmake_minimum_required(VERSION 2.8.9)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake)
set(PROJECT_VERSION "16.10.0")
set(PACKAGE ${CMAKE_PROJECT_NAME})
set(GETTEXT_PACKAGE "indicator-power")
add_definitions(
-DGETTEXT_PACKAGE="${GETTEXT_PACKAGE}"
-DG_LOG_DOMAIN="${GETTEXT_PACKAGE}"
-DGNOMELOCALEDIR="${CMAKE_INSTALL_FULL_LOCALEDIR}"
-DLOW_BATTERY_SOUND="Low battery.ogg"
)
set(SERVICE_LIB "indicatorpowerservice")
set(SERVICE_EXEC "indicator-power-service")
add_definitions(-DSERVICE_EXEC="${SERVICE_EXEC}")
##
## GNU standard installation directories
##
include (GNUInstallDirs)
if (EXISTS "/etc/debian_version") # Workaround for libexecdir on debian
set (CMAKE_INSTALL_LIBEXECDIR "${CMAKE_INSTALL_LIBDIR}")
set (CMAKE_INSTALL_FULL_LIBEXECDIR "${CMAKE_INSTALL_FULL_LIBDIR}")
endif ()
set (CMAKE_INSTALL_PKGLIBEXECDIR "${CMAKE_INSTALL_LIBEXECDIR}/${CMAKE_PROJECT_NAME}")
set (CMAKE_INSTALL_FULL_PKGLIBEXECDIR "${CMAKE_INSTALL_FULL_LIBEXECDIR}/${CMAKE_PROJECT_NAME}")
##
## Check for prerequisites
##
find_package (PkgConfig REQUIRED)
include (CheckIncludeFile)
include (FindPkgConfig)
pkg_check_modules(SERVICE_DEPS REQUIRED
glib-2.0>=2.36
gio-2.0>=2.36
gio-unix-2.0>=2.36
gudev-1.0>=204
libnotify>=0.7.6
url-dispatcher-1>=1)
include_directories (SYSTEM ${SERVICE_DEPS_INCLUDE_DIRS})
##
## custom targets
##
set (ARCHIVE_NAME ${CMAKE_PROJECT_NAME}-${PROJECT_VERSION})
add_custom_target (dist
COMMAND bzr export --root=${ARCHIVE_NAME} ${CMAKE_BINARY_DIR}/${ARCHIVE_NAME}.tar.gz
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
add_custom_target (cppcheck COMMAND cppcheck --enable=all -q --error-exitcode=2 --inline-suppr
${CMAKE_SOURCE_DIR}/src
${CMAKE_SOURCE_DIR}/tests)
##
## Actual building
##
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
set(C_WARNING_ARGS "${C_WARNING_ARGS} -Weverything")
set(C_WARNING_ARGS "${C_WARNING_ARGS} -Wno-c++98-compat -Wno-padded") # these are annoying
set(C_WARNING_ARGS "${C_WARNING_ARGS} -Wno-documentation") # gtk-doc != doxygen
else()
set(C_WARNING_ARGS "${C_WARNING_ARGS} -Wall -Wextra -Wpedantic -Wformat=2")
endif()
set(C_WARNING_ARGS "${C_WARNING_ARGS} -Wno-missing-field-initializers") # GActionEntry
include_directories (${CMAKE_CURRENT_SOURCE_DIR}/include)
include_directories (${CMAKE_CURRENT_BINARY_DIR}/include)
# actually build things
add_subdirectory(src)
add_subdirectory(data)
add_subdirectory(po)
# testing & coverage
enable_testing ()
add_subdirectory(tests)
find_package(CoverageReport)
ENABLE_COVERAGE_REPORT(
TARGETS ${SERVICE_LIB} ${SERVICE_EXEC}
TESTS ${COVERAGE_TEST_TARGETS}
FILTER /usr/include ${CMAKE_BINARY_DIR}/*
)
./NEWS 0000644 0000041 0000041 00000001232 13151304741 011737 0 ustar www-data www-data 13.10.0
- Use the new GMenu indicator scheme
12.10.5
- Fix a device display bug introduced in 12.10.3 (LP: #1075192)
12.10.4
- Fix primary device selection bug introduced in 12.10.3 (LP: #1071757)
12.10.3
- Show the proper icon for mice and ups devices. (LP: #1066208)
- Follow the spec when choosing the primary device (LP: #1071645)
- Fix minor memory leaks
12.10.2
- Show a more accurate view of discharging batteries (LP: #1054146)
- Fix a GIcon memory leak
- In device.c, include gi18n-lib.h instead of gi18n.h
12.10.1
- Update our glib version dependency (LP: #1023533)
12.10.0
- Refactored the device icon/text code for better test coverage
./COPYING 0000644 0000041 0000041 00000104513 13151304741 012301 0 ustar www-data www-data GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
./src/ 0000755 0000041 0000041 00000000000 13151304741 012031 5 ustar www-data www-data ./src/CMakeLists.txt 0000644 0000041 0000041 00000005237 13151304741 014600 0 ustar www-data www-data # handwritten sources
set(SERVICE_MANUAL_SOURCES
brightness.c
datafiles.c
device-provider-mock.c
device-provider-upower.c
device-provider.c
device.c
notifier.c
testing.c
service.c)
# generated sources
include(GdbusCodegen)
set(SERVICE_GENERATED_SOURCES)
add_gdbus_codegen_with_namespace(SERVICE_GENERATED_SOURCES dbus-powerd
com.canonical
Dbus
${CMAKE_SOURCE_DIR}/src/com.canonical.powerd.xml)
add_gdbus_codegen_with_namespace(SERVICE_GENERATED_SOURCES dbus-battery
com.canonical.indicator.power
Dbus
${CMAKE_SOURCE_DIR}/data/com.canonical.indicator.power.Battery.xml)
add_gdbus_codegen_with_namespace(SERVICE_GENERATED_SOURCES dbus-testing
com.canonical.indicator.power
Dbus
${CMAKE_SOURCE_DIR}/data/com.canonical.indicator.power.Testing.xml)
add_gdbus_codegen_with_namespace(SERVICE_GENERATED_SOURCES dbus-accounts-sound
com.ubuntu.touch
Dbus
/usr/share/accountsservice/interfaces/com.ubuntu.touch.AccountsService.Sound.xml)
# add the bin dir to our include path so the code can find the generated header files
include_directories(${CMAKE_CURRENT_BINARY_DIR})
# add warnings/coverage info on handwritten files
# but not the autogenerated ones...
set(C_WARNING_ARGS "${C_WARNING_ARGS} -Wno-bad-function-cast") # g_clear_object()
set(C_WARNING_ARGS "${C_WARNING_ARGS} -Wno-used-but-marked-unused") # G_ADD_PRIVATE
set(C_WARNING_ARGS "${C_WARNING_ARGS} -Wno-disabled-macro-expansion") # G_DEFINE_TYPE
set(C_WARNING_ARGS "${C_WARNING_ARGS} -Wno-assign-enum") # GParamFlags
set(C_WARNING_ARGS "${C_WARNING_ARGS} -Wno-switch-enum")
set_source_files_properties(${SERVICE_MANUAL_SOURCES}
PROPERTIES COMPILE_FLAGS "${C_WARNING_ARGS} -std=c99")
# the service library for tests to link against (basically, everything except main())
add_library(${SERVICE_LIB} STATIC ${SERVICE_MANUAL_SOURCES} ${SERVICE_GENERATED_SOURCES})
include_directories(${CMAKE_SOURCE_DIR})
link_directories(${SERVICE_DEPS_LIBRARY_DIRS})
# the executable: lib + main()
add_executable (${SERVICE_EXEC} main.c)
set_source_files_properties(${SERVICE_SOURCES} main.c PROPERTIES COMPILE_FLAGS "${C_WARNING_ARGS} -std=c99")
target_link_libraries (${SERVICE_EXEC} ${SERVICE_LIB} ${SERVICE_DEPS_LIBRARIES})
install (TARGETS ${SERVICE_EXEC} RUNTIME DESTINATION ${CMAKE_INSTALL_FULL_PKGLIBEXECDIR})
./src/service.c 0000644 0000041 0000041 00000120616 13151304741 013643 0 ustar www-data www-data /*
* Copyright 2013-2016 Canonical Ltd.
*
* 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 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 .
*
* Authors:
* Charles Kerr
* Ted Gould
*/
#include
#include
#include
#include "brightness.h"
#include "dbus-shared.h"
#include "device.h"
#include "device-provider.h"
#include "notifier.h"
#include "service.h"
#define BUS_NAME "com.canonical.indicator.power"
#define BUS_PATH "/com/canonical/indicator/power"
#define SETTINGS_SHOW_TIME_S "show-time"
#define SETTINGS_ICON_POLICY_S "icon-policy"
#define SETTINGS_SHOW_PERCENTAGE_S "show-percentage"
G_DEFINE_TYPE (IndicatorPowerService,
indicator_power_service,
G_TYPE_OBJECT)
enum
{
SIGNAL_NAME_LOST,
LAST_SIGNAL
};
static guint signals[LAST_SIGNAL] = { 0 };
enum
{
PROP_0,
PROP_BUS,
PROP_DEVICE_PROVIDER,
PROP_NOTIFIER,
LAST_PROP
};
static GParamSpec * properties[LAST_PROP];
enum
{
SECTION_HEADER = (1<<0),
SECTION_DEVICES = (1<<1),
SECTION_SETTINGS = (1<<2),
};
enum
{
PROFILE_PHONE,
PROFILE_DESKTOP,
PROFILE_DESKTOP_GREETER,
N_PROFILES
};
static const char * const menu_names[N_PROFILES] =
{
"phone",
"desktop",
"desktop_greeter"
};
enum
{
POWER_INDICATOR_ICON_POLICY_PRESENT,
POWER_INDICATOR_ICON_POLICY_CHARGE,
POWER_INDICATOR_ICON_POLICY_NEVER
};
struct ProfileMenuInfo
{
/* the root level -- the header is the only child of this */
GMenu * menu;
/* parent of the sections. This is the header's submenu */
GMenu * submenu;
guint export_id;
};
struct _IndicatorPowerServicePrivate
{
GCancellable * cancellable;
GSettings * settings;
IndicatorPowerBrightness * brightness;
guint own_id;
guint actions_export_id;
GDBusConnection * conn;
gboolean menus_built;
struct ProfileMenuInfo menus[N_PROFILES];
GSimpleActionGroup * actions;
GSimpleAction * header_action;
GSimpleAction * battery_level_action;
GSimpleAction * device_state_action;
GSimpleAction * brightness_action;
IndicatorPowerDevice * primary_device;
GList * devices; /* IndicatorPowerDevice */
IndicatorPowerDeviceProvider * device_provider;
IndicatorPowerNotifier * notifier;
};
typedef IndicatorPowerServicePrivate priv_t;
/***
****
**** DEVICES
****
***/
/* the higher the weight, the more interesting the device */
static int
get_device_kind_weight (const IndicatorPowerDevice * device)
{
UpDeviceKind kind;
static gboolean initialized = FALSE;
static int weights[UP_DEVICE_KIND_LAST];
kind = indicator_power_device_get_kind (device);
g_return_val_if_fail (0<=kind && kind b_time ? -1 : 1;
else
ret = a_percentage < b_percentage ? -1 : 1;
}
}
state = UP_DEVICE_STATE_DISCHARGING;
if (!ret && ((a_state == state) || (b_state == state)))
{
if (a_state != state) /* b is discharging */
{
ret = 1;
}
else if (b_state != state) /* a is discharging */
{
ret = -1;
}
else /* both are discharging; use percentage */
{
ret = a_percentage < b_percentage ? -1 : 1;
}
}
/* neither device is charging nor discharging... */
/* unless there's no other option,
don't choose a device with an unknown state.
https://bugs.launchpad.net/ubuntu/+source/indicator-power/+bug/1470080 */
state = UP_DEVICE_STATE_UNKNOWN;
if (!ret && ((a_state == state) || (b_state == state)))
{
if (a_state != state) /* b is unknown */
{
ret = -1;
}
else if (b_state != state) /* a is unknown */
{
ret = 1;
}
}
if (!ret)
{
const int weight_a = get_device_kind_weight (a);
const int weight_b = get_device_kind_weight (b);
if (weight_a > weight_b)
{
ret = -1;
}
else if (weight_a < weight_b)
{
ret = 1;
}
}
if (!ret)
ret = a_state - b_state;
return ret;
}
static const char*
device_state_to_string(UpDeviceState device_state)
{
const char * str;
switch (device_state)
{
case UP_DEVICE_STATE_CHARGING:
str = "charging";
break;
case UP_DEVICE_STATE_DISCHARGING:
str = "discharging";
break;
case UP_DEVICE_STATE_EMPTY:
str = "empty";
break;
case UP_DEVICE_STATE_FULLY_CHARGED:
str = "fully-charged";
break;
case UP_DEVICE_STATE_PENDING_CHARGE:
str = "pending-charge";
break;
case UP_DEVICE_STATE_PENDING_DISCHARGE:
str = "pending-discharge";
break;
default:
str = "unknown";
break;
}
return str;
}
static GVariant *
calculate_device_state_action_state (IndicatorPowerService * self)
{
const priv_t * const p = self->priv;
UpDeviceState device_state;
if (p->primary_device != NULL)
device_state = indicator_power_device_get_state(p->primary_device);
else
device_state = UP_DEVICE_STATE_UNKNOWN;
return g_variant_new_string(device_state_to_string(device_state));
}
static GVariant*
calculate_battery_level_action_state (IndicatorPowerService * self)
{
const priv_t * const p = self->priv;
guint32 battery_level;
if (p->primary_device == NULL)
battery_level = 0;
else
battery_level = (guint32)(indicator_power_device_get_percentage (p->primary_device) + 0.5);
return g_variant_new_uint32 (battery_level);
}
/***
****
**** HEADER SECTION
****
***/
static void
count_batteries (GList * devices, int *total, int *inuse)
{
GList * l;
for (l=devices; l!=NULL; l=l->next)
{
const IndicatorPowerDevice * device = INDICATOR_POWER_DEVICE(l->data);
if (indicator_power_device_get_kind(device) == UP_DEVICE_KIND_BATTERY ||
indicator_power_device_get_kind(device) == UP_DEVICE_KIND_UPS)
{
++*total;
const UpDeviceState state = indicator_power_device_get_state (device);
if ((state == UP_DEVICE_STATE_CHARGING) ||
(state == UP_DEVICE_STATE_DISCHARGING))
++*inuse;
}
}
g_debug ("count_batteries found %d batteries (%d are charging/discharging)",
*total, *inuse);
}
static gboolean
should_be_visible (IndicatorPowerService * self)
{
gboolean visible = TRUE;
priv_t * p = self->priv;
const int policy = g_settings_get_enum (p->settings, SETTINGS_ICON_POLICY_S);
g_debug ("policy is: %d (present==0, charge==1, never==2)", policy);
if (policy == POWER_INDICATOR_ICON_POLICY_NEVER)
{
visible = FALSE;
}
else
{
int batteries=0, inuse=0;
count_batteries (p->devices, &batteries, &inuse);
if (policy == POWER_INDICATOR_ICON_POLICY_PRESENT)
{
visible = batteries > 0;
}
else if (policy == POWER_INDICATOR_ICON_POLICY_CHARGE)
{
visible = inuse > 0;
}
}
g_debug ("should_be_visible: %s", visible?"yes":"no");
return visible;
}
static GVariant *
create_header_state (IndicatorPowerService * self)
{
GVariantBuilder b;
const priv_t * const p = self->priv;
g_variant_builder_init (&b, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add (&b, "{sv}", "title", g_variant_new_string (_("Battery")));
g_variant_builder_add (&b, "{sv}", "visible",
g_variant_new_boolean (should_be_visible (self)));
if (p->primary_device != NULL)
{
char * title;
GIcon * icon;
const gboolean want_time = g_settings_get_boolean (p->settings, SETTINGS_SHOW_TIME_S);
const gboolean want_percent = g_settings_get_boolean (p->settings, SETTINGS_SHOW_PERCENTAGE_S);
title = indicator_power_device_get_readable_title (p->primary_device,
want_time,
want_percent);
if (title)
{
if (*title)
g_variant_builder_add (&b, "{sv}", "label", g_variant_new_take_string (title));
else
g_free (title);
}
title = indicator_power_device_get_accessible_title (p->primary_device,
want_time,
want_percent);
if (title)
{
if (*title)
g_variant_builder_add (&b, "{sv}", "accessible-desc", g_variant_new_take_string (title));
else
g_free (title);
}
if ((icon = indicator_power_device_get_gicon (p->primary_device)))
{
GVariant * serialized_icon = g_icon_serialize (icon);
if (serialized_icon != NULL)
{
g_variant_builder_add (&b, "{sv}", "icon", serialized_icon);
g_variant_unref (serialized_icon);
}
g_object_unref (icon);
}
}
return g_variant_builder_end (&b);
}
/***
****
**** DEVICE SECTION
****
***/
static void
append_device_to_menu (GMenu * menu, const IndicatorPowerDevice * device, int profile)
{
const UpDeviceKind kind = indicator_power_device_get_kind (device);
if (kind != UP_DEVICE_KIND_LINE_POWER)
{
char * label;
GMenuItem * item;
GIcon * icon;
label = indicator_power_device_get_readable_text (device);
item = g_menu_item_new (label, NULL);
g_free (label);
g_menu_item_set_attribute (item, "x-canonical-type", "s", "com.canonical.indicator.basic");
if ((icon = indicator_power_device_get_gicon (device)))
{
GVariant * serialized_icon = g_icon_serialize (icon);
if (serialized_icon != NULL)
{
g_menu_item_set_attribute_value (item,
G_MENU_ATTRIBUTE_ICON,
serialized_icon);
g_variant_unref (serialized_icon);
}
g_object_unref (icon);
}
if (profile == PROFILE_DESKTOP)
{
g_menu_item_set_action_and_target(item, "indicator.activate-statistics", "s",
indicator_power_device_get_object_path (device));
}
g_menu_append_item (menu, item);
g_object_unref (item);
}
}
static GMenuModel *
create_desktop_devices_section (IndicatorPowerService * self, int profile)
{
GList * l;
GMenu * menu = g_menu_new ();
for (l=self->priv->devices; l!=NULL; l=l->next)
append_device_to_menu (menu, l->data, profile);
return G_MENU_MODEL (menu);
}
/* https://wiki.ubuntu.com/Power#Phone
* The spec also discusses including an item for any connected bluetooth
* headset, but bluez doesn't appear to support Battery Level at this time */
static GMenuModel *
create_phone_devices_section (IndicatorPowerService * self G_GNUC_UNUSED)
{
GMenu * menu;
GMenuItem *item;
menu = g_menu_new ();
item = g_menu_item_new (_("Charge level"), "indicator.battery-level");
g_menu_item_set_attribute (item, "x-canonical-type", "s", "com.canonical.indicator.progress");
g_menu_append_item (menu, item);
g_object_unref (item);
return G_MENU_MODEL (menu);
}
/***
****
**** SETTINGS SECTION
****
***/
static GMenuItem *
create_brightness_menu_item(void)
{
GIcon * icon;
GMenuItem * item;
item = g_menu_item_new(NULL, "indicator.brightness");
g_menu_item_set_attribute(item, "x-canonical-type", "s", "com.canonical.unity.slider");
g_menu_item_set_attribute(item, "min-value", "d", 0.0);
g_menu_item_set_attribute(item, "max-value", "d", 1.0);
icon = g_themed_icon_new("display-brightness-min");
g_menu_item_set_attribute_value(item, "min-icon", g_icon_serialize(icon));
g_clear_object(&icon);
icon = g_themed_icon_new("display-brightness-max");
g_menu_item_set_attribute_value(item, "max-icon", g_icon_serialize(icon));
g_clear_object(&icon);
return item;
}
static GVariant *
action_state_for_brightness (IndicatorPowerService * self)
{
IndicatorPowerBrightness * b = self->priv->brightness;
return g_variant_new_double(indicator_power_brightness_get_percentage(b));
}
static void
update_brightness_action_state (IndicatorPowerService * self)
{
g_simple_action_set_state (self->priv->brightness_action,
action_state_for_brightness (self));
}
static void
on_brightness_change_requested (GSimpleAction * action G_GNUC_UNUSED,
GVariant * parameter,
gpointer gself)
{
IndicatorPowerService * self = INDICATOR_POWER_SERVICE (gself);
indicator_power_brightness_set_percentage(self->priv->brightness,
g_variant_get_double (parameter));
}
static GMenuModel *
create_desktop_settings_section (IndicatorPowerService * self G_GNUC_UNUSED)
{
GMenu * menu = g_menu_new ();
g_menu_append (menu,
_("Show Time in Menu Bar"),
"indicator.show-time");
g_menu_append (menu,
_("Show Percentage in Menu Bar"),
"indicator.show-percentage");
g_menu_append (menu,
_("Power Settings…"),
"indicator.activate-settings");
return G_MENU_MODEL (menu);
}
static GMenuModel *
create_phone_settings_section(IndicatorPowerService * self)
{
GMenu * section;
GMenuItem * item;
gboolean ab_supported;
section = g_menu_new();
item = create_brightness_menu_item();
g_menu_append_item(section, item);
update_brightness_action_state(self);
g_object_unref(item);
g_object_get(self->priv->brightness,
"auto-brightness-supported", &ab_supported,
NULL);
if (ab_supported)
{
item = g_menu_item_new(_("Adjust brightness automatically"), "indicator.auto-brightness");
g_menu_item_set_attribute(item, "x-canonical-type", "s", "com.canonical.indicator.switch");
g_menu_append_item(section, item);
g_object_unref(item);
}
g_menu_append(section, _("Battery settings…"), "indicator.activate-phone-settings");
return G_MENU_MODEL(section);
}
/***
****
**** SECTION REBUILDING
****
***/
/**
* A small helper function for rebuild_now().
* - removes the previous section
* - adds and unrefs the new section
*/
static void
rebuild_section (GMenu * parent, int pos, GMenuModel * new_section)
{
g_menu_remove (parent, pos);
g_menu_insert_section (parent, pos, NULL, new_section);
g_object_unref (new_section);
}
static void
rebuild_now (IndicatorPowerService * self, guint sections)
{
priv_t * p = self->priv;
struct ProfileMenuInfo * phone = &p->menus[PROFILE_PHONE];
struct ProfileMenuInfo * desktop = &p->menus[PROFILE_DESKTOP];
struct ProfileMenuInfo * greeter = &p->menus[PROFILE_DESKTOP_GREETER];
if (sections & SECTION_HEADER)
{
g_simple_action_set_state (p->header_action, create_header_state (self));
}
if (!p->menus_built)
return;
if (sections & SECTION_DEVICES)
{
rebuild_section (desktop->submenu, 0, create_desktop_devices_section (self, PROFILE_DESKTOP));
rebuild_section (greeter->submenu, 0, create_desktop_devices_section (self, PROFILE_DESKTOP_GREETER));
}
if (sections & SECTION_SETTINGS)
{
rebuild_section (desktop->submenu, 1, create_desktop_settings_section (self));
rebuild_section (phone->submenu, 1, create_phone_settings_section (self));
}
}
static inline void
rebuild_header_now (IndicatorPowerService * self)
{
rebuild_now (self, SECTION_HEADER);
}
static void
create_menu (IndicatorPowerService * self, int profile)
{
GMenu * menu;
GMenu * submenu;
GMenuItem * header;
GMenuModel * sections[16];
guint i;
guint n = 0;
g_assert (0<=profile && profilepriv->menus[profile].menu == NULL);
/* build the sections */
switch (profile)
{
case PROFILE_PHONE:
sections[n++] = create_phone_devices_section (self);
sections[n++] = create_phone_settings_section (self);
break;
case PROFILE_DESKTOP:
sections[n++] = create_desktop_devices_section (self, PROFILE_DESKTOP);
sections[n++] = create_desktop_settings_section (self);
break;
case PROFILE_DESKTOP_GREETER:
sections[n++] = create_desktop_devices_section (self, PROFILE_DESKTOP_GREETER);
break;
}
/* add sections to the submenu */
submenu = g_menu_new ();
for (i=0; ipriv->menus[profile].menu = menu;
self->priv->menus[profile].submenu = submenu;
}
/***
**** GActions
***/
/* Run a particular program based on an activation */
static void
execute_command (const gchar * cmd)
{
GError * err = NULL;
g_debug ("Issuing command '%s'", cmd);
if (!g_spawn_command_line_async (cmd, &err))
{
g_warning ("Unable to start %s: %s", cmd, err->message);
g_error_free (err);
}
}
static void
on_settings_activated (GSimpleAction * a G_GNUC_UNUSED,
GVariant * param G_GNUC_UNUSED,
gpointer gself G_GNUC_UNUSED)
{
static const gchar *control_center_cmd = NULL;
if (control_center_cmd == NULL)
{
if (g_getenv ("MIR_SOCKET") != NULL)
{
url_dispatch_send("settings:///system/battery", NULL, NULL);
return;
}
else if (!g_strcmp0 (g_getenv ("DESKTOP_SESSION"), "xubuntu"))
{
control_center_cmd = "xfce4-power-manager-settings";
}
else if (!g_strcmp0 (g_getenv ("DESKTOP_SESSION"), "mate"))
{
control_center_cmd = "mate-power-preferences";
}
else if (!g_strcmp0 (g_getenv ("XDG_CURRENT_DESKTOP"), "Pantheon"))
{
control_center_cmd = "switchboard --open-plug system-pantheon-power";
}
else
{
gchar *path;
path = g_find_program_in_path ("unity-control-center");
if (path != NULL)
control_center_cmd = "unity-control-center power";
else
control_center_cmd = "gnome-control-center power";
g_free (path);
}
}
execute_command (control_center_cmd);
}
static void
on_statistics_activated (GSimpleAction * a G_GNUC_UNUSED,
GVariant * param,
gpointer gself G_GNUC_UNUSED)
{
char *cmd = g_strconcat ("gnome-power-statistics", " --device ",
g_variant_get_string (param, NULL), NULL);
execute_command (cmd);
g_free (cmd);
}
static void
on_phone_settings_activated (GSimpleAction * a G_GNUC_UNUSED,
GVariant * param G_GNUC_UNUSED,
gpointer gself G_GNUC_UNUSED)
{
url_dispatch_send("settings:///system/battery", NULL, NULL);
}
/***
****
***/
static gboolean
convert_auto_prop_to_state(GBinding * binding G_GNUC_UNUSED,
const GValue * from_value,
GValue * to_value,
gpointer user_data G_GNUC_UNUSED)
{
const gboolean b = g_value_get_boolean(from_value);
g_value_set_variant(to_value, g_variant_new_boolean(b));
return TRUE;
}
static gboolean
convert_auto_state_to_prop(GBinding * binding G_GNUC_UNUSED,
const GValue * from_value,
GValue * to_value,
gpointer user_data G_GNUC_UNUSED)
{
GVariant * v = g_value_get_variant(from_value);
g_value_set_boolean(to_value, g_variant_get_boolean(v));
return TRUE;
}
static void
init_gactions (IndicatorPowerService * self)
{
GSimpleAction * a;
GAction * show_time_action;
GAction * show_percentage_action;
priv_t * p = self->priv;
GActionEntry entries[] = {
{ "activate-settings", on_settings_activated },
{ "activate-phone-settings", on_phone_settings_activated },
{ "activate-statistics", on_statistics_activated, "s" }
};
p->actions = g_simple_action_group_new ();
g_action_map_add_action_entries (G_ACTION_MAP(p->actions),
entries,
G_N_ELEMENTS(entries),
self);
/* add the header action */
a = g_simple_action_new_stateful ("_header", NULL, create_header_state (self));
g_action_map_add_action (G_ACTION_MAP(p->actions), G_ACTION(a));
p->header_action = a;
/* add the power-level action */
a = g_simple_action_new_stateful ("battery-level", NULL, calculate_battery_level_action_state(self));
g_simple_action_set_enabled (a, FALSE);
g_action_map_add_action (G_ACTION_MAP(p->actions), G_ACTION(a));
p->battery_level_action = a;
/* add the charge state action */
a = g_simple_action_new_stateful ("device-state", NULL, calculate_device_state_action_state(self));
g_simple_action_set_enabled (a, FALSE);
g_action_map_add_action (G_ACTION_MAP(p->actions), G_ACTION(a));
p->device_state_action = a;
/* add the auto-brightness action */
a = g_simple_action_new_stateful("auto-brightness", NULL, g_variant_new_boolean(FALSE));
g_object_bind_property_full(p->brightness, "auto-brightness",
a, "state",
G_BINDING_SYNC_CREATE|G_BINDING_BIDIRECTIONAL,
convert_auto_prop_to_state,
convert_auto_state_to_prop,
NULL, NULL);
g_action_map_add_action(G_ACTION_MAP(p->actions), G_ACTION(a));
/* add the brightness action */
a = g_simple_action_new_stateful ("brightness", NULL, action_state_for_brightness (self));
g_action_map_add_action (G_ACTION_MAP(p->actions), G_ACTION(a));
g_signal_connect (a, "change-state", G_CALLBACK(on_brightness_change_requested), self);
p->brightness_action = a;
/* add the show-time action */
show_time_action = g_settings_create_action (p->settings, "show-time");
g_action_map_add_action (G_ACTION_MAP(p->actions), show_time_action);
/* add the show-percentage action */
show_percentage_action = g_settings_create_action (p->settings, "show-percentage");
g_action_map_add_action (G_ACTION_MAP(p->actions), show_percentage_action);
rebuild_header_now (self);
g_object_unref (show_time_action);
g_object_unref (show_percentage_action);
}
/***
**** GDBus Name Ownership & Menu / Action Exporting
***/
static void
on_bus_acquired (GDBusConnection * connection,
const gchar * name,
gpointer gself)
{
int i;
guint id;
GError * err = NULL;
IndicatorPowerService * self = INDICATOR_POWER_SERVICE(gself);
priv_t * p = self->priv;
GString * path = g_string_new (NULL);
g_debug ("bus acquired: %s", name);
p->conn = g_object_ref (G_OBJECT (connection));
g_object_notify_by_pspec (G_OBJECT(self), properties[PROP_BUS]);
/* export the battery properties */
if (p->notifier != NULL)
indicator_power_notifier_set_bus (p->notifier, connection);
/* export the actions */
if ((id = g_dbus_connection_export_action_group (connection,
BUS_PATH,
G_ACTION_GROUP (p->actions),
&err)))
{
p->actions_export_id = id;
}
else
{
g_warning ("cannot export action group: %s", err->message);
g_clear_error (&err);
}
/* export the menus */
for (i=0; imenus[i];
g_string_printf (path, "%s/%s", BUS_PATH, menu_names[i]);
if ((id = g_dbus_connection_export_menu_model (connection,
path->str,
G_MENU_MODEL (menu->menu),
&err)))
{
menu->export_id = id;
}
else
{
g_warning ("cannot export %s menu: %s", path->str, err->message);
g_clear_error (&err);
}
}
g_string_free (path, TRUE);
}
static void
unexport (IndicatorPowerService * self)
{
int i;
priv_t * p = self->priv;
/* unexport the menus */
for (i=0; ipriv->menus[i].export_id;
if (*id)
{
g_dbus_connection_unexport_menu_model (p->conn, *id);
*id = 0;
}
}
/* unexport the actions */
if (p->actions_export_id)
{
g_dbus_connection_unexport_action_group (p->conn, p->actions_export_id);
p->actions_export_id = 0;
}
}
static void
on_name_lost (GDBusConnection * connection G_GNUC_UNUSED,
const gchar * name,
gpointer gself)
{
IndicatorPowerService * self = INDICATOR_POWER_SERVICE (gself);
g_debug ("%s %s name lost %s", G_STRLOC, G_STRFUNC, name);
unexport (self);
g_signal_emit (self, signals[SIGNAL_NAME_LOST], 0, NULL);
}
/***
**** Events
***/
static void
on_devices_changed (IndicatorPowerService * self)
{
priv_t * p = self->priv;
/* update the device list */
g_list_free_full (p->devices, (GDestroyNotify)g_object_unref);
p->devices = indicator_power_device_provider_get_devices (p->device_provider);
/* update the primary device */
g_clear_object (&p->primary_device);
p->primary_device = indicator_power_service_choose_primary_device (p->devices);
/* update the notifier's battery */
if ((p->primary_device != NULL) && (indicator_power_device_get_kind(p->primary_device) == UP_DEVICE_KIND_BATTERY))
indicator_power_notifier_set_battery (p->notifier, p->primary_device);
else
indicator_power_notifier_set_battery (p->notifier, NULL);
/* update the battery-level action's state */
g_simple_action_set_state (p->battery_level_action, calculate_battery_level_action_state(self));
/* update the device-state action's state */
g_simple_action_set_state (p->device_state_action, calculate_device_state_action_state(self));
rebuild_now (self, SECTION_HEADER | SECTION_DEVICES);
}
static void
on_auto_brightness_supported_changed(IndicatorPowerService * self)
{
rebuild_now(self, SECTION_SETTINGS);
}
/***
**** GObject virtual functions
***/
static void
my_get_property (GObject * o,
guint property_id,
GValue * value,
GParamSpec * pspec)
{
IndicatorPowerService * self = INDICATOR_POWER_SERVICE (o);
priv_t * p = self->priv;
switch (property_id)
{
case PROP_BUS:
g_value_set_object (value, p->conn);
break;
case PROP_DEVICE_PROVIDER:
g_value_set_object (value, p->device_provider);
break;
case PROP_NOTIFIER:
g_value_set_object (value, p->notifier);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (o, property_id, pspec);
}
}
static void
my_set_property (GObject * o,
guint property_id,
const GValue * value,
GParamSpec * pspec)
{
IndicatorPowerService * self = INDICATOR_POWER_SERVICE (o);
switch (property_id)
{
case PROP_DEVICE_PROVIDER:
indicator_power_service_set_device_provider (self, g_value_get_object (value));
break;
case PROP_NOTIFIER:
indicator_power_service_set_notifier (self, g_value_get_object (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (o, property_id, pspec);
}
}
static void
my_dispose (GObject * o)
{
IndicatorPowerService * self = INDICATOR_POWER_SERVICE(o);
priv_t * p = self->priv;
if (p->own_id)
{
g_bus_unown_name (p->own_id);
p->own_id = 0;
}
unexport (self);
if (p->cancellable != NULL)
{
g_cancellable_cancel (p->cancellable);
g_clear_object (&p->cancellable);
}
if (p->settings != NULL)
{
g_signal_handlers_disconnect_by_data (p->settings, self);
g_clear_object (&p->settings);
}
g_clear_object (&p->notifier);
g_clear_object (&p->brightness_action);
g_clear_object (&p->brightness);
g_clear_object (&p->battery_level_action);
g_clear_object (&p->header_action);
g_clear_object (&p->actions);
g_clear_object (&p->conn);
indicator_power_service_set_device_provider (self, NULL);
indicator_power_service_set_notifier (self, NULL);
G_OBJECT_CLASS (indicator_power_service_parent_class)->dispose (o);
}
/***
**** Instantiation
***/
static void
indicator_power_service_init (IndicatorPowerService * self)
{
priv_t * p;
int i;
p = G_TYPE_INSTANCE_GET_PRIVATE (self,
INDICATOR_TYPE_POWER_SERVICE,
IndicatorPowerServicePrivate);
self->priv = p;
p->cancellable = g_cancellable_new ();
p->settings = g_settings_new ("com.canonical.indicator.power");
p->brightness = indicator_power_brightness_new();
g_signal_connect_swapped(p->brightness, "notify::percentage",
G_CALLBACK(update_brightness_action_state), self);
init_gactions (self);
g_signal_connect_swapped (p->settings, "changed", G_CALLBACK(rebuild_header_now), self);
for (i=0; imenus_built = TRUE;
g_signal_connect_swapped(p->brightness, "notify::auto-brightness-supported",
G_CALLBACK(on_auto_brightness_supported_changed), self);
p->own_id = g_bus_own_name(G_BUS_TYPE_SESSION,
BUS_NAME,
G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT,
on_bus_acquired,
NULL,
on_name_lost,
self,
NULL);
}
static void
indicator_power_service_class_init (IndicatorPowerServiceClass * klass)
{
GObjectClass * object_class = G_OBJECT_CLASS (klass);
object_class->dispose = my_dispose;
object_class->get_property = my_get_property;
object_class->set_property = my_set_property;
g_type_class_add_private (klass, sizeof (IndicatorPowerServicePrivate));
signals[SIGNAL_NAME_LOST] = g_signal_new (
INDICATOR_POWER_SERVICE_SIGNAL_NAME_LOST,
G_TYPE_FROM_CLASS(klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (IndicatorPowerServiceClass, name_lost),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
properties[PROP_0] = NULL;
properties[PROP_BUS] = g_param_spec_object (
"bus",
"Bus",
"GDBusConnection for exporting menus/actions",
G_TYPE_OBJECT,
G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
properties[PROP_DEVICE_PROVIDER] = g_param_spec_object (
"device-provider",
"Device Provider",
"Source for power devices",
G_TYPE_OBJECT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
properties[PROP_NOTIFIER] = g_param_spec_object (
"notifier",
"Notifier",
"Notifies user of important battery changes",
G_TYPE_OBJECT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
g_object_class_install_properties (object_class, LAST_PROP, properties);
}
/***
**** Public API
***/
IndicatorPowerService *
indicator_power_service_new (IndicatorPowerDeviceProvider * device_provider,
IndicatorPowerNotifier * notifier)
{
GObject * o = g_object_new (INDICATOR_TYPE_POWER_SERVICE,
"device-provider", device_provider,
"notifier", notifier,
NULL);
return INDICATOR_POWER_SERVICE (o);
}
void
indicator_power_service_set_device_provider (IndicatorPowerService * self,
IndicatorPowerDeviceProvider * dp)
{
priv_t * p;
g_return_if_fail (INDICATOR_IS_POWER_SERVICE (self));
g_return_if_fail (!dp || INDICATOR_IS_POWER_DEVICE_PROVIDER (dp));
p = self->priv;
if (p->device_provider != NULL)
{
g_signal_handlers_disconnect_by_data (p->device_provider, self);
g_clear_object (&p->device_provider);
g_clear_object (&p->primary_device);
g_list_free_full (p->devices, g_object_unref);
p->devices = NULL;
}
if (dp != NULL)
{
p->device_provider = g_object_ref (dp);
g_signal_connect_swapped (p->device_provider, "devices-changed",
G_CALLBACK(on_devices_changed), self);
on_devices_changed (self);
}
}
void
indicator_power_service_set_notifier (IndicatorPowerService * self,
IndicatorPowerNotifier * notifier)
{
priv_t * p;
g_return_if_fail (INDICATOR_IS_POWER_SERVICE (self));
g_return_if_fail (!notifier || INDICATOR_IS_POWER_NOTIFIER (notifier));
p = self->priv;
if (p->notifier == notifier)
return;
g_clear_object (&p->notifier);
if (notifier != NULL)
{
p->notifier = g_object_ref (notifier);
indicator_power_notifier_set_bus (p->notifier, p->conn);
}
}
/* If a device has multiple batteries and uses only one of them at a time,
they should be presented as separate items inside the battery menu,
but everywhere else they should be aggregated (bug 880881).
Their percentages should be averaged. If any are discharging,
the aggregated time remaining should be the maximum of the times
for all those that are discharging, plus the sum of the times
for all those that are idle. Otherwise, the aggregated time remaining
should be the the maximum of the times for all those that are charging. */
static IndicatorPowerDevice *
create_totalled_battery_device (const GList * devices)
{
const GList * l;
guint n_charged = 0;
guint n_charging = 0;
guint n_discharging = 0;
guint n_batteries = 0;
double sum_percent = 0;
time_t max_discharge_time = 0;
time_t max_charge_time = 0;
time_t sum_charged_time = 0;
IndicatorPowerDevice * device = NULL;
for (l=devices; l!=NULL; l=l->next)
{
const IndicatorPowerDevice * walk = INDICATOR_POWER_DEVICE(l->data);
if (indicator_power_device_get_kind(walk) == UP_DEVICE_KIND_BATTERY)
{
const double percent = indicator_power_device_get_percentage (walk);
const time_t t = indicator_power_device_get_time (walk);
const UpDeviceState state = indicator_power_device_get_state (walk);
++n_batteries;
if (percent > 0.01)
sum_percent += percent;
if (state == UP_DEVICE_STATE_CHARGING)
{
++n_charging;
max_charge_time = MAX(max_charge_time, t);
}
else if (state == UP_DEVICE_STATE_DISCHARGING)
{
++n_discharging;
max_discharge_time = MAX(max_discharge_time, t);
}
else if (state == UP_DEVICE_STATE_FULLY_CHARGED)
{
++n_charged;
sum_charged_time += t;
}
}
}
if (n_batteries > 1)
{
const double percent = sum_percent / n_batteries;
UpDeviceState state;
time_t time_left;
if (n_discharging > 0)
{
state = UP_DEVICE_STATE_DISCHARGING;
time_left = max_discharge_time + sum_charged_time;
}
else if (n_charging > 0)
{
state = UP_DEVICE_STATE_CHARGING;
time_left = max_charge_time;
}
else if (n_charged > 0)
{
state = UP_DEVICE_STATE_FULLY_CHARGED;
time_left = 0;
}
else
{
state = UP_DEVICE_STATE_UNKNOWN;
time_left = 0;
}
device = indicator_power_device_new (NULL,
UP_DEVICE_KIND_BATTERY,
percent,
state,
time_left,
TRUE);
}
return device;
}
/**
* If there are multiple UP_DEVICE_KIND_BATTERY devices in the list,
* they're merged into a new 'totalled' device representing the sum of them.
*
* Returns: (element-type IndicatorPowerDevice)(transfer full): a list of devices
*/
static GList*
merge_batteries_together (GList * devices)
{
GList * ret;
IndicatorPowerDevice * merged_device;
if ((merged_device = create_totalled_battery_device (devices)))
{
GList * l;
ret = g_list_append (NULL, merged_device);
for (l=devices; l!=NULL; l=l->next)
if (indicator_power_device_get_kind(INDICATOR_POWER_DEVICE(l->data)) != UP_DEVICE_KIND_BATTERY)
ret = g_list_append (ret, g_object_ref(l->data));
}
else /* not enough batteries to merge */
{
ret = g_list_copy (devices);
g_list_foreach (ret, (GFunc)g_object_ref, NULL);
}
return ret;
}
IndicatorPowerDevice *
indicator_power_service_choose_primary_device (GList * devices)
{
IndicatorPowerDevice * primary = NULL;
if (devices != NULL)
{
GList * tmp = merge_batteries_together (devices);
tmp = g_list_sort (tmp, device_compare_func);
primary = g_object_ref (tmp->data);
g_list_free_full (tmp, (GDestroyNotify)g_object_unref);
}
return primary;
}
./src/datafiles.c 0000644 0000041 0000041 00000003767 13151304741 014146 0 ustar www-data www-data /*
* Copyright 2016 Canonical Ltd.
*
* 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 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 .
*
* Authors:
* Charles Kerr
*/
#include "datafiles.h"
static const gchar*
get_directory_prefix_for_type (DatafileType type)
{
switch (type)
{
case DATAFILE_TYPE_SOUND:
return "sounds";
default:
g_critical("unknown type");
return "";
}
}
static gchar*
test_directory_for_file(const char* dir, DatafileType type, const char* basename)
{
gchar* filename = g_build_filename(dir,
GETTEXT_PACKAGE,
get_directory_prefix_for_type(type),
basename,
NULL);
g_debug("looking for \"%s\" at \"%s\"", basename, filename);
if (g_file_test(filename, G_FILE_TEST_EXISTS))
return filename;
g_free(filename);
return NULL;
}
gchar*
datafile_find(DatafileType type, const char * basename)
{
gchar * filename;
const gchar * user_data_dir;
const gchar * const * system_data_dirs;
gsize i;
user_data_dir = g_get_user_data_dir();
if ((filename = test_directory_for_file(user_data_dir, type, basename)))
return filename;
system_data_dirs = g_get_system_data_dirs();
for (i=0; system_data_dirs && system_data_dirs[i]; ++i)
if ((filename = test_directory_for_file(system_data_dirs[i], type, basename)))
return filename;
return NULL;
}
./src/brightness.c 0000644 0000041 0000041 00000036072 13151304741 014355 0 ustar www-data www-data /*
* Copyright 2014 Canonical Ltd.
*
* 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 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 .
*
* Authors:
* Charles Kerr
*/
#include "brightness.h"
#include "dbus-powerd.h"
#include
#define SCHEMA_NAME "com.ubuntu.touch.system"
#define KEY_AUTO "auto-brightness"
#define KEY_AUTO_SUPPORTED "auto-brightness-supported"
#define KEY_BRIGHTNESS "brightness"
#define KEY_NEED_DEFAULT "brightness-needs-hardware-default"
enum
{
PROP_0,
PROP_PERCENTAGE,
PROP_AUTO,
PROP_AUTO_SUPPORTED,
LAST_PROP
};
static GParamSpec* properties[LAST_PROP];
typedef struct
{
GDBusConnection * system_bus;
GCancellable * cancellable;
GSettings * settings;
DbusPowerd * powerd_proxy;
char * powerd_name_owner;
double percentage;
/* powerd brightness params */
gint powerd_dim;
gint powerd_min;
gint powerd_max;
gint powerd_default_value;
gboolean powerd_ab_supported;
gboolean have_powerd_params;
}
IndicatorPowerBrightnessPrivate;
typedef IndicatorPowerBrightnessPrivate priv_t;
G_DEFINE_TYPE_WITH_PRIVATE(IndicatorPowerBrightness,
indicator_power_brightness,
G_TYPE_OBJECT)
#define get_priv(o) ((priv_t*)indicator_power_brightness_get_instance_private(o))
/***
**** GObject virtual functions
***/
static void
my_get_property(GObject * o,
guint property_id,
GValue * value,
GParamSpec * pspec)
{
IndicatorPowerBrightness * self = INDICATOR_POWER_BRIGHTNESS(o);
priv_t * p = get_priv(self);
switch (property_id)
{
case PROP_PERCENTAGE:
g_value_set_double(value, indicator_power_brightness_get_percentage(self));
break;
case PROP_AUTO:
g_value_set_boolean(value, p->settings ? g_settings_get_boolean(p->settings, KEY_AUTO) : FALSE);
break;
case PROP_AUTO_SUPPORTED:
g_value_set_boolean(value, p->powerd_ab_supported);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(o, property_id, pspec);
}
}
static void
my_set_property(GObject * o,
guint property_id,
const GValue * value,
GParamSpec * pspec)
{
IndicatorPowerBrightness * self = INDICATOR_POWER_BRIGHTNESS(o);
priv_t * p = get_priv(self);
switch (property_id)
{
case PROP_PERCENTAGE:
indicator_power_brightness_set_percentage(self, g_value_get_double(value));
break;
case PROP_AUTO:
if (p->settings != NULL)
g_settings_set_boolean (p->settings, KEY_AUTO, g_value_get_boolean(value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(o, property_id, pspec);
}
}
static void
my_dispose(GObject * o)
{
IndicatorPowerBrightness * self = INDICATOR_POWER_BRIGHTNESS(o);
priv_t * p = get_priv(self);
if (p->cancellable != NULL)
{
g_cancellable_cancel(p->cancellable);
g_clear_object(&p->cancellable);
}
if (p->powerd_proxy != NULL)
{
g_signal_handlers_disconnect_by_data(p->powerd_proxy, o);
g_clear_object(&p->powerd_proxy);
}
g_clear_object(&p->settings);
g_clear_object(&p->system_bus);
g_clear_pointer(&p->powerd_name_owner, g_free);
G_OBJECT_CLASS(indicator_power_brightness_parent_class)->dispose(o);
}
/***
**** Percentage <-> Brightness Int conversion helpers
***/
static gdouble
brightness_to_percentage(IndicatorPowerBrightness * self, int brightness)
{
const priv_t * p;
gdouble percentage;
p = get_priv(self);
if (p->have_powerd_params)
{
const int lo = p->powerd_min;
const int hi = p->powerd_max;
percentage = (brightness-lo) / (double)(hi-lo);
}
else
{
percentage = 0;
}
return percentage;
}
static int
percentage_to_brightness(IndicatorPowerBrightness * self, double percentage)
{
const priv_t * p;
int brightness;
p = get_priv(self);
if (p->have_powerd_params)
{
const int lo = p->powerd_min;
const int hi = p->powerd_max;
brightness = (int)(lo + (percentage*(hi-lo)));
}
else
{
brightness = 0;
}
return brightness;
}
/**
* DBus Chatter: com.canonical.powerd
*
* This is used to get default value, and upper and lower bounds,
* of the brightness setting
*/
static void set_brightness_global(IndicatorPowerBrightness*, int);
static void set_brightness_local(IndicatorPowerBrightness*, int);
static void
on_powerd_brightness_params_ready(GObject * oproxy,
GAsyncResult * res,
gpointer gself)
{
GError * error;
GVariant * v;
v = NULL;
error = NULL;
if (dbus_powerd_call_get_brightness_params_finish(DBUS_POWERD(oproxy), &v, res, &error))
{
IndicatorPowerBrightness * self = INDICATOR_POWER_BRIGHTNESS(gself);
priv_t * p = get_priv(self);
const gboolean old_ab_supported = p->powerd_ab_supported;
p->have_powerd_params = TRUE;
g_variant_get(v, "(iiiib)", &p->powerd_dim,
&p->powerd_min,
&p->powerd_max,
&p->powerd_default_value,
&p->powerd_ab_supported);
g_debug("powerd brightness settings: dim=%d, min=%d, max=%d, default=%d, ab_supported=%d",
p->powerd_dim,
p->powerd_min,
p->powerd_max,
p->powerd_default_value,
(int)p->powerd_ab_supported);
if (old_ab_supported != p->powerd_ab_supported)
g_object_notify_by_pspec(G_OBJECT(self), properties[PROP_AUTO_SUPPORTED]);
if (p->settings != NULL)
{
if (g_settings_get_boolean(p->settings, KEY_NEED_DEFAULT))
{
/* user's first session, so init the schema's default
brightness from powerd's hardware-specific params */
g_debug("%s is true, so initializing brightness to powerd default '%d'", KEY_NEED_DEFAULT, p->powerd_default_value);
set_brightness_global(self, p->powerd_default_value);
g_settings_set_boolean(p->settings, KEY_NEED_DEFAULT, FALSE);
}
else
{
/* not the first time, so restore the previous session's brightness */
set_brightness_global(self, g_settings_get_int(p->settings, KEY_BRIGHTNESS));
}
}
/* cleanup */
g_variant_unref(v);
}
else if (error != NULL)
{
if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
g_warning("Unable to get system bus: %s", error->message);
g_error_free(error);
}
}
static void
on_powerd_name_owner_changed(GDBusProxy * powerd_proxy,
GParamSpec * pspec G_GNUC_UNUSED,
gpointer gself)
{
priv_t * p = get_priv(INDICATOR_POWER_BRIGHTNESS(gself));
gchar * owner = g_dbus_proxy_get_name_owner(powerd_proxy);
if (g_strcmp0(p->powerd_name_owner, owner))
{
p->have_powerd_params = FALSE;
if (owner != NULL)
{
dbus_powerd_call_get_brightness_params(DBUS_POWERD(powerd_proxy),
p->cancellable,
on_powerd_brightness_params_ready,
gself);
}
g_free(p->powerd_name_owner);
p->powerd_name_owner = owner;
}
}
static void
on_powerd_brightness_changed(DbusPowerd * powerd_proxy,
GParamSpec * pspec G_GNUC_UNUSED,
gpointer gself)
{
set_brightness_local(gself, dbus_powerd_get_brightness(powerd_proxy));
}
static void
on_powerd_proxy_ready(GObject * source_object G_GNUC_UNUSED,
GAsyncResult * res,
gpointer gself)
{
GError * error;
DbusPowerd * powerd_proxy;
error = NULL;
powerd_proxy = dbus_powerd_proxy_new_for_bus_finish(res, &error);
if (powerd_proxy != NULL)
{
priv_t * p;
p = get_priv(INDICATOR_POWER_BRIGHTNESS(gself));
/* keep a handle to the system bus */
g_clear_object(&p->system_bus);
p->system_bus = g_object_ref(g_dbus_proxy_get_connection(G_DBUS_PROXY(powerd_proxy)));
/* keep the proxy and listen to owner changes */
p->powerd_proxy = powerd_proxy;
g_signal_connect(p->powerd_proxy, "notify::g-name-owner",
G_CALLBACK(on_powerd_name_owner_changed), gself);
g_signal_connect(p->powerd_proxy, "notify::brightness",
G_CALLBACK(on_powerd_brightness_changed), gself);
on_powerd_name_owner_changed(G_DBUS_PROXY(powerd_proxy), NULL, gself);
}
else if (error != NULL)
{
if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
g_warning("Unable to get powerd proxy: %s", error->message);
g_error_free(error);
}
}
/**
* DBus Chatter: com.canonical.Unity.Screen
*
* Used to set the backlight brightness via setUserBrightness
*/
/* setUserBrightness doesn't return anything,
so this function is just to check for bus error messages */
static void
on_set_uscreen_user_brightness_result(GObject * system_bus,
GAsyncResult * res,
gpointer gself G_GNUC_UNUSED)
{
GError * error;
GVariant * v;
error = NULL;
v = g_dbus_connection_call_finish(G_DBUS_CONNECTION(system_bus), res, &error);
if (error != NULL)
{
if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
g_warning("Unable to call uscreen.setBrightness: %s", error->message);
g_error_free(error);
}
g_clear_pointer(&v, g_variant_unref);
}
static void
set_uscreen_user_brightness(IndicatorPowerBrightness * self,
int value)
{
priv_t * p = get_priv(self);
g_dbus_connection_call(p->system_bus,
"com.canonical.Unity.Screen",
"/com/canonical/Unity/Screen",
"com.canonical.Unity.Screen",
"setUserBrightness",
g_variant_new("(i)", value),
NULL, /* no return args */
G_DBUS_CALL_FLAGS_NONE,
-1, /* default timeout */
p->cancellable,
on_set_uscreen_user_brightness_result,
self);
}
/***
****
***/
static void
set_brightness_local(IndicatorPowerBrightness * self, int brightness)
{
priv_t * p = get_priv(self);
p->percentage = brightness_to_percentage(self, brightness);
g_object_notify_by_pspec(G_OBJECT(self), properties[PROP_PERCENTAGE]);
}
static void
on_brightness_changed_in_schema(GSettings * settings,
gchar * key,
gpointer gself)
{
set_brightness_local(INDICATOR_POWER_BRIGHTNESS(gself),
g_settings_get_int(settings, key));
}
static void
set_brightness_global(IndicatorPowerBrightness * self, int brightness)
{
priv_t * p = get_priv(self);
set_uscreen_user_brightness(self, brightness);
if (p->settings != NULL)
g_settings_set_int(p->settings, KEY_BRIGHTNESS, brightness);
else
set_brightness_local(self, brightness);
}
static void
on_auto_changed_in_schema(IndicatorPowerBrightness * self)
{
g_object_notify_by_pspec(G_OBJECT(self), properties[PROP_AUTO]);
}
/***
**** Instantiation
***/
static void
indicator_power_brightness_init(IndicatorPowerBrightness * self)
{
priv_t * p;
GSettingsSchema * schema;
p = get_priv(self);
p->cancellable = g_cancellable_new();
schema = g_settings_schema_source_lookup(g_settings_schema_source_get_default(),
SCHEMA_NAME,
TRUE);
/* "brightness" is only spec'ed for the phone profile,
so fail gracefully & silently if we don't have the
schema for it. */
if (schema != NULL)
{
if (g_settings_schema_has_key(schema, KEY_BRIGHTNESS))
{
p->settings = g_settings_new(SCHEMA_NAME);
g_signal_connect(p->settings, "changed::" KEY_BRIGHTNESS,
G_CALLBACK(on_brightness_changed_in_schema), self);
g_signal_connect_swapped(p->settings, "changed::" KEY_AUTO,
G_CALLBACK(on_auto_changed_in_schema), self);
}
g_settings_schema_unref(schema);
}
dbus_powerd_proxy_new_for_bus (G_BUS_TYPE_SYSTEM,
G_DBUS_PROXY_FLAGS_GET_INVALIDATED_PROPERTIES,
"com.canonical.powerd",
"/com/canonical/powerd",
p->cancellable,
on_powerd_proxy_ready,
self);
}
static void
indicator_power_brightness_class_init(IndicatorPowerBrightnessClass * klass)
{
GObjectClass * object_class = G_OBJECT_CLASS(klass);
object_class->dispose = my_dispose;
object_class->get_property = my_get_property;
object_class->set_property = my_set_property;
properties[PROP_0] = NULL;
properties[PROP_PERCENTAGE] = g_param_spec_double(
"percentage",
"Percentage",
"Brightness percentage",
0.0, /* minimum */
1.0, /* maximum */
0.8,
G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS);
properties[PROP_AUTO] = g_param_spec_boolean(
"auto-brightness",
"Auto-Brightness",
"Automatically adjust brightness level",
FALSE,
G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS);
properties[PROP_AUTO_SUPPORTED] = g_param_spec_boolean(
"auto-brightness-supported",
"Auto-Brightness Supported",
"True if the device can automatically adjust brightness",
FALSE,
G_PARAM_READABLE|G_PARAM_STATIC_STRINGS);
g_object_class_install_properties(object_class, LAST_PROP, properties);
}
/***
**** Public API
***/
IndicatorPowerBrightness *
indicator_power_brightness_new(void)
{
gpointer o = g_object_new(INDICATOR_TYPE_POWER_BRIGHTNESS, NULL);
return INDICATOR_POWER_BRIGHTNESS(o);
}
void
indicator_power_brightness_set_percentage(IndicatorPowerBrightness * self,
double percentage)
{
g_return_if_fail(INDICATOR_IS_POWER_BRIGHTNESS(self));
set_brightness_global(self, percentage_to_brightness(self, percentage));
}
double
indicator_power_brightness_get_percentage(IndicatorPowerBrightness * self)
{
g_return_val_if_fail(INDICATOR_IS_POWER_BRIGHTNESS(self), 0.0);
return get_priv(self)->percentage;
}
./src/device-provider-mock.c 0000644 0000041 0000041 00000005663 13151304741 016225 0 ustar www-data www-data /*
* Copyright 2014 Canonical Ltd.
*
* 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 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 .
*
* Authors:
* Charles Kerr
*/
#include "device.h"
#include "device-provider.h"
#include "device-provider-mock.h"
/***
**** GObject boilerplate
***/
static void indicator_power_device_provider_interface_init (
IndicatorPowerDeviceProviderInterface * iface);
G_DEFINE_TYPE_WITH_CODE (
IndicatorPowerDeviceProviderMock,
indicator_power_device_provider_mock,
G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE (INDICATOR_TYPE_POWER_DEVICE_PROVIDER,
indicator_power_device_provider_interface_init))
/***
**** IndicatorPowerDeviceProvider virtual functions
***/
static GList *
my_get_devices (IndicatorPowerDeviceProvider * provider)
{
IndicatorPowerDeviceProviderMock * self = INDICATOR_POWER_DEVICE_PROVIDER_MOCK(provider);
return g_list_copy_deep (self->devices, (GCopyFunc)g_object_ref, NULL);
}
/***
**** GObject virtual functions
***/
static void
my_dispose (GObject * o)
{
IndicatorPowerDeviceProviderMock * self = INDICATOR_POWER_DEVICE_PROVIDER_MOCK(o);
g_list_free_full (self->devices, g_object_unref);
G_OBJECT_CLASS (indicator_power_device_provider_mock_parent_class)->dispose (o);
}
/***
**** Instantiation
***/
static void
indicator_power_device_provider_mock_class_init (IndicatorPowerDeviceProviderMockClass * klass)
{
GObjectClass * object_class;
object_class = G_OBJECT_CLASS (klass);
object_class->dispose = my_dispose;
}
static void
indicator_power_device_provider_interface_init (IndicatorPowerDeviceProviderInterface * iface)
{
iface->get_devices = my_get_devices;
}
static void
indicator_power_device_provider_mock_init (IndicatorPowerDeviceProviderMock * self G_GNUC_UNUSED)
{
}
/***
**** Public API
***/
IndicatorPowerDeviceProvider *
indicator_power_device_provider_mock_new (void)
{
gpointer o = g_object_new (INDICATOR_TYPE_POWER_DEVICE_PROVIDER_MOCK, NULL);
return INDICATOR_POWER_DEVICE_PROVIDER (o);
}
void
indicator_power_device_provider_add_device (IndicatorPowerDeviceProviderMock * provider,
IndicatorPowerDevice * device)
{
provider->devices = g_list_append (provider->devices, g_object_ref(device));
g_signal_connect_swapped (device, "notify", G_CALLBACK(indicator_power_device_provider_emit_devices_changed), provider);
}
./src/com.canonical.powerd.xml 0000644 0000041 0000041 00000004421 13151304741 016557 0 ustar www-data www-data
./src/dbus-shared.h 0000644 0000041 0000041 00000001631 13151304741 014404 0 ustar www-data www-data /*
* Copyright 2014 Canonical Ltd.
*
* 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 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 .
*
* Authors:
* Charles Kerr
* Ted Gould
*/
#ifndef DBUS_SHARED_H
#define DBUS_SHARED_H
#define BUS_NAME "com.canonical.indicator.power"
#define BUS_PATH "/com/canonical/indicator/power"
#endif /* DBUS_SHARED_H */
./src/device.c 0000644 0000041 0000041 00000100163 13151304741 013435 0 ustar www-data www-data /*
A simple Device structure used internally by indicator-power
Copyright 2012 Canonical Ltd.
Authors:
Charles Kerr
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 3.0 as published by the Free Software Foundation.
This library 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 version 3.0 for more details.
You should have received a copy of the GNU General Public
License along with this library. If not, see
.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include
#include
#include "device.h"
struct _IndicatorPowerDevicePrivate
{
UpDeviceKind kind;
UpDeviceState state;
gchar * object_path;
gdouble percentage;
time_t time;
/* Timestamp of when when we first noticed that upower couldn't estimate
the time-remaining field for this device, or 0 if not applicable.
This is used when generating the time-remaining string. */
GTimer * inestimable;
gboolean power_supply;
};
/* Properties */
/* Enum for the properties so that they can be quickly found and looked up. */
enum {
PROP_0,
PROP_KIND,
PROP_STATE,
PROP_OBJECT_PATH,
PROP_PERCENTAGE,
PROP_TIME,
PROP_POWER_SUPPLY,
N_PROPERTIES
};
static GParamSpec * properties[N_PROPERTIES];
/* GObject stuff */
static void indicator_power_device_class_init (IndicatorPowerDeviceClass *klass);
static void indicator_power_device_init (IndicatorPowerDevice *self);
static void indicator_power_device_dispose (GObject *object);
static void indicator_power_device_finalize (GObject *object);
static void set_property (GObject*, guint prop_id, const GValue*, GParamSpec* );
static void get_property (GObject*, guint prop_id, GValue*, GParamSpec* );
/* LCOV_EXCL_START */
G_DEFINE_TYPE (IndicatorPowerDevice, indicator_power_device, G_TYPE_OBJECT)
/* LCOV_EXCL_STOP */
static void
indicator_power_device_class_init (IndicatorPowerDeviceClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
g_type_class_add_private (klass, sizeof (IndicatorPowerDevicePrivate));
object_class->dispose = indicator_power_device_dispose;
object_class->finalize = indicator_power_device_finalize;
object_class->set_property = set_property;
object_class->get_property = get_property;
properties[PROP_KIND] = g_param_spec_int (INDICATOR_POWER_DEVICE_KIND,
"kind",
"The device's UpDeviceKind",
UP_DEVICE_KIND_UNKNOWN, UP_DEVICE_KIND_LAST,
UP_DEVICE_KIND_UNKNOWN,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
properties[PROP_STATE] = g_param_spec_int (INDICATOR_POWER_DEVICE_STATE,
"state",
"The device's UpDeviceState",
UP_DEVICE_STATE_UNKNOWN, UP_DEVICE_STATE_LAST,
UP_DEVICE_STATE_UNKNOWN,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
properties[PROP_OBJECT_PATH] = g_param_spec_string (INDICATOR_POWER_DEVICE_OBJECT_PATH,
"object path",
"The device's DBus object path",
NULL,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
properties[PROP_PERCENTAGE] = g_param_spec_double (INDICATOR_POWER_DEVICE_PERCENTAGE,
"percentage",
"percent charged",
0.0, 100.0,
0.0,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
properties[PROP_TIME] = g_param_spec_uint64 (INDICATOR_POWER_DEVICE_TIME,
"time",
"time left",
0, G_MAXUINT64,
0,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
properties[PROP_POWER_SUPPLY] = g_param_spec_boolean (INDICATOR_POWER_DEVICE_POWER_SUPPLY,
"power supply",
"The device's power supply",
FALSE,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
g_object_class_install_properties (object_class, N_PROPERTIES, properties);
}
/* Initialize an instance */
static void
indicator_power_device_init (IndicatorPowerDevice *self)
{
IndicatorPowerDevicePrivate * priv;
priv = G_TYPE_INSTANCE_GET_PRIVATE (self, INDICATOR_POWER_DEVICE_TYPE,
IndicatorPowerDevicePrivate);
priv->kind = UP_DEVICE_KIND_UNKNOWN;
priv->state = UP_DEVICE_STATE_UNKNOWN;
priv->object_path = NULL;
priv->percentage = 0.0;
priv->time = 0;
priv->power_supply = FALSE;
self->priv = priv;
}
static void
indicator_power_device_dispose (GObject *object)
{
IndicatorPowerDevice * self = INDICATOR_POWER_DEVICE(object);
IndicatorPowerDevicePrivate * p = self->priv;
g_clear_pointer (&p->inestimable, g_timer_destroy);
G_OBJECT_CLASS (indicator_power_device_parent_class)->dispose (object);
}
static void
indicator_power_device_finalize (GObject *object)
{
IndicatorPowerDevice * self = INDICATOR_POWER_DEVICE(object);
IndicatorPowerDevicePrivate * priv = self->priv;
g_clear_pointer (&priv->object_path, g_free);
G_OBJECT_CLASS (indicator_power_device_parent_class)->finalize (object);
}
/***
****
***/
static void
get_property (GObject * o, guint prop_id, GValue * value, GParamSpec * pspec)
{
IndicatorPowerDevice * self = INDICATOR_POWER_DEVICE(o);
IndicatorPowerDevicePrivate * priv = self->priv;
switch (prop_id)
{
case PROP_KIND:
g_value_set_int (value, priv->kind);
break;
case PROP_STATE:
g_value_set_int (value, priv->state);
break;
case PROP_OBJECT_PATH:
g_value_set_string (value, priv->object_path);
break;
case PROP_PERCENTAGE:
g_value_set_double (value, priv->percentage);
break;
case PROP_TIME:
g_value_set_uint64 (value, (guint64)priv->time);
break;
case PROP_POWER_SUPPLY:
g_value_set_boolean (value, priv->power_supply);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(o, prop_id, pspec);
break;
}
}
static void
set_property (GObject * o, guint prop_id, const GValue * value, GParamSpec * pspec)
{
IndicatorPowerDevice * self = INDICATOR_POWER_DEVICE(o);
IndicatorPowerDevicePrivate * p = self->priv;
switch (prop_id)
{
case PROP_KIND:
p->kind = (UpDeviceKind) g_value_get_int (value);
break;
case PROP_STATE:
p->state = (UpDeviceState) g_value_get_int (value);
break;
case PROP_OBJECT_PATH:
g_free (p->object_path);
p->object_path = g_value_dup_string (value);
break;
case PROP_PERCENTAGE:
p->percentage = g_value_get_double (value);
break;
case PROP_TIME:
p->time = (time_t) g_value_get_uint64(value);
break;
case PROP_POWER_SUPPLY:
p->power_supply = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(o, prop_id, pspec);
break;
}
/**
* Check to see if the time-remaining value is estimable.
* When it first becomes inestimable, kick off a timer because
* we need to track that to generate the appropriate title text.
*/
const gboolean is_inestimable = (p->time == 0)
&& (p->state != UP_DEVICE_STATE_FULLY_CHARGED)
&& (p->percentage > 0);
if (!is_inestimable)
{
g_clear_pointer (&p->inestimable, g_timer_destroy);
}
else if (p->inestimable == NULL)
{
p->inestimable = g_timer_new ();
}
}
/***
**** Accessors
***/
UpDeviceKind
indicator_power_device_get_kind (const IndicatorPowerDevice * device)
{
/* LCOV_EXCL_START */
g_return_val_if_fail (INDICATOR_IS_POWER_DEVICE(device), UP_DEVICE_KIND_UNKNOWN);
/* LCOV_EXCL_STOP */
return device->priv->kind;
}
UpDeviceState
indicator_power_device_get_state (const IndicatorPowerDevice * device)
{
/* LCOV_EXCL_START */
g_return_val_if_fail (INDICATOR_IS_POWER_DEVICE(device), UP_DEVICE_STATE_UNKNOWN);
/* LCOV_EXCL_STOP */
return device->priv->state;
}
const gchar *
indicator_power_device_get_object_path (const IndicatorPowerDevice * device)
{
/* LCOV_EXCL_START */
g_return_val_if_fail (INDICATOR_IS_POWER_DEVICE(device), NULL);
/* LCOV_EXCL_STOP */
return device->priv->object_path;
}
gdouble
indicator_power_device_get_percentage (const IndicatorPowerDevice * device)
{
/* LCOV_EXCL_START */
g_return_val_if_fail (INDICATOR_IS_POWER_DEVICE(device), 0.0);
/* LCOV_EXCL_STOP */
return device->priv->percentage;
}
time_t
indicator_power_device_get_time (const IndicatorPowerDevice * device)
{
/* LCOV_EXCL_START */
g_return_val_if_fail (INDICATOR_IS_POWER_DEVICE(device), (time_t)0);
/* LCOV_EXCL_STOP */
return device->priv->time;
}
gboolean
indicator_power_device_get_power_supply (const IndicatorPowerDevice * device)
{
/* LCOV_EXCL_START */
g_return_val_if_fail (INDICATOR_IS_POWER_DEVICE(device), FALSE);
/* LCOV_EXCL_STOP */
return device->priv->power_supply;
}
/***
****
****
***/
static const gchar *
get_device_icon_suffix (gdouble percentage)
{
if (percentage >= 60) return "full";
if (percentage >= 30) return "good";
if (percentage >= 10) return "low";
return "caution";
}
static const gchar *
get_closest_10_percent_percentage (gdouble percentage)
{
if (percentage >= 95) return "100";
if (percentage >= 85) return "090";
if (percentage >= 75) return "080";
if (percentage >= 65) return "070";
if (percentage >= 55) return "060";
if (percentage >= 45) return "050";
if (percentage >= 35) return "040";
if (percentage >= 21) return "030"; /* don't round down to 20: see bug #1388235 */
if (percentage >= 15) return "020";
if (percentage >= 5) return "010";
return "000";
}
static const gchar *
get_fallback_device_icon_index (gdouble percentage)
{
if (percentage >= 90) return "100";
if (percentage >= 70) return "080";
if (percentage >= 50) return "060";
if (percentage > 20) return "040"; /* don't round down to 20: see bug #1559731 */
if (percentage >= 10) return "020";
return "000";
}
static const char *
device_kind_to_string (UpDeviceKind kind)
{
switch (kind)
{
case UP_DEVICE_KIND_LINE_POWER: return "line-power";
case UP_DEVICE_KIND_BATTERY: return "battery";
case UP_DEVICE_KIND_UPS: return "ups";
case UP_DEVICE_KIND_MONITOR: return "monitor";
case UP_DEVICE_KIND_MOUSE: return "mouse";
case UP_DEVICE_KIND_KEYBOARD: return "keyboard";
case UP_DEVICE_KIND_PDA: return "pda";
case UP_DEVICE_KIND_PHONE: return "phone";
case UP_DEVICE_KIND_MEDIA_PLAYER: return "media-player";
case UP_DEVICE_KIND_TABLET: return "tablet";
case UP_DEVICE_KIND_COMPUTER: return "computer";
default: return "unknown";
}
}
/**
indicator_power_device_get_icon_names:
@device: #IndicatorPowerDevice from which to generate the icon names
See also indicator_power_device_get_gicon().
Return value: (array zero-terminated=1) (transfer full):
A GStrv of icon names suitable for passing to g_themed_icon_new_from_names().
Free with g_strfreev() when done.
*/
GStrv
indicator_power_device_get_icon_names (const IndicatorPowerDevice * device)
{
const gchar *suffix_str;
const gchar *index_str;
const gchar *index_str_2;
/* LCOV_EXCL_START */
g_return_val_if_fail (INDICATOR_IS_POWER_DEVICE(device), NULL);
/* LCOV_EXCL_STOP */
gdouble percentage = indicator_power_device_get_percentage (device);
const UpDeviceKind kind = indicator_power_device_get_kind (device);
const UpDeviceState state = indicator_power_device_get_state (device);
const gchar * kind_str = device_kind_to_string (kind);
GPtrArray * names = g_ptr_array_new ();
if (kind == UP_DEVICE_KIND_LINE_POWER)
{
g_ptr_array_add (names, g_strdup("unity-ac-adapter-symbolic"));
g_ptr_array_add (names, g_strdup("unity-ac-adapter"));
g_ptr_array_add (names, g_strdup("ac-adapter-symbolic"));
g_ptr_array_add (names, g_strdup("ac-adapter"));
}
else if (kind == UP_DEVICE_KIND_MONITOR)
{
g_ptr_array_add (names, g_strdup("unity-gpm-monitor-symbolic"));
g_ptr_array_add (names, g_strdup("unity-gpm-monitor"));
g_ptr_array_add (names, g_strdup("gpm-monitor-symbolic"));
g_ptr_array_add (names, g_strdup("gpm-monitor"));
}
else switch (state)
{
case UP_DEVICE_STATE_EMPTY:
g_ptr_array_add (names, g_strdup_printf("unity-%s-empty-symbolic", kind_str));
g_ptr_array_add (names, g_strdup_printf("unity-gpm-%s-empty", kind_str));
g_ptr_array_add (names, g_strdup_printf("unity-gpm-%s-000", kind_str));
g_ptr_array_add (names, g_strdup_printf("unity-%s-empty", kind_str));
g_ptr_array_add (names, g_strdup_printf("%s-empty-symbolic", kind_str));
g_ptr_array_add (names, g_strdup_printf("gpm-%s-empty", kind_str));
g_ptr_array_add (names, g_strdup_printf("gpm-%s-000", kind_str));
g_ptr_array_add (names, g_strdup_printf("%s-empty", kind_str));
break;
case UP_DEVICE_STATE_FULLY_CHARGED:
g_ptr_array_add (names, g_strdup_printf("unity-%s-full-charged-symbolic", kind_str));
g_ptr_array_add (names, g_strdup_printf("unity-%s-full-charging-symbolic", kind_str));
g_ptr_array_add (names, g_strdup_printf("unity-gpm-%s-full", kind_str));
g_ptr_array_add (names, g_strdup_printf("unity-gpm-%s-100", kind_str));
g_ptr_array_add (names, g_strdup_printf("unity-%s-full-charged", kind_str));
g_ptr_array_add (names, g_strdup_printf("unity-%s-full-charging", kind_str));
g_ptr_array_add (names, g_strdup_printf("%s-full-charged-symbolic", kind_str));
g_ptr_array_add (names, g_strdup_printf("%s-full-charging-symbolic", kind_str));
g_ptr_array_add (names, g_strdup_printf("gpm-%s-full", kind_str));
g_ptr_array_add (names, g_strdup_printf("gpm-%s-100", kind_str));
g_ptr_array_add (names, g_strdup_printf("%s-full-charged", kind_str));
g_ptr_array_add (names, g_strdup_printf("%s-full-charging", kind_str));
break;
case UP_DEVICE_STATE_CHARGING:
suffix_str = get_device_icon_suffix (percentage);
index_str = get_closest_10_percent_percentage (percentage);
g_ptr_array_add (names, g_strdup_printf ("unity-%s-%s-charging", kind_str, index_str));
g_ptr_array_add (names, g_strdup_printf ("unity-gpm-%s-%s-charging", kind_str, index_str));
g_ptr_array_add (names, g_strdup_printf ("%s-%s-charging", kind_str, index_str));
g_ptr_array_add (names, g_strdup_printf ("gpm-%s-%s-charging", kind_str, index_str));
index_str_2 = get_fallback_device_icon_index (percentage);
if (g_strcmp0 (index_str, index_str_2))
{
g_ptr_array_add (names, g_strdup_printf ("unity-%s-%s-charging", kind_str, index_str_2));
g_ptr_array_add (names, g_strdup_printf ("unity-gpm-%s-%s-charging", kind_str, index_str_2));
g_ptr_array_add (names, g_strdup_printf ("%s-%s-charging", kind_str, index_str_2));
g_ptr_array_add (names, g_strdup_printf ("gpm-%s-%s-charging", kind_str, index_str_2));
}
g_ptr_array_add (names, g_strdup_printf ("unity-%s-%s-charging-symbolic", kind_str, suffix_str));
g_ptr_array_add (names, g_strdup_printf ("unity-%s-%s-charging", kind_str, suffix_str));
g_ptr_array_add (names, g_strdup_printf ("%s-%s-charging-symbolic", kind_str, suffix_str));
g_ptr_array_add (names, g_strdup_printf ("%s-%s-charging", kind_str, suffix_str));
// NB: fallthrough to use foo-bar as a fallback for foo-bar-charging
case UP_DEVICE_STATE_PENDING_CHARGE:
case UP_DEVICE_STATE_DISCHARGING:
case UP_DEVICE_STATE_PENDING_DISCHARGE:
case UP_DEVICE_STATE_UNKNOWN: /* http://pad.lv/1470080 */
suffix_str = get_device_icon_suffix (percentage);
index_str = get_closest_10_percent_percentage (percentage);
g_ptr_array_add (names, g_strdup_printf ("unity-%s-%s", kind_str, index_str));
g_ptr_array_add (names, g_strdup_printf ("unity-gpm-%s-%s", kind_str, index_str));
g_ptr_array_add (names, g_strdup_printf ("%s-%s", kind_str, index_str));
g_ptr_array_add (names, g_strdup_printf ("gpm-%s-%s", kind_str, index_str));
index_str_2 = get_fallback_device_icon_index (percentage);
if (g_strcmp0 (index_str, index_str_2))
{
g_ptr_array_add (names, g_strdup_printf ("unity-%s-%s", kind_str, index_str_2));
g_ptr_array_add (names, g_strdup_printf ("unity-gpm-%s-%s", kind_str, index_str_2));
g_ptr_array_add (names, g_strdup_printf ("%s-%s", kind_str, index_str_2));
g_ptr_array_add (names, g_strdup_printf ("gpm-%s-%s", kind_str, index_str_2));
}
g_ptr_array_add (names, g_strdup_printf ("unity-%s-%s-symbolic", kind_str, suffix_str));
g_ptr_array_add (names, g_strdup_printf ("unity-%s-%s", kind_str, suffix_str));
g_ptr_array_add (names, g_strdup_printf ("%s-%s-symbolic", kind_str, suffix_str));
g_ptr_array_add (names, g_strdup_printf ("%s-%s", kind_str, suffix_str));
break;
default:
g_ptr_array_add (names, g_strdup_printf("unity-%s-missing-symbolic", kind_str));
g_ptr_array_add (names, g_strdup_printf("unity-gpm-%s-missing", kind_str));
g_ptr_array_add (names, g_strdup_printf("unity-%s-missing", kind_str));
g_ptr_array_add (names, g_strdup_printf("%s-missing-symbolic", kind_str));
g_ptr_array_add (names, g_strdup_printf("gpm-%s-missing", kind_str));
g_ptr_array_add (names, g_strdup_printf("%s-missing", kind_str));
}
g_ptr_array_add (names, NULL); /* terminates the strv */
return (GStrv) g_ptr_array_free (names, FALSE);
}
/**
indicator_power_device_get_gicon:
@device: #IndicatorPowerDevice to generate the icon names from
A convenience function to call g_themed_icon_new_from_names()
with the names returned by indicator_power_device_get_icon_names()
Return value: (transfer full): A themed GIcon
*/
GIcon *
indicator_power_device_get_gicon (const IndicatorPowerDevice * device)
{
GStrv names = indicator_power_device_get_icon_names (device);
GIcon * icon = g_themed_icon_new_from_names (names, -1);
g_strfreev (names);
return icon;
}
/***
****
***/
static const gchar *
device_kind_to_localised_string (UpDeviceKind kind)
{
const gchar *text = NULL;
switch (kind) {
case UP_DEVICE_KIND_LINE_POWER:
/* TRANSLATORS: system power cord */
text = _("AC Adapter");
break;
case UP_DEVICE_KIND_BATTERY:
/* TRANSLATORS: laptop primary battery */
text = _("Battery");
break;
case UP_DEVICE_KIND_UPS:
/* TRANSLATORS: battery-backed AC power source */
text = _("UPS");
break;
case UP_DEVICE_KIND_MONITOR:
/* TRANSLATORS: a monitor is a device to measure voltage and current */
text = _("Monitor");
break;
case UP_DEVICE_KIND_MOUSE:
/* TRANSLATORS: wireless mice with internal batteries */
text = _("Mouse");
break;
case UP_DEVICE_KIND_KEYBOARD:
/* TRANSLATORS: wireless keyboard with internal battery */
text = _("Keyboard");
break;
case UP_DEVICE_KIND_PDA:
/* TRANSLATORS: portable device */
text = _("PDA");
break;
case UP_DEVICE_KIND_PHONE:
/* TRANSLATORS: cell phone (mobile...) */
text = _("Cell phone");
break;
case UP_DEVICE_KIND_MEDIA_PLAYER:
/* TRANSLATORS: media player, mp3 etc */
text = _("Media player");
break;
case UP_DEVICE_KIND_TABLET:
/* TRANSLATORS: tablet device */
text = _("Tablet");
break;
case UP_DEVICE_KIND_COMPUTER:
/* TRANSLATORS: tablet device */
text = _("Computer");
break;
case UP_DEVICE_KIND_UNKNOWN:
/* TRANSLATORS: unknown device */
text = _("Unknown");
break;
default:
g_warning ("enum unrecognised: %i", kind);
text = device_kind_to_string (kind);
}
return text;
}
/**
* The '''brief time-remaining string''' for a component should be:
* * the time remaining for it to empty or fully charge,
* if estimable, in H:MM format; otherwise
* * “estimating…” if the time remaining has been inestimable for
* less than 30 seconds; otherwise
* * “unknown” if the time remaining has been inestimable for
* between 30 seconds and one minute; otherwise
* * the empty string.
*/
static char *
get_brief_time_remaining (const IndicatorPowerDevice * device)
{
gchar * str = NULL;
const IndicatorPowerDevicePrivate * p = device->priv;
if (p->time > 0)
{
int minutes = p->time / 60;
const int hours = minutes / 60;
minutes %= 60;
str = g_strdup_printf("%0d:%02d", hours, minutes);
}
else if (p->inestimable != NULL)
{
const double elapsed = g_timer_elapsed (p->inestimable, NULL);
if (elapsed < 30)
{
str = g_strdup_printf (_("estimating…"));
}
else if (elapsed < 60)
{
str = g_strdup_printf (_("unknown"));
}
}
return str;
}
/**
* The '''expanded time-remaining string''' for a component should
* be the same as the brief time-remaining string, except that if
* the time is estimable:
* * if the component is charging, it should be “H:MM to charge”
* * if the component is discharging, it should be “H:MM left”.
*/
static char*
get_expanded_time_remaining (const IndicatorPowerDevice * device)
{
char * str = NULL;
const IndicatorPowerDevicePrivate * p = device->priv;
if (p->time && ((p->state == UP_DEVICE_STATE_CHARGING) || (p->state == UP_DEVICE_STATE_DISCHARGING)))
{
int minutes = p->time / 60;
const int hours = minutes / 60;
minutes %= 60;
if (p->state == UP_DEVICE_STATE_CHARGING)
{
/* TRANSLATORS: H:MM (hours, minutes) to charge the battery. Example: "1:30 to charge" */
str = g_strdup_printf (_("%0d:%02d to charge"), hours, minutes);
}
else // discharging
{
/* TRANSLATORS: H:MM (hours, minutes) to discharge the battery. Example: "1:30 left"*/
str = g_strdup_printf (_("%0d:%02d left"), hours, minutes);
}
}
else
{
str = get_brief_time_remaining (device);
}
return str;
}
/**
* The '''accessible time-remaining string''' for a component
* should be the same as the expanded time-remaining string,
* except the H:MM time should be rendered as “''H'' hours ''M'' minutes”,
* or just as “''M'' minutes” if the time is less than one hour.
*/
static char *
get_accessible_time_remaining (const IndicatorPowerDevice * device)
{
char * str = NULL;
const IndicatorPowerDevicePrivate * p = device->priv;
if (p->time && ((p->state == UP_DEVICE_STATE_CHARGING) || (p->state == UP_DEVICE_STATE_DISCHARGING)))
{
guint minutes = (guint)p->time / 60u;
const guint hours = minutes / 60u;
minutes %= 60;
if (p->state == UP_DEVICE_STATE_CHARGING)
{
if (hours > 0)
{
/* TRANSLATORS: "X (hour,hours) Y (minute,minutes) to charge" the battery.
Example: "1 hour 10 minutes to charge" */
str = g_strdup_printf (_("%d %s %d %s to charge"),
hours, g_dngettext (NULL, "hour", "hours", hours),
minutes, g_dngettext (NULL, "minute", "minutes", minutes));
}
else
{
/* TRANSLATORS: "Y (minute,minutes) to charge" the battery.
Example: "59 minutes to charge" */
str = g_strdup_printf (_("%d %s to charge"),
minutes, g_dngettext (NULL, "minute", "minutes", minutes));
}
}
else // discharging
{
if (hours > 0)
{
/* TRANSLATORS: "X (hour,hours) Y (minute,minutes) left" until the battery's empty.
Example: "1 hour 10 minutes left" */
str = g_strdup_printf (_("%d %s %d %s left"),
hours, g_dngettext (NULL, "hour", "hours", hours),
minutes, g_dngettext (NULL, "minute", "minutes", minutes));
}
else
{
/* TRANSLATORS: "Y (minute,minutes) left" until the battery's empty.
Example: "59 minutes left" */
str = g_strdup_printf (_("%d %s left"),
minutes, g_dngettext (NULL, "minute", "minutes", minutes));
}
}
}
else
{
str = get_brief_time_remaining (device);
}
return str;
}
/**
* The time is relevant for a device if either (a) the component is charging,
* or (b) the component is discharging and the estimated time is less than
* 24 hours. (A time greater than 24 hours is probably a mistaken calculation.)
*/
static gboolean
time_is_relevant (const IndicatorPowerDevice * device)
{
const IndicatorPowerDevicePrivate * p = device->priv;
if (p->state == UP_DEVICE_STATE_CHARGING)
return TRUE;
if ((p->state == UP_DEVICE_STATE_DISCHARGING) && (p->time<(24*60*60)))
return TRUE;
return FALSE;
}
/**
* The menu item for each chargeable component should consist of ...
* Text representing the name of the component (“Battery”, “Mouse”,
* “UPS”, “Alejandra’s iPod”, etc) and the charge status in brackets:
*
* * “X (charged)” if it is fully charged and not discharging;
* * “X (expanded time-remaining string)” if it is charging,
* or discharging with less than 24 hours left;
* * “X” if it is discharging with 24 hours or more left.
*
* The accessible label for the menu item should be the same as the
* visible label, except with the accessible time-remaining string
* instead of the expanded time-remaining string.
*/
static char *
get_menuitem_text (const IndicatorPowerDevice * device,
gboolean accessible)
{
char * str = NULL;
const IndicatorPowerDevicePrivate * p = device->priv;
const char * kind_str = device_kind_to_localised_string (p->kind);
if (p->state == UP_DEVICE_STATE_FULLY_CHARGED)
{
/* TRANSLATORS: example: "battery (charged)" */
str = g_strdup_printf (_("%s (charged)"), kind_str);
}
else
{
char * time_str = NULL;
if (time_is_relevant (device))
{
if (accessible)
time_str = get_accessible_time_remaining (device);
else
time_str = get_expanded_time_remaining (device);
}
if (time_str && *time_str)
{
/* TRANSLATORS: example: "battery (time remaining)" */
str = g_strdup_printf (_("%s (%s)"), kind_str, time_str);
}
else
{
str = g_strdup (kind_str);
}
g_free (time_str);
}
return str;
}
char *
indicator_power_device_get_readable_text (const IndicatorPowerDevice * device)
{
g_return_val_if_fail (INDICATOR_IS_POWER_DEVICE(device), NULL);
return get_menuitem_text (device, FALSE);
}
char *
indicator_power_device_get_accessible_text (const IndicatorPowerDevice * device)
{
g_return_val_if_fail (INDICATOR_IS_POWER_DEVICE(device), NULL);
return get_menuitem_text (device, TRUE);
}
/**
* If the time is relevant and/or “Show Percentage in Menu Bar” is checked,
* the icon should be followed by brackets.
*
* If the time is relevant, the brackets should contain the time-remaining
* string for that component.
*
* If “Show Percentage in Menu Bar” is checked (as it should not be by default),
* the brackets should contain the percentage charge for that device.
*
* If both conditions are true, the time and percentage should be separated by a space.
*/
char*
indicator_power_device_get_readable_title (const IndicatorPowerDevice * device,
gboolean want_time,
gboolean want_percent)
{
char * str = NULL;
char * time_str = NULL;
const IndicatorPowerDevicePrivate * p;
g_return_val_if_fail (INDICATOR_IS_POWER_DEVICE(device), NULL);
p = device->priv;
// if we can't provide time-remaining, turn off the time flag
if (want_time && !time_is_relevant (device))
want_time = FALSE;
// if we can't provide percent, turn off the percent flag
if (p->percentage < 0.01)
want_percent = FALSE;
// try to build the time-remaining string
if (want_time)
{
time_str = get_brief_time_remaining (device);
want_time = time_str && *time_str;
}
if (want_time && want_percent)
{
/* TRANSLATORS: after the icon, a time-remaining string + battery %. Example: "(0:59, 33%)" */
str = g_strdup_printf (_("(%s, %.0lf%%)"), time_str, p->percentage);
}
else if (want_time)
{
/* TRANSLATORS: after the icon, a time-remaining string Example: "(0:59)" */
str = g_strdup_printf (_("(%s)"), time_str);
}
else if (want_percent)
{
/* TRANSLATORS: after the icon, a battery %. Example: "(33%)" */
str = g_strdup_printf (_("(%.0lf%%)"), p->percentage);
}
else
{
str = NULL;
}
g_free (time_str);
return str;
}
/**
* Regardless, the accessible name for the whole menu title should be the same
* as the accessible name for that thing’s component inside the menu itself.
*/
char *
indicator_power_device_get_accessible_title (const IndicatorPowerDevice * device,
gboolean want_time G_GNUC_UNUSED,
gboolean want_percent G_GNUC_UNUSED)
{
g_return_val_if_fail (INDICATOR_IS_POWER_DEVICE(device), NULL);
return indicator_power_device_get_accessible_text (device);
}
/***
**** Instantiation
***/
IndicatorPowerDevice *
indicator_power_device_new (const gchar * object_path,
UpDeviceKind kind,
gdouble percentage,
UpDeviceState state,
time_t timestamp,
gboolean power_supply)
{
GObject * o = g_object_new (INDICATOR_POWER_DEVICE_TYPE,
INDICATOR_POWER_DEVICE_KIND, kind,
INDICATOR_POWER_DEVICE_STATE, state,
INDICATOR_POWER_DEVICE_OBJECT_PATH, object_path,
INDICATOR_POWER_DEVICE_PERCENTAGE, percentage,
INDICATOR_POWER_DEVICE_TIME, (guint64)timestamp,
INDICATOR_POWER_DEVICE_POWER_SUPPLY, power_supply,
NULL);
return INDICATOR_POWER_DEVICE(o);
}
IndicatorPowerDevice *
indicator_power_device_new_from_variant (GVariant * v)
{
g_return_val_if_fail (g_variant_is_of_type (v, G_VARIANT_TYPE("(susdutb)")), NULL);
UpDeviceKind kind = UP_DEVICE_KIND_UNKNOWN;
UpDeviceState state = UP_DEVICE_STATE_UNKNOWN;
const gchar * icon = NULL;
const gchar * object_path = NULL;
gdouble percentage = 0;
guint64 time = 0;
gboolean power_supply = FALSE;
g_variant_get (v, "(&su&sdutb)",
&object_path,
&kind,
&icon,
&percentage,
&state,
&time,
&power_supply);
return indicator_power_device_new (object_path,
kind,
percentage,
state,
(time_t)time,
power_supply);
}
./src/device-provider-upower.c 0000644 0000041 0000041 00000046267 13151304741 016622 0 ustar www-data www-data /*
* Copyright 2013 Canonical Ltd.
*
* Authors:
* Charles Kerr
*
* 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 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 .
*/
#include "device.h"
#include "device-provider.h"
#include "device-provider-upower.h"
#define BUS_NAME "org.freedesktop.UPower"
#define MGR_IFACE "org.freedesktop.UPower"
#define MGR_PATH "/org/freedesktop/UPower"
#define DISPLAY_DEVICE_PATH "/org/freedesktop/UPower/devices/DisplayDevice"
/***
**** private struct
***/
typedef struct
{
GDBusConnection * bus;
GCancellable * cancellable;
/* dbus object path --> IndicatorPowerDevice */
GHashTable * devices;
/* a hashset of paths whose devices need to be refreshed */
GHashTable * queued_paths;
/* when this timer fires, the queued_paths will be refreshed */
guint queued_paths_timer;
GSList* subscriptions;
guint name_tag;
}
IndicatorPowerDeviceProviderUPowerPrivate;
typedef IndicatorPowerDeviceProviderUPowerPrivate priv_t;
#define get_priv(o) ((priv_t*)indicator_power_device_provider_upower_get_instance_private(o))
/***
**** GObject boilerplate
***/
static void indicator_power_device_provider_interface_init (
IndicatorPowerDeviceProviderInterface * iface);
G_DEFINE_TYPE_WITH_CODE (
IndicatorPowerDeviceProviderUPower,
indicator_power_device_provider_upower,
G_TYPE_OBJECT,
G_ADD_PRIVATE(IndicatorPowerDeviceProviderUPower)
G_IMPLEMENT_INTERFACE (INDICATOR_TYPE_POWER_DEVICE_PROVIDER,
indicator_power_device_provider_interface_init))
/***
**** UPOWER DBUS
***/
struct device_get_all_data
{
char * path;
IndicatorPowerDeviceProviderUPower * self;
};
static void
emit_devices_changed (IndicatorPowerDeviceProviderUPower * self)
{
indicator_power_device_provider_emit_devices_changed (INDICATOR_POWER_DEVICE_PROVIDER (self));
}
static void
on_get_all_response (GObject * o, GAsyncResult * res, gpointer gdata)
{
struct device_get_all_data * data = gdata;
GError * error;
GVariant * response;
error = NULL;
response = g_dbus_connection_call_finish (G_DBUS_CONNECTION(o), res, &error);
if (error != NULL)
{
if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
g_warning ("Error getting properties for UPower device '%s': %s",
data->path, error->message);
g_error_free (error);
}
else
{
guint32 kind = 0;
guint32 state = 0;
gdouble percentage = 0;
gint64 time_to_empty = 0;
gint64 time_to_full = 0;
gint64 time;
gboolean power_supply = FALSE;
IndicatorPowerDevice * device;
priv_t * p = get_priv(data->self);
GVariant * dict = g_variant_get_child_value (response, 0);
g_variant_lookup (dict, "Type", "u", &kind);
g_variant_lookup (dict, "State", "u", &state);
g_variant_lookup (dict, "Percentage", "d", &percentage);
g_variant_lookup (dict, "TimeToEmpty", "x", &time_to_empty);
g_variant_lookup (dict, "TimeToFull", "x", &time_to_full);
g_variant_lookup (dict, "PowerSupply", "b", &power_supply);
time = time_to_empty ? time_to_empty : time_to_full;
if ((device = g_hash_table_lookup (p->devices, data->path)))
{
g_object_set (device, INDICATOR_POWER_DEVICE_KIND, (gint)kind,
INDICATOR_POWER_DEVICE_STATE, (gint)state,
INDICATOR_POWER_DEVICE_OBJECT_PATH, data->path,
INDICATOR_POWER_DEVICE_PERCENTAGE, percentage,
INDICATOR_POWER_DEVICE_TIME, time,
INDICATOR_POWER_DEVICE_POWER_SUPPLY, power_supply,
NULL);
}
else
{
device = indicator_power_device_new (data->path,
kind,
percentage,
state,
(time_t)time,
power_supply);
g_hash_table_insert (p->devices,
g_strdup (data->path),
g_object_ref (device));
g_object_unref (device);
}
emit_devices_changed (data->self);
g_variant_unref (dict);
g_variant_unref (response);
}
g_free (data->path);
g_slice_free (struct device_get_all_data, data);
}
static void
update_device_from_object_path (IndicatorPowerDeviceProviderUPower * self,
const char * path)
{
priv_t * p = get_priv(self);
struct device_get_all_data * data;
/* Symbolic composite item. Nice idea! But its composite rules
differ from Design's so (for now) don't use it.
https://wiki.ubuntu.com/Power#Handling_multiple_batteries */
if (!g_strcmp0(path, DISPLAY_DEVICE_PATH))
return;
data = g_slice_new (struct device_get_all_data);
data->path = g_strdup (path);
data->self = self;
g_dbus_connection_call(p->bus,
BUS_NAME,
path,
"org.freedesktop.DBus.Properties",
"GetAll",
g_variant_new ("(s)", "org.freedesktop.UPower.Device"),
G_VARIANT_TYPE("(a{sv})"),
G_DBUS_CALL_FLAGS_NO_AUTO_START,
-1, /* default timeout */
p->cancellable,
on_get_all_response,
data);
}
/*
* UPower 0.99 added proper PropertyChanged signals, but before that
* it MGR_IFACE emitted a DeviceChanged signal which didn't tell which
* property changed, so all properties had to get refreshed w/GetAll().
*
* Changes often come in bursts, so this timer tries to fold them together
* by waiting a small bit before making calling GetAll().
*/
/* rebuild all the devices listed in our queued_paths hashset */
static gboolean
on_queued_paths_timer(gpointer gself)
{
IndicatorPowerDeviceProviderUPower * self;
priv_t * p;
GHashTableIter iter;
gpointer path;
self = INDICATOR_POWER_DEVICE_PROVIDER_UPOWER (gself);
p = get_priv(self);
/* create new devices for all the queued paths */
g_hash_table_iter_init (&iter, p->queued_paths);
while (g_hash_table_iter_next (&iter, &path, NULL))
update_device_from_object_path (self, path);
/* cleanup */
g_hash_table_remove_all (p->queued_paths);
p->queued_paths_timer = 0;
return G_SOURCE_REMOVE;
}
/* add the path to our queued_paths hashset and ensure the timer's running */
static void
refresh_device_soon (IndicatorPowerDeviceProviderUPower * self,
const char * object_path)
{
priv_t * p = get_priv(self);
g_hash_table_add (p->queued_paths, g_strdup (object_path));
if (p->queued_paths_timer == 0)
p->queued_paths_timer = g_timeout_add (500, on_queued_paths_timer, self);
}
/***
****
***/
static void
on_enumerate_devices_response(GObject * bus,
GAsyncResult * res,
gpointer gself)
{
GError* error;
GVariant* v;
error = NULL;
v = g_dbus_connection_call_finish(G_DBUS_CONNECTION(bus), res, &error);
if (v == NULL)
{
if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
g_warning ("Unable to enumerate UPower devices: %s", error->message);
g_error_free (error);
}
else if (g_variant_is_of_type(v, G_VARIANT_TYPE("(ao)")))
{
GVariant * ao;
GVariantIter iter;
const gchar * path;
ao = g_variant_get_child_value(v, 0);
g_variant_iter_init(&iter, ao);
path = NULL;
while(g_variant_iter_loop(&iter, "o", &path))
refresh_device_soon (gself, path);
g_variant_unref(ao);
}
g_clear_pointer(&v, g_variant_unref);
}
static void
on_device_properties_changed(GDBusConnection * connection G_GNUC_UNUSED,
const gchar * sender_name G_GNUC_UNUSED,
const gchar * object_path,
const gchar * interface_name G_GNUC_UNUSED,
const gchar * signal_name G_GNUC_UNUSED,
GVariant * parameters,
gpointer gself)
{
IndicatorPowerDeviceProviderUPower* self;
priv_t* p;
IndicatorPowerDevice* device;
self = INDICATOR_POWER_DEVICE_PROVIDER_UPOWER(gself);
p = get_priv(self);
device = g_hash_table_lookup(p->devices, object_path);
if (device == NULL) /* unlikely, but let's handle it */
{
refresh_device_soon (self, object_path);
}
else if ((parameters != NULL) && g_variant_n_children(parameters)>=2)
{
gboolean changed = FALSE;
GVariant* dict;
GVariantIter iter;
gchar* key;
GVariant* value;
dict = g_variant_get_child_value(parameters, 1);
g_variant_iter_init(&iter, dict);
while (g_variant_iter_next(&iter, "{sv}", &key, &value))
{
if (!g_strcmp0(key, "TimeToFull") || !g_strcmp0(key, "TimeToEmpty"))
{
const gint64 i = g_variant_get_int64(value);
if (i != 0)
{
g_object_set(device,
INDICATOR_POWER_DEVICE_TIME, (guint64)i,
NULL);
changed = TRUE;
}
}
else if (!g_strcmp0(key, "Percentage"))
{
const gdouble d = g_variant_get_double(value);
g_object_set(device,
INDICATOR_POWER_DEVICE_PERCENTAGE, d,
NULL);
changed = TRUE;
}
else if (!g_strcmp0(key, "Type"))
{
const guint32 u = g_variant_get_uint32(value);
g_object_set(device,
INDICATOR_POWER_DEVICE_KIND, (gint)u,
NULL);
changed = TRUE;
}
else if (!g_strcmp0(key, "State"))
{
const guint32 u = g_variant_get_uint32(value);
g_object_set(device,
INDICATOR_POWER_DEVICE_STATE, (gint)u,
NULL);
changed = TRUE;
}
}
g_variant_unref(dict);
if (changed)
emit_devices_changed(self);
}
}
static const gchar*
get_path_from_nth_child(GVariant* parameters, gsize i)
{
const gchar* path = NULL;
if ((parameters != NULL) && g_variant_n_children(parameters)>i)
{
GVariant* v = g_variant_get_child_value(parameters, i);
if (g_variant_is_of_type(v, G_VARIANT_TYPE_STRING) || /* UPower < 0.99 */
g_variant_is_of_type(v, G_VARIANT_TYPE_OBJECT_PATH)) /* and >= 0.99 */
{
path = g_variant_get_string(v, NULL);
}
g_variant_unref(v);
}
return path;
}
static void
on_upower_signal(GDBusConnection * connection G_GNUC_UNUSED,
const gchar * sender_name G_GNUC_UNUSED,
const gchar * object_path G_GNUC_UNUSED,
const gchar * interface_name G_GNUC_UNUSED,
const gchar * signal_name,
GVariant * parameters,
gpointer gself)
{
IndicatorPowerDeviceProviderUPower * self;
priv_t * p;
self = INDICATOR_POWER_DEVICE_PROVIDER_UPOWER(gself);
p = get_priv(self);
if (!g_strcmp0(signal_name, "DeviceAdded"))
{
refresh_device_soon (self, get_path_from_nth_child(parameters, 0));
}
else if (!g_strcmp0(signal_name, "DeviceRemoved"))
{
const char* device_path = get_path_from_nth_child(parameters, 0);
g_hash_table_remove(p->devices, device_path);
g_hash_table_remove(p->queued_paths, device_path);
emit_devices_changed(self);
}
else if (!g_strcmp0(signal_name, "DeviceChanged")) /* UPower < 0.99 */
{
refresh_device_soon (self, get_path_from_nth_child(parameters, 0));
}
else if (!g_strcmp0(signal_name, "Resuming")) /* UPower < 0.99 */
{
GHashTableIter iter;
gpointer device_path = NULL;
g_debug("Resumed from hibernate/sleep; queueing all devices for a refresh");
g_hash_table_iter_init (&iter, p->devices);
while (g_hash_table_iter_next (&iter, &device_path, NULL))
refresh_device_soon (self, device_path);
}
}
/* start listening for UPower events on the bus */
static void
on_bus_name_appeared(GDBusConnection * bus,
const gchar * name G_GNUC_UNUSED,
const gchar * name_owner,
gpointer gself)
{
IndicatorPowerDeviceProviderUPower * self;
priv_t * p;
guint tag;
self = INDICATOR_POWER_DEVICE_PROVIDER_UPOWER(gself);
p = get_priv(self);
p->bus = G_DBUS_CONNECTION(g_object_ref(bus));
/* listen for signals from the boss */
tag = g_dbus_connection_signal_subscribe(p->bus,
name_owner,
MGR_IFACE,
NULL /*signal_name*/,
MGR_PATH,
NULL /*arg0*/,
G_DBUS_SIGNAL_FLAGS_NONE,
on_upower_signal,
self,
NULL);
p->subscriptions = g_slist_prepend(p->subscriptions, GUINT_TO_POINTER(tag));
/* listen for change events from the devices */
tag = g_dbus_connection_signal_subscribe(p->bus,
name_owner,
"org.freedesktop.DBus.Properties",
"PropertiesChanged",
NULL /*object_path*/,
"org.freedesktop.UPower.Device", /*arg0*/
G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE,
on_device_properties_changed,
self,
NULL);
p->subscriptions = g_slist_prepend(p->subscriptions, GUINT_TO_POINTER(tag));
/* rebuild our devices list */
g_dbus_connection_call(p->bus,
BUS_NAME,
MGR_PATH,
MGR_IFACE,
"EnumerateDevices",
NULL,
G_VARIANT_TYPE("(ao)"),
G_DBUS_CALL_FLAGS_NO_AUTO_START,
-1, /* default timeout */
p->cancellable,
on_enumerate_devices_response,
self);
}
static void
on_bus_name_vanished(GDBusConnection * connection G_GNUC_UNUSED,
const gchar * name G_GNUC_UNUSED,
gpointer gself)
{
IndicatorPowerDeviceProviderUPower * self;
priv_t * p;
GSList * l;
self = INDICATOR_POWER_DEVICE_PROVIDER_UPOWER(gself);
p = get_priv(self);
/* clear the devices */
g_hash_table_remove_all(p->devices);
g_hash_table_remove_all(p->queued_paths);
if (p->queued_paths_timer != 0)
{
g_source_remove(p->queued_paths_timer);
p->queued_paths_timer = 0;
}
emit_devices_changed (self);
/* clear the bus subscriptions */
for (l=p->subscriptions; l!=NULL; l=l->next)
g_dbus_connection_signal_unsubscribe(p->bus, GPOINTER_TO_UINT(l->data));
g_slist_free(p->subscriptions);
p->subscriptions = NULL;
/* clear the bus */
g_clear_object(&p->bus);
}
/***
**** IndicatorPowerDeviceProvider virtual functions
***/
static GList *
my_get_devices(IndicatorPowerDeviceProvider * provider)
{
IndicatorPowerDeviceProviderUPower * self;
priv_t * p;
GList * devices;
self = INDICATOR_POWER_DEVICE_PROVIDER_UPOWER(provider);
p = get_priv(self);
devices = g_hash_table_get_values (p->devices);
g_list_foreach (devices, (GFunc)g_object_ref, NULL);
return devices;
}
/***
**** GObject virtual functions
***/
static void
my_dispose (GObject * o)
{
IndicatorPowerDeviceProviderUPower * self;
priv_t * p;
self = INDICATOR_POWER_DEVICE_PROVIDER_UPOWER(o);
p = get_priv(self);
if (p->cancellable != NULL)
{
g_cancellable_cancel (p->cancellable);
g_clear_object (&p->cancellable);
}
if (p->queued_paths_timer != 0)
{
g_source_remove (p->queued_paths_timer);
p->queued_paths_timer = 0;
}
if (p->name_tag != 0)
{
g_bus_unwatch_name(p->name_tag);
on_bus_name_vanished(NULL, NULL, self);
p->name_tag = 0;
}
G_OBJECT_CLASS (indicator_power_device_provider_upower_parent_class)->dispose(o);
}
static void
my_finalize (GObject * o)
{
IndicatorPowerDeviceProviderUPower * self;
priv_t * p;
self = INDICATOR_POWER_DEVICE_PROVIDER_UPOWER(o);
p = get_priv(self);
g_hash_table_destroy (p->devices);
g_hash_table_destroy (p->queued_paths);
G_OBJECT_CLASS (indicator_power_device_provider_upower_parent_class)->finalize (o);
}
/***
**** Instantiation
***/
static void
indicator_power_device_provider_upower_class_init (IndicatorPowerDeviceProviderUPowerClass * klass)
{
GObjectClass * object_class = G_OBJECT_CLASS (klass);
object_class->dispose = my_dispose;
object_class->finalize = my_finalize;
}
static void
indicator_power_device_provider_interface_init (IndicatorPowerDeviceProviderInterface * iface)
{
iface->get_devices = my_get_devices;
}
static void
indicator_power_device_provider_upower_init (IndicatorPowerDeviceProviderUPower * self)
{
priv_t * p = get_priv(self);
p->cancellable = g_cancellable_new();
p->devices = g_hash_table_new_full(g_str_hash,
g_str_equal,
g_free,
g_object_unref);
p->queued_paths = g_hash_table_new_full(g_str_hash,
g_str_equal,
g_free,
NULL);
p->name_tag = g_bus_watch_name(G_BUS_TYPE_SYSTEM,
BUS_NAME,
G_BUS_NAME_WATCHER_FLAGS_NONE,
on_bus_name_appeared,
on_bus_name_vanished,
self,
NULL);
}
/***
**** Public API
***/
IndicatorPowerDeviceProvider *
indicator_power_device_provider_upower_new(void)
{
gpointer o = g_object_new (INDICATOR_TYPE_POWER_DEVICE_PROVIDER_UPOWER, NULL);
return INDICATOR_POWER_DEVICE_PROVIDER (o);
}
./src/service.h 0000644 0000041 0000041 00000005034 13151304741 013644 0 ustar www-data www-data /*
* Copyright 2013 Canonical Ltd.
*
* Authors:
* Charles Kerr
*
* 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 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 .
*/
#ifndef __INDICATOR_POWER_SERVICE_H__
#define __INDICATOR_POWER_SERVICE_H__
#include
#include
#include "device-provider.h"
#include "notifier.h"
G_BEGIN_DECLS
/* standard GObject macros */
#define INDICATOR_POWER_SERVICE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), INDICATOR_TYPE_POWER_SERVICE, IndicatorPowerService))
#define INDICATOR_TYPE_POWER_SERVICE (indicator_power_service_get_type())
#define INDICATOR_IS_POWER_SERVICE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), INDICATOR_TYPE_POWER_SERVICE))
typedef struct _IndicatorPowerService IndicatorPowerService;
typedef struct _IndicatorPowerServiceClass IndicatorPowerServiceClass;
typedef struct _IndicatorPowerServicePrivate IndicatorPowerServicePrivate;
/* signal keys */
#define INDICATOR_POWER_SERVICE_SIGNAL_NAME_LOST "name-lost"
/**
* The Indicator Power Service.
*/
struct _IndicatorPowerService
{
/*< private >*/
GObject parent;
IndicatorPowerServicePrivate * priv;
};
struct _IndicatorPowerServiceClass
{
GObjectClass parent_class;
/* signals */
void (* name_lost)(IndicatorPowerService * self);
};
/***
****
***/
GType indicator_power_service_get_type (void);
IndicatorPowerService * indicator_power_service_new (IndicatorPowerDeviceProvider * provider,
IndicatorPowerNotifier * notifier);
void indicator_power_service_set_device_provider (IndicatorPowerService * self,
IndicatorPowerDeviceProvider * provider);
void indicator_power_service_set_notifier (IndicatorPowerService * self,
IndicatorPowerNotifier * notifier);
IndicatorPowerDevice * indicator_power_service_choose_primary_device (GList * devices);
G_END_DECLS
#endif /* __INDICATOR_POWER_SERVICE_H__ */
./src/testing.h 0000644 0000041 0000041 00000003746 13151304741 013671 0 ustar www-data www-data /*
* Copyright 2014 Canonical Ltd.
*
* 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 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 .
*
* Authors:
* Charles Kerr
*/
#ifndef __INDICATOR_POWER_TESTING_H__
#define __INDICATOR_POWER_TESTING_H__
#include
#include "service.h"
G_BEGIN_DECLS
/* standard GObject macros */
#define INDICATOR_POWER_TESTING(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), INDICATOR_TYPE_POWER_TESTING, IndicatorPowerTesting))
#define INDICATOR_TYPE_POWER_TESTING (indicator_power_testing_get_type())
#define INDICATOR_IS_POWER_TESTING(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), INDICATOR_TYPE_POWER_TESTING))
#define INDICATOR_POWER_TESTING_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), INDICATOR_TYPE_POWER_TESTING, IndicatorPowerTestingClass))
typedef struct _IndicatorPowerTesting IndicatorPowerTesting;
typedef struct _IndicatorPowerTestingClass IndicatorPowerTestingClass;
/**
* The Indicator Power Testing.
*/
struct _IndicatorPowerTesting
{
/*< private >*/
GObject parent;
};
struct _IndicatorPowerTestingClass
{
GObjectClass parent_class;
};
/***
****
***/
GType indicator_power_testing_get_type (void);
IndicatorPowerTesting * indicator_power_testing_new (IndicatorPowerService * service);
void indicator_power_testing_set_bus (IndicatorPowerTesting * self,
GDBusConnection * connection);
G_END_DECLS
#endif /* __INDICATOR_POWER_TESTING_H__ */
./src/brightness.h 0000644 0000041 0000041 00000003763 13151304741 014363 0 ustar www-data www-data /*
* Copyright 2014 Canonical Ltd.
*
* 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 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 .
*
* Authors:
* Charles Kerr
*/
#ifndef INDICATOR_POWER_BRIGHTNESS__H
#define INDICATOR_POWER_BRIGHTNESS__H
#include
#include
G_BEGIN_DECLS
/* standard GObject macros */
#define INDICATOR_POWER_BRIGHTNESS(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), INDICATOR_TYPE_POWER_BRIGHTNESS, IndicatorPowerBrightness))
#define INDICATOR_TYPE_POWER_BRIGHTNESS (indicator_power_brightness_get_type())
#define INDICATOR_IS_POWER_BRIGHTNESS(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), INDICATOR_TYPE_POWER_BRIGHTNESS))
typedef struct _IndicatorPowerBrightness IndicatorPowerBrightness;
typedef struct _IndicatorPowerBrightnessClass IndicatorPowerBrightnessClass;
/* property keys */
#define INDICATOR_POWER_BRIGHTNESS_PROP_PERCENTAGE "percentage"
/**
* The Indicator Power Brightness.
*/
struct _IndicatorPowerBrightness
{
/*< private >*/
GObject parent;
};
struct _IndicatorPowerBrightnessClass
{
GObjectClass parent_class;
};
/***
****
***/
GType indicator_power_brightness_get_type(void);
IndicatorPowerBrightness * indicator_power_brightness_new(void);
void indicator_power_brightness_set_percentage(IndicatorPowerBrightness * self, double percentage);
double indicator_power_brightness_get_percentage(IndicatorPowerBrightness * self);
G_END_DECLS
#endif /* INDICATOR_POWER_BRIGHTNESS__H */
./src/device.h 0000644 0000041 0000041 00000012514 13151304741 013444 0 ustar www-data www-data /*
A simple Device structure used internally by indicator-power
Copyright 2012 Canonical Ltd.
Authors:
Charles Kerr
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 3.0 as published by the Free Software Foundation.
This library 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 version 3.0 for more details.
You should have received a copy of the GNU General Public
License along with this library. If not, see
.
*/
#ifndef __INDICATOR_POWER_DEVICE_H__
#define __INDICATOR_POWER_DEVICE_H__
#include /* GIcon */
G_BEGIN_DECLS
#define INDICATOR_POWER_DEVICE_TYPE (indicator_power_device_get_type ())
#define INDICATOR_POWER_DEVICE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), INDICATOR_POWER_DEVICE_TYPE, IndicatorPowerDevice))
#define INDICATOR_POWER_DEVICE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), INDICATOR_POWER_DEVICE_TYPE, IndicatorPowerDeviceClass))
#define INDICATOR_IS_POWER_DEVICE(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), INDICATOR_POWER_DEVICE_TYPE))
#define INDICATOR_IS_POWER_DEVICE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), INDICATOR_POWER_DEVICE_TYPE))
#define INDICATOR_POWER_DEVICE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), INDICATOR_POWER_DEVICE_TYPE, IndicatorPowerDeviceClass))
typedef struct _IndicatorPowerDevice IndicatorPowerDevice;
typedef struct _IndicatorPowerDeviceClass IndicatorPowerDeviceClass;
typedef struct _IndicatorPowerDevicePrivate IndicatorPowerDevicePrivate;
#define INDICATOR_POWER_DEVICE_KIND "kind"
#define INDICATOR_POWER_DEVICE_STATE "state"
#define INDICATOR_POWER_DEVICE_OBJECT_PATH "object-path"
#define INDICATOR_POWER_DEVICE_PERCENTAGE "percentage"
#define INDICATOR_POWER_DEVICE_TIME "time"
#define INDICATOR_POWER_DEVICE_POWER_SUPPLY "power-supply"
typedef enum
{
UP_DEVICE_KIND_UNKNOWN,
UP_DEVICE_KIND_LINE_POWER,
UP_DEVICE_KIND_BATTERY,
UP_DEVICE_KIND_UPS,
UP_DEVICE_KIND_MONITOR,
UP_DEVICE_KIND_MOUSE,
UP_DEVICE_KIND_KEYBOARD,
UP_DEVICE_KIND_PDA,
UP_DEVICE_KIND_PHONE,
UP_DEVICE_KIND_MEDIA_PLAYER,
UP_DEVICE_KIND_TABLET,
UP_DEVICE_KIND_COMPUTER,
UP_DEVICE_KIND_LAST
}
UpDeviceKind;
typedef enum
{
UP_DEVICE_STATE_UNKNOWN,
UP_DEVICE_STATE_CHARGING,
UP_DEVICE_STATE_DISCHARGING,
UP_DEVICE_STATE_EMPTY,
UP_DEVICE_STATE_FULLY_CHARGED,
UP_DEVICE_STATE_PENDING_CHARGE,
UP_DEVICE_STATE_PENDING_DISCHARGE,
UP_DEVICE_STATE_LAST
}
UpDeviceState;
/**
* IndicatorPowerDeviceClass:
* @parent_class: #GObjectClass
*/
struct _IndicatorPowerDeviceClass
{
GObjectClass parent_class;
};
/**
* IndicatorPowerDevice:
* @parent: #GObject
* @priv: A cached reference to the private data for the instance.
*/
struct _IndicatorPowerDevice
{
GObject parent;
IndicatorPowerDevicePrivate * priv;
};
/***
****
***/
GType indicator_power_device_get_type (void);
IndicatorPowerDevice* indicator_power_device_new (const gchar * object_path,
UpDeviceKind kind,
gdouble percentage,
UpDeviceState state,
time_t time,
gboolean power_supply);
/**
* Convenience wrapper around indicator_power_device_new()
* @variant holds the same args as indicator_power_device_new() in "(susdut)"
*/
IndicatorPowerDevice* indicator_power_device_new_from_variant (GVariant * variant);
UpDeviceKind indicator_power_device_get_kind (const IndicatorPowerDevice * device);
UpDeviceState indicator_power_device_get_state (const IndicatorPowerDevice * device);
const gchar * indicator_power_device_get_object_path (const IndicatorPowerDevice * device);
gdouble indicator_power_device_get_percentage (const IndicatorPowerDevice * device);
time_t indicator_power_device_get_time (const IndicatorPowerDevice * device);
gboolean indicator_power_device_get_power_supply (const IndicatorPowerDevice * device);
GStrv indicator_power_device_get_icon_names (const IndicatorPowerDevice * device);
GIcon * indicator_power_device_get_gicon (const IndicatorPowerDevice * device);
char * indicator_power_device_get_readable_text (const IndicatorPowerDevice * device);
char * indicator_power_device_get_accessible_text (const IndicatorPowerDevice * device);
char * indicator_power_device_get_readable_title (const IndicatorPowerDevice * device,
gboolean want_time,
gboolean want_percent);
char * indicator_power_device_get_accessible_title (const IndicatorPowerDevice * device,
gboolean want_time,
gboolean want_percent);
G_END_DECLS
#endif
./src/notifier.c 0000644 0000041 0000041 00000040724 13151304741 014023 0 ustar www-data www-data /*
* Copyright 2014-2016 Canonical Ltd.
*
* 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 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 .
*
* Authors:
* Charles Kerr
*/
#include "datafiles.h"
#include "dbus-accounts-sound.h"
#include "dbus-battery.h"
#include "dbus-shared.h"
#include "notifier.h"
#include
#include
#include
#include /* UINT32_MAX */
typedef enum
{
POWER_LEVEL_CRITICAL,
POWER_LEVEL_VERY_LOW,
POWER_LEVEL_LOW,
POWER_LEVEL_OK
}
PowerLevel;
/**
*** GObject Properties
**/
enum
{
PROP_0,
PROP_BATTERY,
LAST_PROP
};
#define PROP_BATTERY_NAME "battery"
static GParamSpec * properties[LAST_PROP];
static int instance_count = 0;
/**
***
**/
typedef struct
{
/* The battery we're currently watching.
This may be a physical battery or it may be an aggregated
battery from multiple batteries present on the device.
See indicator_power_service_choose_primary_device() and
bug #880881 */
IndicatorPowerDevice * battery;
PowerLevel power_level;
gboolean discharging;
NotifyNotification * notify_notification;
GDBusConnection * bus;
DbusBattery * dbus_battery; /* com.canonical.indicator.power.Battery skeleton */
gboolean caps_queried;
gboolean actions_supported;
GCancellable * cancellable;
DbusAccountsServiceSound * accounts_service_sound_proxy;
gboolean accounts_service_sound_proxy_pending;
}
IndicatorPowerNotifierPrivate;
typedef IndicatorPowerNotifierPrivate priv_t;
G_DEFINE_TYPE_WITH_PRIVATE(IndicatorPowerNotifier,
indicator_power_notifier,
G_TYPE_OBJECT)
#define get_priv(o) ((priv_t*)indicator_power_notifier_get_instance_private(o))
/***
****
***/
static const char *
power_level_to_dbus_string (const PowerLevel power_level)
{
switch (power_level)
{
case POWER_LEVEL_LOW: return POWER_LEVEL_STR_LOW;
case POWER_LEVEL_VERY_LOW: return POWER_LEVEL_STR_VERY_LOW;
case POWER_LEVEL_CRITICAL: return POWER_LEVEL_STR_CRITICAL;
default: return POWER_LEVEL_STR_OK;
}
}
static PowerLevel
get_battery_power_level (IndicatorPowerDevice * battery)
{
static const double percent_critical = 2.0;
static const double percent_very_low = 5.0;
static const double percent_low = 10.0;
gdouble p;
PowerLevel ret;
g_return_val_if_fail(battery != NULL, POWER_LEVEL_OK);
g_return_val_if_fail(indicator_power_device_get_kind(battery) == UP_DEVICE_KIND_BATTERY, POWER_LEVEL_OK);
p = indicator_power_device_get_percentage(battery);
if (p <= percent_critical)
ret = POWER_LEVEL_CRITICAL;
else if (p <= percent_very_low)
ret = POWER_LEVEL_VERY_LOW;
else if (p <= percent_low)
ret = POWER_LEVEL_LOW;
else
ret = POWER_LEVEL_OK;
return ret;
}
/***
**** Sounds
***/
static void
on_sound_proxy_ready (GObject * source_object G_GNUC_UNUSED,
GAsyncResult * res,
gpointer gself)
{
GError * error;
DbusAccountsServiceSound * proxy;
error = NULL;
proxy = dbus_accounts_service_sound_proxy_new_for_bus_finish (res, &error);
if (error != NULL)
{
if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
{
get_priv(gself)->accounts_service_sound_proxy_pending = FALSE;
g_debug("%s Couldn't find accounts service sound proxy: %s", G_STRLOC, error->message);
}
g_clear_error(&error);
}
else
{
IndicatorPowerNotifier * const self = INDICATOR_POWER_NOTIFIER(gself);
priv_t * const p = get_priv (self);
g_clear_object (&p->accounts_service_sound_proxy);
p->accounts_service_sound_proxy = proxy;
p->accounts_service_sound_proxy_pending = FALSE;
}
}
static gboolean
silent_mode (IndicatorPowerNotifier * self)
{
priv_t * const p = get_priv (self);
/* if we don't have a proxy yet, assume we're in silent mode
as a "do no harm" level of response */
if (p->accounts_service_sound_proxy_pending)
return TRUE;
return (p->accounts_service_sound_proxy != NULL)
&& dbus_accounts_service_sound_get_silent_mode(p->accounts_service_sound_proxy);
}
/***
**** Notifications
***/
static void
on_notify_notification_finalized (gpointer gself, GObject * dead)
{
IndicatorPowerNotifier * const self = INDICATOR_POWER_NOTIFIER(gself);
priv_t * const p = get_priv(self);
g_return_if_fail ((void*)(p->notify_notification) == (void*)dead);
p->notify_notification = NULL;
dbus_battery_set_is_warning (p->dbus_battery, FALSE);
}
static void
notification_clear (IndicatorPowerNotifier * self)
{
priv_t * const p = get_priv(self);
NotifyNotification * nn;
if ((nn = p->notify_notification))
{
GError * error = NULL;
g_object_weak_unref(G_OBJECT(nn), on_notify_notification_finalized, self);
if (!notify_notification_close(nn, &error))
{
g_warning("Unable to close notification: %s", error->message);
g_error_free(error);
}
p->notify_notification = NULL;
dbus_battery_set_is_warning (p->dbus_battery, FALSE);
}
}
static void
on_battery_settings_clicked(NotifyNotification * nn G_GNUC_UNUSED,
char * action G_GNUC_UNUSED,
gpointer user_data G_GNUC_UNUSED)
{
url_dispatch_send("settings:///system/battery", NULL, NULL);
}
static void
on_dismiss_clicked(NotifyNotification * nn G_GNUC_UNUSED,
char * action G_GNUC_UNUSED,
gpointer user_data G_GNUC_UNUSED)
{
/* no-op; libnotify warns if we have a NULL action callback */
}
static gboolean
are_actions_supported(IndicatorPowerNotifier * self)
{
priv_t * const p = get_priv(self);
if (!p->caps_queried)
{
gboolean actions_supported;
GList * caps;
GList * l;
/* see if actions are supported */
actions_supported = FALSE;
caps = notify_get_server_caps();
for (l=caps; l!=NULL && !actions_supported; l=l->next)
if (!g_strcmp0(l->data, "actions"))
actions_supported = TRUE;
p->actions_supported = actions_supported;
p->caps_queried = TRUE;
g_list_free_full(caps, g_free);
}
return p->actions_supported;
}
static void
notification_show(IndicatorPowerNotifier * self)
{
priv_t * const p = get_priv(self);
gdouble pct;
const char * title;
char * body;
GStrv icon_names;
const char * icon_name;
NotifyNotification * nn;
GError * error;
const PowerLevel power_level = get_battery_power_level(p->battery);
notification_clear(self);
g_return_if_fail(power_level != POWER_LEVEL_OK);
/* create the notification */
title = power_level == POWER_LEVEL_LOW
? _("Battery Low")
: _("Battery Critical");
pct = indicator_power_device_get_percentage(p->battery);
body = g_strdup_printf(_("%.0f%% charge remaining"), pct);
icon_names = indicator_power_device_get_icon_names(p->battery);
if (icon_names && *icon_names)
icon_name = icon_names[0];
else
icon_name = NULL;
nn = notify_notification_new(title, body, icon_name);
g_strfreev (icon_names);
g_free (body);
if (are_actions_supported(self))
{
if (!silent_mode(self))
{
gchar* filename = datafile_find(DATAFILE_TYPE_SOUND, LOW_BATTERY_SOUND);
if (filename != NULL)
{
gchar * uri = g_filename_to_uri(filename, NULL, NULL);
notify_notification_set_hint(nn, "sound-file", g_variant_new_take_string(uri));
g_clear_pointer(&filename, g_free);
}
else
{
g_warning("Unable to find '%s' in XDG data dirs", LOW_BATTERY_SOUND);
}
}
notify_notification_set_hint(nn, "x-canonical-snap-decisions", g_variant_new_string("true"));
notify_notification_set_hint(nn, "x-canonical-non-shaped-icon", g_variant_new_string("true"));
notify_notification_set_hint(nn, "x-canonical-private-affirmative-tint", g_variant_new_string("true"));
notify_notification_set_hint(nn, "x-canonical-snap-decisions-timeout", g_variant_new_int32(INT32_MAX));
notify_notification_set_timeout(nn, NOTIFY_EXPIRES_NEVER);
notify_notification_add_action(nn, "dismiss", _("OK"), on_dismiss_clicked, NULL, NULL);
notify_notification_add_action(nn, "settings", _("Battery settings"), on_battery_settings_clicked, NULL, NULL);
}
/* if we can show it, keep it */
error = NULL;
if (notify_notification_show(nn, &error))
{
p->notify_notification = nn;
g_signal_connect(nn, "closed", G_CALLBACK(g_object_unref), NULL);
g_object_weak_ref(G_OBJECT(nn), on_notify_notification_finalized, self);
dbus_battery_set_is_warning (p->dbus_battery, TRUE);
}
else
{
g_critical("Unable to show snap decision for '%s': %s", body, error->message);
g_error_free(error);
g_object_unref(nn);
}
}
/***
****
***/
static void
on_battery_property_changed (IndicatorPowerNotifier * self)
{
priv_t * p;
PowerLevel old_power_level;
PowerLevel new_power_level;
gboolean old_discharging;
gboolean new_discharging;
g_return_if_fail(INDICATOR_IS_POWER_NOTIFIER(self));
p = get_priv (self);
g_return_if_fail(INDICATOR_IS_POWER_DEVICE(p->battery));
old_power_level = p->power_level;
new_power_level = get_battery_power_level (p->battery);
old_discharging = p->discharging;
new_discharging = indicator_power_device_get_state(p->battery) == UP_DEVICE_STATE_DISCHARGING;
/* pop up a 'low battery' notification if either:
a) it's already discharging, and its PowerLevel worsens, OR
b) it's already got a bad PowerLevel and its state becomes 'discharging */
if ((new_discharging && (old_power_level > new_power_level)) ||
((new_power_level != POWER_LEVEL_OK) && new_discharging && !old_discharging))
{
notification_show (self);
}
else if (!new_discharging || (new_power_level == POWER_LEVEL_OK))
{
notification_clear (self);
}
dbus_battery_set_power_level (p->dbus_battery, power_level_to_dbus_string (new_power_level));
p->power_level = new_power_level;
p->discharging = new_discharging;
}
/***
**** GObject virtual functions
***/
static void
my_get_property (GObject * o,
guint property_id,
GValue * value,
GParamSpec * pspec)
{
IndicatorPowerNotifier * const self = INDICATOR_POWER_NOTIFIER (o);
priv_t * const p = get_priv (self);
switch (property_id)
{
case PROP_BATTERY:
g_value_set_object (value, p->battery);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (o, property_id, pspec);
}
}
static void
my_set_property (GObject * o,
guint property_id,
const GValue * value,
GParamSpec * pspec)
{
IndicatorPowerNotifier * const self = INDICATOR_POWER_NOTIFIER (o);
switch (property_id)
{
case PROP_BATTERY:
indicator_power_notifier_set_battery (self, g_value_get_object(value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (o, property_id, pspec);
}
}
static void
my_dispose (GObject * o)
{
IndicatorPowerNotifier * const self = INDICATOR_POWER_NOTIFIER(o);
priv_t * const p = get_priv (self);
if (p->cancellable != NULL)
{
g_cancellable_cancel(p->cancellable);
g_clear_object(&p->cancellable);
}
indicator_power_notifier_set_bus (self, NULL);
notification_clear (self);
indicator_power_notifier_set_battery (self, NULL);
g_clear_object (&p->dbus_battery);
g_clear_object (&p->accounts_service_sound_proxy);
G_OBJECT_CLASS (indicator_power_notifier_parent_class)->dispose (o);
}
static void
my_finalize (GObject * o G_GNUC_UNUSED)
{
/* FIXME: This is an awkward place to put this.
Ordinarily something like this would go in main(), but we need libnotify
to clean itself up before shutting down the bus in the unit tests as well. */
if (!--instance_count)
notify_uninit();
}
/***
**** Instantiation
***/
static void
indicator_power_notifier_init (IndicatorPowerNotifier * self)
{
priv_t * const p = get_priv (self);
/* bind the read-only properties so they'll get pushed to the bus */
p->dbus_battery = dbus_battery_skeleton_new ();
p->power_level = POWER_LEVEL_OK;
p->cancellable = g_cancellable_new();
if (!instance_count++ && !notify_init(SERVICE_EXEC))
g_critical("Unable to initialize libnotify! Notifications might not be shown.");
p->accounts_service_sound_proxy_pending = TRUE;
gchar* object_path = g_strdup_printf("/org/freedesktop/Accounts/User%lu", (gulong)getuid());
dbus_accounts_service_sound_proxy_new_for_bus(
G_BUS_TYPE_SYSTEM,
G_DBUS_PROXY_FLAGS_GET_INVALIDATED_PROPERTIES,
"org.freedesktop.Accounts",
object_path,
p->cancellable,
on_sound_proxy_ready,
self);
g_clear_pointer(&object_path, g_free);
}
static void
indicator_power_notifier_class_init (IndicatorPowerNotifierClass * klass)
{
GObjectClass * object_class = G_OBJECT_CLASS (klass);
object_class->dispose = my_dispose;
object_class->finalize = my_finalize;
object_class->get_property = my_get_property;
object_class->set_property = my_set_property;
properties[PROP_BATTERY] = g_param_spec_object (
PROP_BATTERY_NAME,
"Battery",
"The current battery",
G_TYPE_OBJECT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
g_object_class_install_properties (object_class, LAST_PROP, properties);
}
/***
**** Public API
***/
IndicatorPowerNotifier *
indicator_power_notifier_new (void)
{
GObject * o = g_object_new (INDICATOR_TYPE_POWER_NOTIFIER, NULL);
return INDICATOR_POWER_NOTIFIER (o);
}
void
indicator_power_notifier_set_battery (IndicatorPowerNotifier * self,
IndicatorPowerDevice * battery)
{
priv_t * p;
g_return_if_fail(INDICATOR_IS_POWER_NOTIFIER(self));
g_return_if_fail((battery == NULL) || INDICATOR_IS_POWER_DEVICE(battery));
g_return_if_fail((battery == NULL) || (indicator_power_device_get_kind(battery) == UP_DEVICE_KIND_BATTERY));
p = get_priv (self);
if (p->battery == battery)
return;
if (p->battery != NULL)
{
g_signal_handlers_disconnect_by_data (p->battery, self);
g_clear_object (&p->battery);
dbus_battery_set_power_level (p->dbus_battery, power_level_to_dbus_string (POWER_LEVEL_OK));
notification_clear (self);
}
if (battery != NULL)
{
p->battery = g_object_ref (battery);
g_signal_connect_swapped (p->battery, "notify::"INDICATOR_POWER_DEVICE_PERCENTAGE,
G_CALLBACK(on_battery_property_changed), self);
g_signal_connect_swapped (p->battery, "notify::"INDICATOR_POWER_DEVICE_STATE,
G_CALLBACK(on_battery_property_changed), self);
on_battery_property_changed (self);
}
}
void
indicator_power_notifier_set_bus (IndicatorPowerNotifier * self,
GDBusConnection * bus)
{
priv_t * p;
GDBusInterfaceSkeleton * skel;
g_return_if_fail(INDICATOR_IS_POWER_NOTIFIER(self));
g_return_if_fail((bus == NULL) || G_IS_DBUS_CONNECTION(bus));
p = get_priv (self);
if (p->bus == bus)
return;
skel = G_DBUS_INTERFACE_SKELETON(p->dbus_battery);
if (p->bus != NULL)
{
if (skel != NULL)
g_dbus_interface_skeleton_unexport (skel);
g_clear_object (&p->bus);
}
if (bus != NULL)
{
GError * error;
p->bus = g_object_ref (bus);
error = NULL;
if (!g_dbus_interface_skeleton_export(skel,
bus,
BUS_PATH"/Battery",
&error))
{
g_warning ("Unable to export LowBattery properties: %s", error->message);
g_error_free (error);
}
}
}
const char *
indicator_power_notifier_get_power_level (IndicatorPowerDevice * battery)
{
return power_level_to_dbus_string (get_battery_power_level (battery));
}
./src/device-provider.c 0000644 0000041 0000041 00000004605 13151304741 015271 0 ustar www-data www-data /*
* Copyright 2013 Canonical Ltd.
*
* Authors:
* Charles Kerr
*
* 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 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 .
*/
#include "device-provider.h"
enum
{
SIGNAL_DEVICES_CHANGED,
SIGNAL_LAST
};
static guint signals[SIGNAL_LAST] = { 0 };
G_DEFINE_INTERFACE (IndicatorPowerDeviceProvider,
indicator_power_device_provider,
0)
static void
indicator_power_device_provider_default_init (IndicatorPowerDeviceProviderInterface * klass)
{
signals[SIGNAL_DEVICES_CHANGED] = g_signal_new (
"devices-changed",
G_TYPE_FROM_CLASS(klass),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (IndicatorPowerDeviceProviderInterface, devices_changed),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
}
/***
**** PUBLIC API
***/
/**
* Get a list of devices
*
* An easy way to free the list properly in one step is as follows:
*
* g_slist_free_full (list, (GDestroyNotify)g_object_unref);
*
* Return value: (element-type IndicatorPowerDevice)
* (transfer full):
* list of devices
*/
GList *
indicator_power_device_provider_get_devices (IndicatorPowerDeviceProvider * self)
{
GList * devices;
IndicatorPowerDeviceProviderInterface * iface;
g_return_val_if_fail (INDICATOR_IS_POWER_DEVICE_PROVIDER (self), NULL);
iface = INDICATOR_POWER_DEVICE_PROVIDER_GET_INTERFACE (self);
if (iface->get_devices != NULL)
devices = iface->get_devices (self);
else
devices = NULL;
return devices;
}
/**
* Emits the "devices-changed" signal.
*
* This should only be called by subclasses.
*/
void
indicator_power_device_provider_emit_devices_changed (IndicatorPowerDeviceProvider * self)
{
g_return_if_fail (INDICATOR_IS_POWER_DEVICE_PROVIDER (self));
g_signal_emit (self, signals[SIGNAL_DEVICES_CHANGED], 0, NULL);
}
./src/testing.c 0000644 0000041 0000041 00000022627 13151304741 013663 0 ustar www-data www-data /*
* Copyright 2014 Canonical Ltd.
*
* 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 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 .
*
* Authors:
* Charles Kerr
*/
#include "dbus-shared.h"
#include "device-provider-mock.h"
#include "device-provider-upower.h"
#include "dbus-testing.h"
#include "service.h"
#include "testing.h"
#include
/**
*** GObject Properties
**/
enum
{
PROP_0,
PROP_SERVICE,
LAST_PROP
};
static GParamSpec * properties[LAST_PROP];
/**
***
**/
typedef struct
{
GDBusConnection * bus;
DbusTesting * skeleton;
IndicatorPowerService * service;
IndicatorPowerDevice * battery_mock;
gpointer provider_mock;
gpointer provider_upower;
}
IndicatorPowerTestingPrivate;
typedef IndicatorPowerTestingPrivate priv_t;
G_DEFINE_TYPE_WITH_PRIVATE(IndicatorPowerTesting,
indicator_power_testing,
G_TYPE_OBJECT)
#define get_priv(o) ((priv_t*)indicator_power_testing_get_instance_private(o))
/***
****
***/
static void
update_device_provider (IndicatorPowerTesting * self)
{
priv_t * const p = get_priv(self);
IndicatorPowerDeviceProvider * device_provider;
device_provider = dbus_testing_get_mock_battery_enabled(p->skeleton)
? p->provider_mock
: p->provider_upower;
indicator_power_service_set_device_provider(p->service, device_provider);
}
static void
set_bus(IndicatorPowerTesting * self, GDBusConnection * bus)
{
priv_t * p;
GDBusInterfaceSkeleton * skel;
g_return_if_fail(INDICATOR_IS_POWER_TESTING(self));
g_return_if_fail((bus == NULL) || G_IS_DBUS_CONNECTION(bus));
p = get_priv (self);
if (p->bus == bus)
return;
skel = G_DBUS_INTERFACE_SKELETON(p->skeleton);
if (p->bus != NULL)
{
if (skel != NULL)
g_dbus_interface_skeleton_unexport (skel);
g_clear_object (&p->bus);
}
if (bus != NULL)
{
GError * error;
p->bus = g_object_ref (bus);
error = NULL;
if (!g_dbus_interface_skeleton_export(skel,
bus,
BUS_PATH"/Testing",
&error))
{
g_warning ("Unable to export Testing properties: %s", error->message);
g_error_free (error);
}
}
}
/***
****
***/
static void
on_mock_battery_enabled_changed(DbusTesting * skeleton G_GNUC_UNUSED,
GParamSpec * pspec G_GNUC_UNUSED,
IndicatorPowerTesting * self)
{
update_device_provider (self);
}
static void
on_mock_battery_level_changed(DbusTesting * skeleton,
GParamSpec * pspec G_GNUC_UNUSED,
IndicatorPowerTesting * self)
{
g_object_set(get_priv(self)->battery_mock,
INDICATOR_POWER_DEVICE_PERCENTAGE, (gdouble)dbus_testing_get_mock_battery_level(skeleton),
NULL);
}
static void
on_mock_battery_state_changed(DbusTesting * skeleton,
GParamSpec * pspec G_GNUC_UNUSED,
IndicatorPowerTesting * self)
{
const gchar* state_str = dbus_testing_get_mock_battery_state(skeleton);
UpDeviceState state;
if (!g_strcmp0(state_str, "charging"))
{
state = UP_DEVICE_STATE_CHARGING;
}
else if (!g_strcmp0(state_str, "discharging"))
{
state = UP_DEVICE_STATE_DISCHARGING;
}
else
{
g_warning("%s unsupported state: '%s'", G_STRLOC, state_str);
state = UP_DEVICE_STATE_UNKNOWN;
}
g_object_set(get_priv(self)->battery_mock,
INDICATOR_POWER_DEVICE_STATE, (gint)state,
NULL);
}
static void
on_mock_battery_minutes_left_changed(DbusTesting * skeleton,
GParamSpec * pspec G_GNUC_UNUSED,
IndicatorPowerTesting * self)
{
g_object_set(get_priv(self)->battery_mock,
INDICATOR_POWER_DEVICE_TIME, (guint64)dbus_testing_get_mock_battery_minutes_left(skeleton),
NULL);
}
static void
on_bus_changed(IndicatorPowerService * service,
GParamSpec * spec G_GNUC_UNUSED,
IndicatorPowerTesting * self)
{
GObject * bus = NULL;
g_object_get(service, "bus", &bus, NULL);
set_bus(self, G_DBUS_CONNECTION(bus));
g_clear_object(&bus);
}
/***
**** GObject virtual functions
***/
static void
my_get_property(GObject * o,
guint property_id,
GValue * value,
GParamSpec * pspec)
{
IndicatorPowerTesting * const self = INDICATOR_POWER_TESTING (o);
priv_t * const p = get_priv(self);
switch (property_id)
{
case PROP_SERVICE:
g_value_set_object(value, p->service);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(o, property_id, pspec);
}
}
static void
my_set_property(GObject * o,
guint property_id,
const GValue * value,
GParamSpec * pspec)
{
IndicatorPowerTesting * const self = INDICATOR_POWER_TESTING (o);
priv_t * const p = get_priv(self);
switch (property_id)
{
case PROP_SERVICE:
g_assert(p->service == NULL); /* G_PARAM_CONSTRUCT_ONLY */
p->service = g_value_dup_object(value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(o, property_id, pspec);
}
}
static void
my_dispose(GObject * o)
{
IndicatorPowerTesting * const self = INDICATOR_POWER_TESTING(o);
priv_t * const p = get_priv (self);
set_bus(self, NULL);
g_clear_object(&p->skeleton);
g_clear_object(&p->provider_upower);
g_clear_object(&p->provider_mock);
g_clear_object(&p->battery_mock);
g_clear_object(&p->service);
G_OBJECT_CLASS (indicator_power_testing_parent_class)->dispose(o);
}
static void
my_finalize (GObject * o G_GNUC_UNUSED)
{
}
static void
my_constructed (GObject * o)
{
IndicatorPowerTesting * const self = INDICATOR_POWER_TESTING(o);
priv_t * const p = get_priv (self);
g_assert(p->service != NULL); /* G_PARAM_CONSTRUCT_ONLY */
g_signal_connect(p->service, "notify::bus", G_CALLBACK(on_bus_changed), o);
on_bus_changed(p->service, NULL, self);
update_device_provider(self);
}
/***
**** Instantiation
***/
static void
indicator_power_testing_init (IndicatorPowerTesting * self)
{
priv_t * const p = get_priv (self);
/* DBus Skeleton */
p->skeleton = dbus_testing_skeleton_new();
dbus_testing_set_mock_battery_level(p->skeleton, 50u);
dbus_testing_set_mock_battery_state(p->skeleton, "discharging");
dbus_testing_set_mock_battery_enabled(p->skeleton, FALSE);
dbus_testing_set_mock_battery_minutes_left(p->skeleton, 30);
g_signal_connect(p->skeleton, "notify::mock-battery-enabled",
G_CALLBACK(on_mock_battery_enabled_changed), self);
g_signal_connect(p->skeleton, "notify::mock-battery-level",
G_CALLBACK(on_mock_battery_level_changed), self);
g_signal_connect(p->skeleton, "notify::mock-battery-state",
G_CALLBACK(on_mock_battery_state_changed), self);
g_signal_connect(p->skeleton, "notify::mock-battery-minutes-left",
G_CALLBACK(on_mock_battery_minutes_left_changed), self);
/* Mock Battery */
p->battery_mock = indicator_power_device_new("/some/path",
UP_DEVICE_KIND_BATTERY,
50.0,
UP_DEVICE_STATE_DISCHARGING,
60*30,
TRUE);
/* Mock Provider */
p->provider_mock = indicator_power_device_provider_mock_new();
indicator_power_device_provider_add_device(INDICATOR_POWER_DEVICE_PROVIDER_MOCK(p->provider_mock),
p->battery_mock);
/* UPower Provider */
p->provider_upower = indicator_power_device_provider_upower_new();
}
static void
indicator_power_testing_class_init (IndicatorPowerTestingClass * klass)
{
GObjectClass * object_class = G_OBJECT_CLASS (klass);
object_class->dispose = my_dispose;
object_class->finalize = my_finalize;
object_class->constructed = my_constructed;
object_class->get_property = my_get_property;
object_class->set_property = my_set_property;
properties[PROP_SERVICE] = g_param_spec_object (
"service",
"Servie",
"The IndicatorPower Service",
G_TYPE_OBJECT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_CONSTRUCT_ONLY);
g_object_class_install_properties (object_class, LAST_PROP, properties);
}
/***
**** Public API
***/
IndicatorPowerTesting *
indicator_power_testing_new (IndicatorPowerService * service)
{
GObject * o = g_object_new (INDICATOR_TYPE_POWER_TESTING, "service", service, NULL);
return INDICATOR_POWER_TESTING (o);
}
./src/device-provider-mock.h 0000644 0000041 0000041 00000005141 13151304741 016221 0 ustar www-data www-data /*
* Copyright 2014 Canonical Ltd.
*
* 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 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 .
*
* Authors:
* Charles Kerr
*/
#ifndef __INDICATOR_POWER_DEVICE_PROVIDER_MOCK__H__
#define __INDICATOR_POWER_DEVICE_PROVIDER_MOCK__H__
#include /* parent class */
#include "device.h"
#include "device-provider.h"
G_BEGIN_DECLS
#define INDICATOR_TYPE_POWER_DEVICE_PROVIDER_MOCK \
(indicator_power_device_provider_mock_get_type())
#define INDICATOR_POWER_DEVICE_PROVIDER_MOCK(o) \
(G_TYPE_CHECK_INSTANCE_CAST ((o), \
INDICATOR_TYPE_POWER_DEVICE_PROVIDER_MOCK, \
IndicatorPowerDeviceProviderMock))
#define INDICATOR_POWER_DEVICE_PROVIDER_MOCK_GET_CLASS(o) \
(G_TYPE_INSTANCE_GET_CLASS ((o), \
INDICATOR_TYPE_POWER_DEVICE_PROVIDER_MOCK, \
IndicatorPowerDeviceProviderMockClass))
#define INDICATOR_IS_POWER_DEVICE_PROVIDER_MOCK(o) \
(G_TYPE_CHECK_INSTANCE_TYPE ((o), \
INDICATOR_TYPE_POWER_DEVICE_PROVIDER_MOCK))
typedef struct _IndicatorPowerDeviceProviderMock
IndicatorPowerDeviceProviderMock;
typedef struct _IndicatorPowerDeviceProviderMockPriv
IndicatorPowerDeviceProviderMockPriv;
typedef struct _IndicatorPowerDeviceProviderMockClass
IndicatorPowerDeviceProviderMockClass;
/**
* An IndicatorPowerDeviceProvider which gets its devices from Mock.
*/
struct _IndicatorPowerDeviceProviderMock
{
GObject parent_instance;
/*< private >*/
GList * devices;
};
struct _IndicatorPowerDeviceProviderMockClass
{
GObjectClass parent_class;
};
GType indicator_power_device_provider_mock_get_type (void);
IndicatorPowerDeviceProvider * indicator_power_device_provider_mock_new (void);
void indicator_power_device_provider_add_device (IndicatorPowerDeviceProviderMock * provider,
IndicatorPowerDevice * device);
G_END_DECLS
#endif /* __INDICATOR_POWER_DEVICE_PROVIDER_MOCK__H__ */
./src/main.c 0000644 0000041 0000041 00000003567 13151304741 013134 0 ustar www-data www-data /*
* Copyright 2013-2016 Canonical Ltd.
*
* 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 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 .
*
* Authors:
* Charles Kerr
*/
#include
#include
#include
#include "device.h"
#include "notifier.h"
#include "service.h"
#include "testing.h"
/***
****
***/
static void
on_name_lost (gpointer instance G_GNUC_UNUSED, gpointer loop)
{
g_message ("exiting: service couldn't acquire or lost ownership of busname");
g_main_loop_quit ((GMainLoop*)loop);
}
int
main (int argc G_GNUC_UNUSED, char ** argv G_GNUC_UNUSED)
{
IndicatorPowerNotifier * notifier;
IndicatorPowerService * service;
IndicatorPowerTesting * testing;
GMainLoop * loop;
/* boilerplate i18n */
setlocale (LC_ALL, "");
bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR);
textdomain (GETTEXT_PACKAGE);
/* run */
notifier = indicator_power_notifier_new();
service = indicator_power_service_new(NULL, notifier);
testing = indicator_power_testing_new (service);
loop = g_main_loop_new (NULL, FALSE);
g_signal_connect (service, INDICATOR_POWER_SERVICE_SIGNAL_NAME_LOST,
G_CALLBACK(on_name_lost), loop);
g_main_loop_run (loop);
/* cleanup */
g_main_loop_unref (loop);
g_clear_object (&testing);
g_clear_object (&service);
g_clear_object (¬ifier);
return 0;
}
./src/device-provider-upower.h 0000644 0000041 0000041 00000004454 13151304741 016617 0 ustar www-data www-data /*
* Copyright 2013 Canonical Ltd.
*
* Authors:
* Charles Kerr
*
* 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 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 .
*/
#ifndef __INDICATOR_POWER_DEVICE_PROVIDER_UPOWER__H__
#define __INDICATOR_POWER_DEVICE_PROVIDER_UPOWER__H__
#include /* parent class */
#include "device-provider.h"
G_BEGIN_DECLS
#define INDICATOR_TYPE_POWER_DEVICE_PROVIDER_UPOWER \
(indicator_power_device_provider_upower_get_type())
#define INDICATOR_POWER_DEVICE_PROVIDER_UPOWER(o) \
(G_TYPE_CHECK_INSTANCE_CAST ((o), \
INDICATOR_TYPE_POWER_DEVICE_PROVIDER_UPOWER, \
IndicatorPowerDeviceProviderUPower))
#define INDICATOR_POWER_DEVICE_PROVIDER_UPOWER_GET_CLASS(o) \
(G_TYPE_INSTANCE_GET_CLASS ((o), \
INDICATOR_TYPE_POWER_DEVICE_PROVIDER_UPOWER, \
IndicatorPowerDeviceProviderUPowerClass))
#define INDICATOR_IS_POWER_DEVICE_PROVIDER_UPOWER(o) \
(G_TYPE_CHECK_INSTANCE_TYPE ((o), \
INDICATOR_TYPE_POWER_DEVICE_PROVIDER_UPOWER))
typedef struct _IndicatorPowerDeviceProviderUPower
IndicatorPowerDeviceProviderUPower;
typedef struct _IndicatorPowerDeviceProviderUPowerClass
IndicatorPowerDeviceProviderUPowerClass;
/**
* An IndicatorPowerDeviceProvider which gets its devices from UPower.
*/
struct _IndicatorPowerDeviceProviderUPower
{
GObject parent_instance;
};
struct _IndicatorPowerDeviceProviderUPowerClass
{
GObjectClass parent_class;
};
GType indicator_power_device_provider_upower_get_type (void);
IndicatorPowerDeviceProvider * indicator_power_device_provider_upower_new (void);
G_END_DECLS
#endif /* __INDICATOR_POWER_DEVICE_PROVIDER_UPOWER__H__ */
./src/notifier.h 0000644 0000041 0000041 00000004571 13151304741 014030 0 ustar www-data www-data /*
* Copyright 2014-2016 Canonical Ltd.
*
* 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 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 .
*
* Authors:
* Charles Kerr
*/
#ifndef __INDICATOR_POWER_NOTIFIER_H__
#define __INDICATOR_POWER_NOTIFIER_H__
#include
#include "device.h"
G_BEGIN_DECLS
/* standard GObject macros */
#define INDICATOR_POWER_NOTIFIER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), INDICATOR_TYPE_POWER_NOTIFIER, IndicatorPowerNotifier))
#define INDICATOR_TYPE_POWER_NOTIFIER (indicator_power_notifier_get_type())
#define INDICATOR_IS_POWER_NOTIFIER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), INDICATOR_TYPE_POWER_NOTIFIER))
#define INDICATOR_POWER_NOTIFIER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), INDICATOR_TYPE_POWER_NOTIFIER, IndicatorPowerNotifierClass))
typedef struct _IndicatorPowerNotifier IndicatorPowerNotifier;
typedef struct _IndicatorPowerNotifierClass IndicatorPowerNotifierClass;
/**
* The Indicator Power Notifier.
*/
struct _IndicatorPowerNotifier
{
/*< private >*/
GObject parent;
};
struct _IndicatorPowerNotifierClass
{
GObjectClass parent_class;
};
/***
****
***/
GType indicator_power_notifier_get_type (void);
IndicatorPowerNotifier * indicator_power_notifier_new (void);
void indicator_power_notifier_set_bus (IndicatorPowerNotifier * self,
GDBusConnection * connection);
void indicator_power_notifier_set_battery (IndicatorPowerNotifier * self,
IndicatorPowerDevice * battery);
#define POWER_LEVEL_STR_OK "ok"
#define POWER_LEVEL_STR_LOW "low"
#define POWER_LEVEL_STR_VERY_LOW "very_low"
#define POWER_LEVEL_STR_CRITICAL "critical"
const char * indicator_power_notifier_get_power_level (IndicatorPowerDevice * battery);
G_END_DECLS
#endif /* __INDICATOR_POWER_NOTIFIER_H__ */
./src/device-provider.h 0000644 0000041 0000041 00000005117 13151304741 015275 0 ustar www-data www-data /*
* Copyright 2013 Canonical Ltd.
*
* Authors:
* Charles Kerr
*
* 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 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 .
*/
#ifndef __INDICATOR_POWER_DEVICE_PROVIDER__H__
#define __INDICATOR_POWER_DEVICE_PROVIDER__H__
#include
G_BEGIN_DECLS
#define INDICATOR_TYPE_POWER_DEVICE_PROVIDER \
(indicator_power_device_provider_get_type ())
#define INDICATOR_POWER_DEVICE_PROVIDER(obj) \
(G_TYPE_CHECK_INSTANCE_CAST ((obj), \
INDICATOR_TYPE_POWER_DEVICE_PROVIDER, \
IndicatorPowerDeviceProvider))
#define INDICATOR_IS_POWER_DEVICE_PROVIDER(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE ((obj), INDICATOR_TYPE_POWER_DEVICE_PROVIDER))
#define INDICATOR_POWER_DEVICE_PROVIDER_GET_INTERFACE(inst) \
(G_TYPE_INSTANCE_GET_INTERFACE ((inst), \
INDICATOR_TYPE_POWER_DEVICE_PROVIDER, \
IndicatorPowerDeviceProviderInterface))
typedef struct _IndicatorPowerDeviceProvider
IndicatorPowerDeviceProvider;
typedef struct _IndicatorPowerDeviceProviderInterface
IndicatorPowerDeviceProviderInterface;
/**
* An interface class for an object that provides IndicatorPowerDevices.
*
* Example uses:
* - in unit tests, a mock that feeds fake devices to the service
* - in production, an implementation that monitors upower
* - in the future, upower can be replaced by changing providers
*/
struct _IndicatorPowerDeviceProviderInterface
{
GTypeInterface parent_iface;
/* signals */
void (*devices_changed) (IndicatorPowerDeviceProvider * self);
/* virtual functions */
GList* (*get_devices) (IndicatorPowerDeviceProvider * self);
};
GType indicator_power_device_provider_get_type (void);
/***
****
***/
GList * indicator_power_device_provider_get_devices (IndicatorPowerDeviceProvider * self);
void indicator_power_device_provider_emit_devices_changed (IndicatorPowerDeviceProvider * self);
G_END_DECLS
#endif /* __INDICATOR_POWER_DEVICE_PROVIDER__H__ */
./src/datafiles.h 0000644 0000041 0000041 00000001761 13151304741 014143 0 ustar www-data www-data /*
* Copyright 2016 Canonical Ltd.
*
* 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 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 .
*
* Authors:
* Charles Kerr
*/
#ifndef __INDICATOR_POWER_DATAFILES_H__
#define __INDICATOR_POWER_DATAFILES_H__
#include
G_BEGIN_DECLS
typedef enum
{
DATAFILE_TYPE_SOUND
}
DatafileType;
gchar* datafile_find(DatafileType type, const char * basename);
G_END_DECLS
#endif /* __INDICATOR_POWER_DATAFILES_H__ */
./cmake/ 0000755 0000041 0000041 00000000000 13151304741 012322 5 ustar www-data www-data ./cmake/UseGSettings.cmake 0000644 0000041 0000041 00000002102 13151304741 015703 0 ustar www-data www-data # GSettings.cmake, CMake macros written for Marlin, feel free to re-use them.
macro(add_schema SCHEMA_NAME)
set(PKG_CONFIG_EXECUTABLE pkg-config)
set(GSETTINGS_DIR "${CMAKE_INSTALL_FULL_DATAROOTDIR}/glib-2.0/schemas")
# Run the validator and error if it fails
execute_process (COMMAND ${PKG_CONFIG_EXECUTABLE} gio-2.0 --variable glib_compile_schemas OUTPUT_VARIABLE _glib_compile_schemas OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process (COMMAND ${_glib_compile_schemas} --dry-run --schema-file=${SCHEMA_NAME} ERROR_VARIABLE _schemas_invalid OUTPUT_STRIP_TRAILING_WHITESPACE)
if (_schemas_invalid)
message (SEND_ERROR "Schema validation error: ${_schemas_invalid}")
endif (_schemas_invalid)
# Actually install and recomple schemas
message (STATUS "${GSETTINGS_DIR} is the GSettings install dir")
install (FILES ${SCHEMA_NAME} DESTINATION ${GSETTINGS_DIR} OPTIONAL)
install (CODE "message (STATUS \"Compiling GSettings schemas\")")
install (CODE "execute_process (COMMAND ${_glib_compile_schemas} ${GSETTINGS_DIR})")
endmacro()
./cmake/GdbusCodegen.cmake 0000644 0000041 0000041 00000002465 13151304741 015664 0 ustar www-data www-data cmake_minimum_required(VERSION 2.6)
if(POLICY CMP0011)
cmake_policy(SET CMP0011 NEW)
endif(POLICY CMP0011)
find_program(GDBUS_CODEGEN NAMES gdbus-codegen DOC "gdbus-codegen executable")
if(NOT GDBUS_CODEGEN)
message(FATAL_ERROR "Excutable gdbus-codegen not found")
endif()
macro(add_gdbus_codegen outfiles name prefix service_xml)
add_custom_command(
OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${name}.h" "${CMAKE_CURRENT_BINARY_DIR}/${name}.c"
COMMAND "${GDBUS_CODEGEN}"
--interface-prefix "${prefix}"
--generate-c-code "${name}"
"${service_xml}"
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${ARGN} "${service_xml}"
)
list(APPEND ${outfiles} "${CMAKE_CURRENT_BINARY_DIR}/${name}.c")
endmacro(add_gdbus_codegen)
macro(add_gdbus_codegen_with_namespace outfiles name prefix namespace service_xml)
add_custom_command(
OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${name}.h" "${CMAKE_CURRENT_BINARY_DIR}/${name}.c"
COMMAND "${GDBUS_CODEGEN}"
--interface-prefix "${prefix}"
--generate-c-code "${name}"
--c-namespace "${namespace}"
"${service_xml}"
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${ARGN} "${service_xml}"
)
list(APPEND ${outfiles} "${CMAKE_CURRENT_BINARY_DIR}/${name}.c")
endmacro(add_gdbus_codegen_with_namespace)
./MERGE-REVIEW 0000644 0000041 0000041 00000001412 13151304741 013021 0 ustar www-data www-data
This documents the expections that the project has on what both submitters
and reviewers should ensure that they've done for a merge into the project.
== Submitter Responsibilities ==
* Ensure the project compiles and the test suite executes without error
* Ensure that non-obvious code has comments explaining it
* If the change works on specific profiles, please include those in the merge description.
== Reviewer Responsibilities ==
* Did the Jenkins build compile? Pass? Run unit tests successfully?
* Are there appropriate tests to cover any new functionality?
* If the description says this effects the phone profile:
* Run tests indicator-power/unity8*
* If the description says this effects the desktop profile:
* Run tests indicator-power/unity7*
./tests/ 0000755 0000041 0000041 00000000000 13151304741 012404 5 ustar www-data www-data ./tests/CMakeLists.txt 0000644 0000041 0000041 00000004656 13151304741 015157 0 ustar www-data www-data find_package(GMock)
include_directories(${GMOCK_INCLUDE_DIRS})
# dbustest
pkg_check_modules(DBUSTEST REQUIRED
dbustest-1>=14.04.0)
include_directories (SYSTEM ${DBUSTEST_INCLUDE_DIRS})
# add warnings
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 ${C_WARNING_ARGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-weak-vtables -Wno-global-constructors") # Google Test
# build the necessary schemas
set_directory_properties (PROPERTIES
ADDITIONAL_MAKE_CLEAN_FILES gschemas.compiled)
set_source_files_properties (gschemas.compiled GENERATED)
# make a XDG_DATA_HOME for sounds/
set(XDG_DATA_HOME "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_DATADIR}")
add_definitions(-DXDG_DATA_HOME="${XDG_DATA_HOME}")
file(COPY "${CMAKE_SOURCE_DIR}/data/sounds" DESTINATION "${XDG_DATA_HOME}/${CMAKE_PROJECT_NAME}")
# GSettings:
# compile the indicator-power schema into a gschemas.compiled file in this directory,
# and help the tests to find that file by setting -DSCHEMA_DIR
set (SCHEMA_DIR ${CMAKE_CURRENT_BINARY_DIR})
add_definitions(-DSCHEMA_DIR="${SCHEMA_DIR}")
execute_process (COMMAND ${PKG_CONFIG_EXECUTABLE} gio-2.0 --variable glib_compile_schemas
OUTPUT_VARIABLE COMPILE_SCHEMA_EXECUTABLE
OUTPUT_STRIP_TRAILING_WHITESPACE)
add_custom_command (OUTPUT gschemas.compiled
DEPENDS ${CMAKE_BINARY_DIR}/data/com.canonical.indicator.power.gschema.xml
COMMAND cp -f ${CMAKE_BINARY_DIR}/data/*gschema.xml ${SCHEMA_DIR}
COMMAND ${COMPILE_SCHEMA_EXECUTABLE} ${SCHEMA_DIR})
# look for headers in our src dir, and also in the directories where we autogenerate files...
include_directories (${CMAKE_SOURCE_DIR}/src)
include_directories (${CMAKE_BINARY_DIR}/src)
include_directories (${CMAKE_CURRENT_BINARY_DIR})
###
###
function(add_test_by_name name)
set (TEST_NAME ${name})
set (COVERAGE_TEST_TARGETS ${COVERAGE_TEST_TARGETS} ${TEST_NAME} PARENT_SCOPE)
add_executable (${TEST_NAME} ${TEST_NAME}.cc gschemas.compiled)
add_test (${TEST_NAME} ${TEST_NAME})
add_dependencies (${TEST_NAME} ${SERVICE_LIB})
target_link_libraries (${TEST_NAME} ${SERVICE_LIB} ${DBUSTEST_LIBRARIES} ${SERVICE_DEPS_LIBRARIES} ${GMOCK_LIBRARIES})
endfunction()
add_test_by_name(test-notify)
add_test(NAME dear-reader-the-next-test-takes-80-seconds COMMAND true)
add_test_by_name(test-device)
set(COVERAGE_TEST_TARGETS
${COVERAGE_TEST_TARGETS}
PARENT_SCOPE
)
./tests/glib-fixture.h 0000644 0000041 0000041 00000016253 13151304741 015165 0 ustar www-data www-data /*
* Copyright 2013-2016 Canonical Ltd.
*
* Authors:
* Charles Kerr
*
* 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 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 .
*/
#pragma once
#include
#include // std::function
#include