fork youker-assistant(commit:764)
|
@ -0,0 +1 @@
|
|||
Ubuntu Kylin Team <ubuntukylin-members@list.launchpad.net>
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
|
@ -0,0 +1,46 @@
|
|||
youker-assistant
|
||||
================
|
||||
|
||||
Attention
|
||||
=========
|
||||
It supports unity and mate for Ubuntu/Ubuntu Kylin.
|
||||
|
||||
Depends
|
||||
=======
|
||||
debhelper (>= 9),python-dev,python-lxml,python-piston-mini-client,python-xdg,libqt4-dev,pkg-config,python (>= 2.6.6-3~),libglib2.0-dev,libgtop2-dev
|
||||
|
||||
Launchpad
|
||||
=======
|
||||
https://launchpad.net/youker-assistant
|
||||
|
||||
Internationalization
|
||||
=======
|
||||
lupdate youker-assistant.pro
|
||||
linguist youker-assistant_zh_CN.ts
|
||||
lrelease youker-assistant.pro
|
||||
|
||||
Python Internationalization
|
||||
=======
|
||||
xgettext -k_ -o youker-assistant.pot cpuinfo.py
|
||||
youker-assistant.pot:修改charset为utf-8
|
||||
cp youker-assistant.pot youker-assistant.po
|
||||
msgfmt -o youker-assistant.mo youker-assistant.po
|
||||
(sudo cp youker-assistant.mo /usr/share/locale/zh_CN/LC_MESSAGES/)
|
||||
|
||||
|
||||
|
||||
|
||||
FT Version:
|
||||
1)changelog like this:
|
||||
youker-assistant (2.0.7kord) juniper; urgency=low
|
||||
|
||||
2)youker-assistant.dekstop
|
||||
|
||||
3)debian/source/format
|
||||
replace quilt with native
|
||||
|
||||
|
||||
DEBUG:
|
||||
gdb python
|
||||
set args start_sessiondbus.py
|
||||
run
|
|
@ -0,0 +1,18 @@
|
|||
TEMPLATE = aux
|
||||
|
||||
inst1.files += ../backends/youker-assistant-daemon/src/
|
||||
inst1.path = /usr/lib/python2.7/dist-packages/youker-assistant-daemon/
|
||||
inst2.files += ../backends/youker-assistant-daemon/data/beautify/autostart/
|
||||
inst2.path = /var/lib/youker-assistant-daemon/
|
||||
inst3.files += ../backends/youker-assistant-daemon/data/beautify/plymouth/
|
||||
inst3.path = /var/lib/youker-assistant-daemon/
|
||||
inst4.files += ../backends/youker-assistant-daemon/data/beautify/sound-theme/
|
||||
inst4.path = /var/lib/youker-assistant-daemon/
|
||||
inst5.files += ../backends/youker-assistant-daemon/data/ubuntukylin-default-settings.ini
|
||||
inst5.path = /var/lib/youker-assistant-daemon/
|
||||
|
||||
INSTALLS += inst1 \
|
||||
inst2 \
|
||||
inst3 \
|
||||
inst4 \
|
||||
inst5
|
|
@ -0,0 +1,11 @@
|
|||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=GNOME Login Sound
|
||||
Comment=Plays a sound whenever you log in
|
||||
Exec=/usr/bin/canberra-gtk-play --id="desktop-login" --description="GNOME Login"
|
||||
OnlyShowIn=GNOME;Unity;
|
||||
AutostartCondition=GSettings org.gnome.desktop.sound event-sounds
|
||||
X-GNOME-Autostart-Phase=Application
|
||||
X-GNOME-Provides=login-sound
|
||||
X-GNOME-Autostart-enabled=true
|
||||
NoDisplay=false
|
|
@ -0,0 +1,6 @@
|
|||
[Plymouth Theme]
|
||||
Name=ubuntukylin Logo
|
||||
Description=A theme that features a blank background with a logo.
|
||||
ModuleName=script
|
||||
|
||||
[script]
|
|
@ -0,0 +1,44 @@
|
|||
# ubuntukylin-logo.script - boot splash plugin
|
||||
#
|
||||
# Copyright (C) 2009 Canonical Ltd.
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin Ltd.
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2, 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.
|
||||
|
||||
logo.image = Image("customBG.png");
|
||||
|
||||
logo.screen_x = Window.GetWidth();
|
||||
logo.screen_y = Window.GetHeight();
|
||||
logo.image_x = logo.image.GetWidth();
|
||||
logo.image_y = logo.image.GetHeight();
|
||||
|
||||
logo.scale_factor_x = Window.GetWidth() / logo.image.GetWidth();
|
||||
logo.scale_factor_y = Window.GetHeight() / logo.image.GetHeight();
|
||||
|
||||
if(logo.scale_factor_x >= 1 && logo.scale_factor_y >= 1){
|
||||
logo.scale_factor = 1;
|
||||
}
|
||||
else{
|
||||
if(logo.scale_factor_x > logo.scale_factor_y){
|
||||
logo.scale_factor = logo.scale_factor_y;
|
||||
}
|
||||
else{
|
||||
logo.scale_factor = logo.scale_factor_x;
|
||||
}
|
||||
}
|
||||
|
||||
logo.scaled_image = logo.image.Scale(logo.image.GetWidth() * logo.scale_factor,
|
||||
logo.image.GetHeight() * logo.scale_factor);
|
||||
|
||||
logo.sprite = Sprite(logo.scaled_image);
|
||||
|
||||
logo.sprite.SetX(Window.GetWidth() / 2 - logo.scaled_image.GetWidth () / 2);
|
||||
logo.sprite.SetY(Window.GetHeight() / 2 - logo.scaled_image.GetHeight() / 2);
|
||||
logo.sprite.SetZ(-10000);
|
|
@ -0,0 +1 @@
|
|||
This directory is used to store the current system can be used in boot animation
|
After Width: | Height: | Size: 526 KiB |
After Width: | Height: | Size: 509 KiB |
After Width: | Height: | Size: 619 KiB |
After Width: | Height: | Size: 626 KiB |
After Width: | Height: | Size: 306 KiB |
After Width: | Height: | Size: 380 KiB |
After Width: | Height: | Size: 47 KiB |
|
@ -0,0 +1,8 @@
|
|||
[Plymouth Theme]
|
||||
Name=My Theme
|
||||
Description=This theme is a template to build on
|
||||
ModuleName=script
|
||||
|
||||
[script]
|
||||
ImageDir=/lib/plymouth/themes/ubuntukylin-logo
|
||||
ScriptFile=/lib/plymouth/themes/ubuntukylin-logo/ubuntukylin-logo.script
|
|
@ -0,0 +1,218 @@
|
|||
/*
|
||||
* Copyright (C) 2014 National University of Defense Technology(NUDT) & Kylin Ltd.
|
||||
*
|
||||
* Authors:
|
||||
* Zhang Chao zhangchao@ubuntukylin.com
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
//背景
|
||||
|
||||
Window.SetBackgroundTopColor (0, 0, 0);
|
||||
Window.SetBackgroundBottomColor (0, 0, 0);
|
||||
//
|
||||
left_1_image = Image("left_1.png");
|
||||
resized_left_1_image = left_1_image.Scale(Window.GetWidth(), Window.GetWidth()*left_1_image.GetHeight()/left_1_image.GetWidth());
|
||||
left_1_sprite = Sprite();
|
||||
left_1_sprite.SetImage(resized_left_1_image);
|
||||
left_1_sprite.SetX(0);
|
||||
left_1_sprite.SetY(Window.GetHeight() / 2 - resized_left_1_image.GetHeight() / 2);
|
||||
left_1_sprite.SetZ(98);
|
||||
left_1_sprite.SetOpacity(0);
|
||||
|
||||
left_2_image = Image("left_2.png");
|
||||
resized_left_2_image = left_2_image.Scale(Window.GetWidth(), Window.GetWidth()*left_2_image.GetHeight()/left_2_image.GetWidth());
|
||||
left_2_sprite = Sprite();
|
||||
left_2_sprite.SetImage(resized_left_2_image);
|
||||
left_2_sprite.SetX(0);
|
||||
left_2_sprite.SetY(Window.GetHeight() / 2 - resized_left_2_image.GetHeight() / 2);
|
||||
left_2_sprite.SetZ(98);
|
||||
left_2_sprite.SetOpacity(1);
|
||||
|
||||
xx_h=resized_left_1_image.GetHeight()-50;
|
||||
xx_y=Window.GetHeight() / 2 - xx_h / 2;
|
||||
|
||||
xx_w=resized_left_1_image.GetWidth()-200;
|
||||
xx_x=Window.GetWidth() / 2 - xx_w / 2;
|
||||
|
||||
all_1_image = Image("all_1.png");
|
||||
resized_all_1_image = all_1_image.Scale(Window.GetWidth(), Window.GetWidth()*all_1_image.GetHeight()/all_1_image.GetWidth());
|
||||
all_1_sprite = Sprite();
|
||||
all_1_sprite.SetImage(resized_all_1_image);
|
||||
all_1_sprite.SetX(0);
|
||||
all_1_sprite.SetY(Window.GetHeight() / 2 - resized_all_1_image.GetHeight() / 2);
|
||||
all_1_sprite.SetZ(102);
|
||||
all_1_sprite.SetOpacity(0);
|
||||
|
||||
all_2_image = Image("all_2.png");
|
||||
resized_all_2_image = all_2_image.Scale(Window.GetWidth(), Window.GetWidth()*all_2_image.GetHeight()/all_2_image.GetWidth());
|
||||
all_2_sprite = Sprite();
|
||||
all_2_sprite.SetImage(resized_all_2_image);
|
||||
all_2_sprite.SetX(0);
|
||||
all_2_sprite.SetY(Window.GetHeight() / 2 - resized_all_2_image.GetHeight() / 2);
|
||||
all_2_sprite.SetZ(103);
|
||||
all_2_sprite.SetOpacity(0);
|
||||
|
||||
all1_1_image = Image("all1_1.png");
|
||||
resized_all1_1_image = all1_1_image.Scale(Window.GetWidth(), Window.GetWidth()*all1_1_image.GetHeight()/all1_1_image.GetWidth());
|
||||
all1_1_sprite = Sprite();
|
||||
all1_1_sprite.SetImage(resized_all1_1_image);
|
||||
all1_1_sprite.SetX(0);
|
||||
all1_1_sprite.SetY(Window.GetHeight() / 2 - resized_all1_1_image.GetHeight() / 2);
|
||||
all1_1_sprite.SetZ(101);
|
||||
all1_1_sprite.SetOpacity(0);
|
||||
|
||||
all1_2_image = Image("all1_2.png");
|
||||
resized_all1_2_image = all1_2_image.Scale(Window.GetWidth(), Window.GetWidth()*all1_2_image.GetHeight()/all1_2_image.GetWidth());
|
||||
all1_2_sprite = Sprite();
|
||||
all1_2_sprite.SetImage(resized_all1_2_image);
|
||||
all1_2_sprite.SetX(0);
|
||||
all1_2_sprite.SetY(Window.GetHeight() / 2 - resized_all1_2_image.GetHeight() / 2);
|
||||
all1_2_sprite.SetZ(100);
|
||||
all1_2_sprite.SetOpacity(0);
|
||||
//文字
|
||||
text_image = Image("text.png");
|
||||
resized_text_image = text_image.Scale(Window.GetWidth(), Window.GetWidth()*text_image.GetHeight()/text_image.GetWidth());
|
||||
text_sprite = Sprite();
|
||||
text_sprite.SetImage(resized_text_image);
|
||||
text_sprite.SetX(0);
|
||||
text_sprite.SetY(Window.GetHeight() / 2 - resized_text_image.GetHeight() / 2);
|
||||
text_sprite.SetZ(106);
|
||||
text_sprite.SetOpacity(0);
|
||||
|
||||
|
||||
xx_image = Image("xx.png");
|
||||
xx1_image = Image("xx1.png");
|
||||
xx2_image = Image("xx2.png");
|
||||
xx3_image = Image("xx3.png");
|
||||
xxnum=15;
|
||||
for(i=0;i<xxnum;i++){
|
||||
xx_sprite[i]=Sprite(xx_image);
|
||||
xx_sprite[i].SetOpacity(0);
|
||||
xx_sprite[i].SetZ(105);
|
||||
xx1_sprite[i]=Sprite(xx1_image);
|
||||
xx1_sprite[i].SetOpacity(0);
|
||||
xx1_sprite[i].SetZ(105);
|
||||
xx2_sprite[i]=Sprite(xx2_image);
|
||||
xx2_sprite[i].SetOpacity(0);
|
||||
xx2_sprite[i].SetZ(105);
|
||||
xx3_sprite[i]=Sprite(xx3_image);
|
||||
xx3_sprite[i].SetOpacity(0);
|
||||
xx3_sprite[i].SetZ(105);
|
||||
}
|
||||
|
||||
progress = 0;
|
||||
star_progress=0;
|
||||
|
||||
|
||||
|
||||
|
||||
fun refresh_callback ()
|
||||
{
|
||||
# Currently we do nothing here
|
||||
|
||||
if(progress < 157){
|
||||
left_1_sprite.SetOpacity(Math.Sin(progress/50));
|
||||
left_2_sprite.SetOpacity(1-Math.Sin(progress/50));
|
||||
text_sprite.SetOpacity(progress/157);
|
||||
}else{
|
||||
left_1_sprite.SetOpacity(0);
|
||||
left_2_sprite.SetOpacity(0);
|
||||
}
|
||||
if(progress > 50){
|
||||
all1_1_Opacity=(progress-50)%314;
|
||||
all1_1_sprite.SetOpacity(Math.Sin(all1_1_Opacity/100));
|
||||
}
|
||||
if(progress > 127){
|
||||
all1_2_Opacity=progress%78;
|
||||
all1_2_sprite.SetOpacity(Math.Sin(all1_2_Opacity/25));
|
||||
}
|
||||
if(progress > 78){
|
||||
all_1_Opacity=(progress-78)%157;
|
||||
all_1_sprite.SetOpacity(Math.Sin(all_1_Opacity/50));
|
||||
}
|
||||
if(progress > 157){
|
||||
all_2_Opacity=progress%157;
|
||||
all_2_sprite.SetOpacity(Math.Sin(all_2_Opacity/50));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
if(star_progress < 800){
|
||||
if(star_progress%40==0){
|
||||
xx_sprite[star_progress/40].SetX(Math.Int(Math.Random(10)*xx_w+xx_x));
|
||||
xx_sprite[star_progress/40].SetY(Math.Int(Math.Random(10)*xx_h+xx_y));
|
||||
xx1_sprite[star_progress/40].SetX(Math.Int(Math.Random(10)*Window.GetWidth()));
|
||||
xx1_sprite[star_progress/40].SetY(Math.Int(Math.Random(10)*Window.GetHeight()));
|
||||
xx2_sprite[star_progress/40].SetX(Math.Int(Math.Random(10)*Window.GetWidth()));
|
||||
xx2_sprite[star_progress/40].SetY(Math.Int(Math.Random(10)*Window.GetHeight()));
|
||||
xx3_sprite[star_progress/40].SetX(Math.Int(Math.Random(10)*Window.GetWidth()));
|
||||
xx3_sprite[star_progress/40].SetY(Math.Int(Math.Random(10)*Window.GetHeight()));
|
||||
}
|
||||
xx_sprite[Math.Int(star_progress/40)].SetOpacity((progress%40)/40);
|
||||
xx1_sprite[Math.Int(star_progress/40)].SetOpacity((progress%40)/40);
|
||||
xx2_sprite[Math.Int(star_progress/40)].SetOpacity((progress%40)/40);
|
||||
xx3_sprite[Math.Int(star_progress/40)].SetOpacity((progress%40)/40);
|
||||
}else{
|
||||
if(star_progress%80 < 40){
|
||||
xx_sprite[Math.Int(star_progress/80)% 20].SetOpacity(1-(progress%80)/40);
|
||||
xx1_sprite[Math.Int(star_progress/80)% 20].SetOpacity(1-(progress%80)/40);
|
||||
xx2_sprite[Math.Int(star_progress/80)% 20].SetOpacity(1-(progress%80)/40);
|
||||
xx3_sprite[Math.Int(star_progress/80)% 20].SetOpacity(1-(progress%80)/40);
|
||||
}else{
|
||||
if(star_progress%80==40){
|
||||
xx_sprite[Math.Int(star_progress/80)% 20].SetX(Math.Int(Math.Random(10)*xx_w+xx_x));
|
||||
xx_sprite[Math.Int(star_progress/80)% 20].SetY(Math.Int(Math.Random(10)*xx_h+xx_y));
|
||||
xx1_sprite[Math.Int(star_progress/80)% 20].SetX(Math.Int(Math.Random(10)*Window.GetWidth()));
|
||||
xx1_sprite[Math.Int(star_progress/80)% 20].SetY(Math.Int(Math.Random(10)*Window.GetHeight()));
|
||||
xx2_sprite[Math.Int(star_progress/80)% 20].SetX(Math.Int(Math.Random(10)*Window.GetWidth()));
|
||||
xx2_sprite[Math.Int(star_progress/80)% 20].SetY(Math.Int(Math.Random(10)*Window.GetHeight()));
|
||||
xx3_sprite[Math.Int(star_progress/80)% 20].SetX(Math.Int(Math.Random(10)*Window.GetWidth()));
|
||||
xx3_sprite[Math.Int(star_progress/80)% 20].SetY(Math.Int(Math.Random(10)*Window.GetHeight()));
|
||||
}
|
||||
xx_sprite[Math.Int(star_progress/80)% 20].SetOpacity((progress%80)/40);
|
||||
xx1_sprite[Math.Int(star_progress/80)% 20].SetOpacity((progress%80)/40);
|
||||
xx2_sprite[Math.Int(star_progress/80)% 20].SetOpacity((progress%80)/40);
|
||||
xx3_sprite[Math.Int(star_progress/80)% 20].SetOpacity((progress%80)/40);
|
||||
}
|
||||
}
|
||||
progress+=2;
|
||||
star_progress+=20;
|
||||
|
||||
}
|
||||
|
||||
|
||||
Plymouth.SetRefreshFunction (refresh_callback);
|
||||
|
||||
|
||||
|
||||
#----------------------------------------- Progress Bar --------------------------------
|
||||
|
||||
|
||||
fun progress_callback (duration, progress)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
Plymouth.SetBootProgressFunction(progress_callback);
|
||||
|
||||
#----------------------------------------- Quit --------------------------------
|
||||
|
||||
fun quit_callback ()
|
||||
{
|
||||
}
|
||||
|
||||
Plymouth.SetQuitFunction(quit_callback);
|
||||
|
||||
|
After Width: | Height: | Size: 18 KiB |
After Width: | Height: | Size: 18 KiB |
After Width: | Height: | Size: 18 KiB |
After Width: | Height: | Size: 149 B |
|
@ -0,0 +1 @@
|
|||
This directory is used to back up the system sound theme
|
|
@ -0,0 +1,71 @@
|
|||
[font]
|
||||
font-name=Ubuntu 11
|
||||
font=Ubuntu 11
|
||||
monospace-font-name=Ubuntu Mono 13
|
||||
document-font-name=Sans 11
|
||||
titlebar-font=Ubuntu Bold 11
|
||||
text-scaling-factor=1
|
||||
hinting=slight
|
||||
antialiasing=rgba
|
||||
|
||||
[icon]
|
||||
icon-theme=ubuntukylin-icon-theme
|
||||
show-desktop-icons=1
|
||||
home-icon-visible=1
|
||||
network-icon-visible=0
|
||||
trash-icon-visible=1
|
||||
volumes-visible=1
|
||||
|
||||
[cinnamon-icon]
|
||||
show-desktop-icons=1
|
||||
computer-icon-visible=1
|
||||
home-icon-visible=1
|
||||
network-icon-visible=0
|
||||
trash-icon-visible=0
|
||||
volumes-visible=1
|
||||
|
||||
[file]
|
||||
always-use-location-entry=0
|
||||
automount=1
|
||||
automount-open=1
|
||||
autorun-never=0
|
||||
thumbnail-size=64
|
||||
maximum-age=180
|
||||
maximum-size=512
|
||||
|
||||
[unity]
|
||||
icon-size=48
|
||||
launcher-hide-mode=0
|
||||
launcher-opacity=0.2
|
||||
backlight-mode=only run app
|
||||
dash-blur-experimental=2
|
||||
panel-opacity=0.2
|
||||
|
||||
[mouse]
|
||||
cursor-theme=DMZ-White
|
||||
cursor-size=24
|
||||
|
||||
[touchpad]
|
||||
touchpad-enabled=1
|
||||
horiz-scroll-enabled=1
|
||||
scrollbar-mode=overlay-auto
|
||||
scroll-method=two-finger-scrolling
|
||||
|
||||
[window]
|
||||
button-layout=close-minimize-maximize:
|
||||
menus-have-icons=0
|
||||
mouse-wheel-action=none
|
||||
action-double-click-titlebar=toggle-maximize
|
||||
action-middle-click-titlebar=lower
|
||||
action-right-click-titlebar=menu
|
||||
|
||||
[datetime]
|
||||
time-format=locale-default
|
||||
show-seconds=0
|
||||
show-day=0
|
||||
show-date=0
|
||||
|
||||
[power]
|
||||
icon-policy=present
|
||||
show-percentage=0
|
||||
show-time=0
|
|
@ -0,0 +1,3 @@
|
|||
[D-BUS Service]
|
||||
Name=com.ubuntukylin.session
|
||||
Exec=/usr/bin/youker-assistant-session.py
|
|
@ -0,0 +1,21 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?> <!-- -*- XML -*- -->
|
||||
|
||||
<!DOCTYPE busconfig PUBLIC
|
||||
"-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<!-- Only root can own the service -->
|
||||
<policy user="root">
|
||||
<allow own="com.ubuntukylin.youker"/>
|
||||
<allow send_interface="com.ubuntukylin.youker"/>
|
||||
</policy>
|
||||
|
||||
<!-- Allow anyone to invoke methods on the interfaces -->
|
||||
<policy context="default">
|
||||
<allow send_interface="com.ubuntukylin.youker"/>
|
||||
<allow send_destination="com.ubuntukylin.youker"
|
||||
send_interface="org.freedesktop.DBus.Introspectable"/>
|
||||
<allow send_destination="com.ubuntukylin.youker"
|
||||
send_interface="org.freedesktop.DBus.Properties"/>
|
||||
</policy>
|
||||
</busconfig>
|
|
@ -0,0 +1,25 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE policyconfig PUBLIC
|
||||
"-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/PolicyKit/1.0/policyconfig.dtd">
|
||||
<policyconfig>
|
||||
|
||||
<vendor>Youker Assistant</vendor>
|
||||
<vendor_url>http://ubuntukylin.com</vendor_url>
|
||||
<icon_name>youker-assistant</icon_name>
|
||||
|
||||
<action id="com.ubuntukylin.youker.action">
|
||||
<_description>
|
||||
system level settings
|
||||
</_description>
|
||||
<_message>
|
||||
To Change the settings, you need to authenticate.
|
||||
</_message>
|
||||
<defaults>
|
||||
<allow_any>auth_admin</allow_any>
|
||||
<allow_inactive>auth_admin</allow_inactive>
|
||||
<allow_active>auth_admin</allow_active>
|
||||
</defaults>
|
||||
</action>
|
||||
|
||||
</policyconfig>
|
|
@ -0,0 +1,4 @@
|
|||
[D-BUS Service]
|
||||
Name=com.ubuntukylin.youker
|
||||
Exec=/usr/bin/youker-assistant-backend.py
|
||||
User=root
|
|
@ -0,0 +1 @@
|
|||
#!/usr/bin/python
|
|
@ -0,0 +1 @@
|
|||
#!/usr/bin/python
|
|
@ -0,0 +1,130 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import psutil
|
||||
import time
|
||||
import subprocess
|
||||
|
||||
class MonitorBall:
|
||||
|
||||
# clean up memory
|
||||
def cleanup_memory(self):
|
||||
'''force changed to disk, update the super block'''
|
||||
pone = subprocess.Popen(["sync"], shell=True)
|
||||
pone.wait()
|
||||
|
||||
'''drop pagecache, dentries and inodes to free the memory'''
|
||||
ptwo = subprocess.Popen(["echo 3 > /proc/sys/vm/drop_caches"], shell=True)
|
||||
ptwo.wait()
|
||||
|
||||
# get cpu percent
|
||||
def get_cpu_percent(self, percpu = False):
|
||||
return psutil.cpu_percent(0.1, percpu)
|
||||
|
||||
# get total memory + cache
|
||||
def get_total_cmemory(self, symbol = "m"):
|
||||
mem = psutil.phymem_usage()
|
||||
value = mem.total
|
||||
return self.bytes2human(value, symbol)
|
||||
|
||||
# get used memory + cache
|
||||
def get_used_cmemory(self, symbol = "m"):
|
||||
mem = psutil.phymem_usage()
|
||||
value = mem.used
|
||||
return self.bytes2human(value, symbol)
|
||||
|
||||
# get free memory + cache
|
||||
def get_free_cmemory(self, symbol = "m"):
|
||||
mem = psutil.phymem_usage()
|
||||
value = mem.free
|
||||
return self.bytes2human(value, symbol)
|
||||
|
||||
# get total memory
|
||||
def get_total_memory(self, symbol = "m"):
|
||||
baseData = psutil.virtual_memory()
|
||||
value = baseData.total
|
||||
return self.bytes2human(value, symbol)
|
||||
|
||||
# get used memory
|
||||
def get_used_memory(self, symbol = "m"):
|
||||
baseData = psutil.virtual_memory()
|
||||
value = baseData.total - baseData.available
|
||||
return self.bytes2human(value, symbol)
|
||||
|
||||
# get free memory
|
||||
def get_free_memory(self, symbol = "m"):
|
||||
baseData = psutil.virtual_memory()
|
||||
value = baseData.available
|
||||
return self.bytes2human(value, symbol)
|
||||
|
||||
# get memory used percent
|
||||
def get_memory_percent(self):
|
||||
baseData = psutil.virtual_memory()
|
||||
return baseData.percent
|
||||
|
||||
# get network total flow, return (up, down)
|
||||
def get_network_flow_total(self, symbol = "k"):
|
||||
network = psutil.network_io_counters()
|
||||
sent = network.bytes_sent
|
||||
recv = network.bytes_recv
|
||||
|
||||
if(symbol == "b"):
|
||||
return (sent, recv)
|
||||
elif(symbol == "k"):
|
||||
k_up = float(sent) / 1024
|
||||
ups = str(k_up)
|
||||
ups = ups[0:ups.find(".") + 2]
|
||||
|
||||
k_down = float(recv) / 1024
|
||||
downs = str(k_down)
|
||||
downs = downs[0:downs.find(".") + 2]
|
||||
|
||||
return (ups, downs)
|
||||
else:
|
||||
return None
|
||||
|
||||
# byte to human by symbol
|
||||
def bytes2human(self, value, symbol):
|
||||
if symbol == "k":
|
||||
value = value / 1024
|
||||
elif symbol == "m":
|
||||
value = value / 1024 / 1024
|
||||
elif symbol == "g":
|
||||
valuef = float(value) / 1024 / 1024 / 1024
|
||||
values = str(valuef)
|
||||
value = values[0:values.find(".") + 2]
|
||||
else:
|
||||
pass
|
||||
return str(value)
|
||||
|
||||
if __name__ == "__main__":
|
||||
mmm = MonitorBall()
|
||||
# print mmm.get_network_flow_total()
|
||||
# print mmm.get_network_flow_total("b")
|
||||
# mmm.cleanup_memory()
|
||||
# print mmm.get_cpu_percent()
|
||||
# print mmm.get_cpu_percent(True)
|
||||
# print mmm.get_cpu_percent()
|
||||
# print mmm.get_free_memory("m")
|
||||
# print mmm.get_used_memory("g")
|
||||
# print mmm.get_total_memory("g")
|
||||
# mmm.ttestt()
|
||||
print mmm.get_memory_percent()
|
||||
print mmm.get_total_memory()
|
||||
print mmm.get_used_memory()
|
||||
print mmm.get_free_memory()
|
|
@ -0,0 +1 @@
|
|||
#!/usr/bin/env python
|
|
@ -0,0 +1,378 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
|
||||
import os
|
||||
import ConfigParser
|
||||
import copy
|
||||
import shutil
|
||||
from pprint import pprint
|
||||
import locale
|
||||
|
||||
SECTION = 'Desktop Entry'
|
||||
OPTION_H = 'Hidden'
|
||||
OPTION_N = 'NoDisplay'
|
||||
OPTION_O = 'OnlyShowIn'
|
||||
OPTION_NOT = 'NotShowIn'
|
||||
OPTION_X = 'X-GNOME-Autostart-enabled'
|
||||
|
||||
class MyConfigParser(ConfigParser.ConfigParser):
|
||||
|
||||
def __inin__(self, defaults=None):
|
||||
ConfigParser.ConfigParser.__init__(self, defaults=None)
|
||||
|
||||
def optionxform(self, optionstr):
|
||||
return optionstr
|
||||
|
||||
class Desktop_Autostart_Manage():
|
||||
|
||||
def __init__(self):
|
||||
self.dic = {}
|
||||
|
||||
def function(self, filename):
|
||||
#config = ConfigParser.ConfigParser()
|
||||
config = MyConfigParser()
|
||||
config.read(filename)
|
||||
|
||||
#flag = ''
|
||||
current_desktop_env = self.get_desktop_env()
|
||||
all_sections = config.sections()
|
||||
|
||||
if SECTION in all_sections:
|
||||
all_options = config.options(SECTION)
|
||||
#pprint(all_options)
|
||||
if OPTION_H in all_options and config.getboolean(SECTION, OPTION_H):
|
||||
self.dic.setdefault(OPTION_H, []).append(filename)
|
||||
#else:
|
||||
#temp_h = '-' + OPTION_H
|
||||
#self.dic.setdefault(temp_h, []).append(filename)
|
||||
else:
|
||||
if OPTION_N in all_options and config.getboolean(SECTION, OPTION_N):
|
||||
self.dic.setdefault(OPTION_N, []).append(filename)
|
||||
else:
|
||||
#OPTION_O in all_options or OPTION_NOT in all_options or OPTION_X in all_options:
|
||||
if (OPTION_O in all_options and current_desktop_env not in config.get(SECTION, OPTION_O)) or (OPTION_NOT in all_options and current_desktop_env in config.get(SECTION, OPTION_NOT)):
|
||||
self.dic.setdefault('*showin', []).append(filename)
|
||||
elif OPTION_X in all_options and not config.getboolean(SECTION, OPTION_X):
|
||||
self.dic.setdefault('notautostart', []).append(filename)
|
||||
else:
|
||||
self.dic.setdefault('autostart', []).append(filename)
|
||||
|
||||
#return flag
|
||||
|
||||
def get_desktop_env(self):
|
||||
desktop_name = os.getenv('XDG_CURRENT_DESKTOP')
|
||||
if desktop_name is None:
|
||||
desktop_name = os.getenv('XDG_SESSION_DESKTOP')
|
||||
return desktop_name
|
||||
|
||||
def _walk_dir(self, sdir):
|
||||
scan_files = []
|
||||
for root, dirs, files in os.walk(sdir):
|
||||
for name in files:
|
||||
absolute_path = os.path.join(root, name)
|
||||
if absolute_path.endswith('desktop'):
|
||||
scan_files.append(absolute_path)
|
||||
return scan_files
|
||||
|
||||
def get_autostart_dirs(self):
|
||||
dirs = []
|
||||
dirs_home = ''
|
||||
dirs_dirs = ''
|
||||
|
||||
dirs_home = os.getenv('XDG_CONFIG_HOME')
|
||||
#pprint(dirs_dirs)
|
||||
if dirs_home:
|
||||
temp1 = [j for j in dirs_home.split(":") if os.path.exists(j)]
|
||||
dirs.extend(temp1)
|
||||
|
||||
dirs_dirs = os.getenv('XDG_CONFIG_DIRS')
|
||||
#pprint(dirs_dirs)
|
||||
if dirs_dirs:
|
||||
temp2 = [i for i in dirs_dirs.split(":") if os.path.exists(i)]
|
||||
dirs.extend(temp2)
|
||||
|
||||
return dirs
|
||||
|
||||
def check_dic(self, filename):
|
||||
name = filename.split("/")[-1]
|
||||
if name in [s.split("/")[-1] for s in self.dic.get(OPTION_H, ['']) if s]:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
|
||||
def init_dic(self):
|
||||
dirs = self.get_autostart_dirs()
|
||||
|
||||
for one in dirs:
|
||||
x = self._walk_dir(one)
|
||||
for value in x:
|
||||
if self.check_dic(value):
|
||||
continue
|
||||
self.function(value)
|
||||
#pprint(self.dic)
|
||||
|
||||
def function_home(self, filename):
|
||||
#config = ConfigParser.ConfigParser()
|
||||
config = MyConfigParser()
|
||||
config.read(filename)
|
||||
|
||||
current_desktop_env = self.get_desktop_env()
|
||||
all_sections = config.sections()
|
||||
if SECTION in all_sections:
|
||||
flag = ''
|
||||
all_options = config.options(SECTION)
|
||||
|
||||
if OPTION_H in all_options and config.getboolean(SECTION, OPTION_H):
|
||||
flag = OPTION_H
|
||||
else:
|
||||
if OPTION_N in all_options and config.getboolean(SECTION, OPTION_N):
|
||||
flag = OPTION_N
|
||||
else:
|
||||
if (OPTION_O in all_options and current_desktop_env not in config.get(SECTION, OPTION_O)) or (OPTION_NOT in all_options and current_desktop_env in config.get(SECTION, OPTION_NOT)):
|
||||
flag = '*showin'
|
||||
elif OPTION_X in all_options and not config.getboolean(SECTION, OPTION_X):
|
||||
flag = 'notautostart'
|
||||
else:
|
||||
flag = 'autostart'
|
||||
return flag
|
||||
|
||||
def get_final_status(self):
|
||||
self.init_dic()
|
||||
|
||||
autostart_home_dir = os.path.expanduser('~/.config/autostart/')
|
||||
|
||||
if os.path.exists(autostart_home_dir):
|
||||
home_desktop_files = self._walk_dir(autostart_home_dir)
|
||||
else:
|
||||
home_desktop_files = []
|
||||
if home_desktop_files:
|
||||
for single in home_desktop_files:
|
||||
status = self.function_home(single)
|
||||
#pprint(status)
|
||||
if status == OPTION_H or status == OPTION_N:
|
||||
autostart_1_list = self.dic.get('autostart', [])
|
||||
if autostart_1_list:
|
||||
new_autostart_list = [d for d in autostart_1_list if not d.count(single.split("/")[-1])]
|
||||
self.dic['autostart'] = new_autostart_list
|
||||
notautostart_1_list = self.dic.get('notautostart', [])
|
||||
if notautostart_1_list:
|
||||
#backup_list = copy.deepcopy(notautostart_list)
|
||||
new_notautostart_list = filter(lambda x: not x.count(single.split("/")[-1]), notautostart_1_list)
|
||||
self.dic['notautostart'] = new_notautostart_list
|
||||
self.dic.setdefault(OPTION_H, []).append(single)
|
||||
|
||||
if status == 'autostart':
|
||||
autostart_2_list = self.dic.get('autostart', [])
|
||||
if autostart_2_list:
|
||||
new_autostart_2_list = [d for d in autostart_2_list if not d.count(single.split("/")[-1])]
|
||||
self.dic['autostart'] = new_autostart_2_list
|
||||
notautostart_2_list = self.dic.get('notautostart', [])
|
||||
if notautostart_2_list:
|
||||
#backup_list = copy.deepcopy(notautostart_list)
|
||||
new_notautostart_2_list = filter(lambda x: not x.count(single.split("/")[-1]), notautostart_2_list)
|
||||
self.dic['notautostart'] = new_notautostart_2_list
|
||||
self.dic.setdefault('autostart', []).append(single)
|
||||
|
||||
if status == 'notautostart':
|
||||
autostart_3_list = self.dic.get('autostart', [])
|
||||
if autostart_3_list:
|
||||
new_autostart_3_list = [d for d in autostart_3_list if not d.count(single.split("/")[-1])]
|
||||
self.dic['autostart'] = new_autostart_3_list
|
||||
notautostart_3_list = self.dic.get('notautostart', [])
|
||||
if notautostart_3_list:
|
||||
#backup_list = copy.deepcopy(notautostart_list)
|
||||
new_notautostart_3_list = filter(lambda x: not x.count(single.split("/")[-1]), notautostart_3_list)
|
||||
self.dic['notautostart'] = new_notautostart_3_list
|
||||
self.dic.setdefault('notautostart', []).append(single)
|
||||
|
||||
else:
|
||||
pass
|
||||
|
||||
#pprint(self.dic)
|
||||
|
||||
def change_single_status(self, filename):
|
||||
#dirs = self.get_autostart_dirs()
|
||||
status = ''
|
||||
new_status = ''
|
||||
hdir = os.path.expanduser('~/.config/autostart/')
|
||||
mdir = '/usr/share/upstart/xdg/autostart/'
|
||||
ldir = '/etc/xdg/autostart/'
|
||||
|
||||
hfilename = hdir + filename
|
||||
mfilename = mdir + filename
|
||||
lfilename = ldir + filename
|
||||
|
||||
if os.path.exists(mfilename):
|
||||
#pprint(mfilename)
|
||||
status = self.function_home(mfilename)
|
||||
#pprint(status)
|
||||
|
||||
if os.path.exists(lfilename):
|
||||
if not status:
|
||||
status = self.function_home(lfilename)
|
||||
else:
|
||||
pass
|
||||
#pprint(status)
|
||||
if os.path.exists(hfilename):
|
||||
new_status = self.function_home(hfilename)
|
||||
#pprint(new_status)
|
||||
if status == new_status:
|
||||
#change
|
||||
if new_status == 'autostart':
|
||||
#pprint("change false")
|
||||
self.change_option_x(hfilename, 'false')
|
||||
elif new_status == 'notautostart':
|
||||
#pprint("change true")
|
||||
self.change_option_x(hfilename, 'true')
|
||||
else:
|
||||
#remove
|
||||
#pprint("remove")
|
||||
os.remove(hfilename)
|
||||
|
||||
else:
|
||||
#touch
|
||||
if not os.path.exists(hdir):
|
||||
os.makedirs(hdir)
|
||||
#pprint("copy")
|
||||
shutil.copy(lfilename, hfilename)
|
||||
if status == 'autostart':
|
||||
#pprint("change false")
|
||||
self.change_option_x(hfilename, 'false')
|
||||
elif status == 'notautostart':
|
||||
self.change_option_x(hfilename, 'true')
|
||||
|
||||
|
||||
def change_option_x(self, name, value):
|
||||
#cf = ConfigParser.ConfigParser()
|
||||
cf = MyConfigParser()
|
||||
cf.read(name)
|
||||
|
||||
s = cf.sections()
|
||||
o = cf.options(SECTION)
|
||||
if SECTION in s:
|
||||
#if OPTION_X in o:
|
||||
#if cf.getboolean(SECTION, OPTION_X):
|
||||
#cf.set(SECTION, OPTION_X, 'false')
|
||||
#else:
|
||||
#cf.set(SECTION, OPTION_X, 'true')
|
||||
#else:
|
||||
cf.set(SECTION, OPTION_X, value)
|
||||
cf.write(open(name, "w"))
|
||||
|
||||
def get_desktop_info(self, filepath, locale_language):
|
||||
cf = MyConfigParser()
|
||||
cf.read(filepath)
|
||||
|
||||
info = []
|
||||
iconpath1 = '/usr/share/icons/hicolor/24x24/apps/'
|
||||
iconpath2 = '/usr/share/pixmaps/'
|
||||
s = cf.sections()
|
||||
o = cf.options(SECTION)
|
||||
info.append('Path:' + filepath)
|
||||
|
||||
#
|
||||
if SECTION in s:
|
||||
if locale_language == "zh_CN":
|
||||
if 'Name[zh_CN]' in o:
|
||||
info.append('Name:' + cf.get(SECTION, 'Name[zh_CN]'))
|
||||
else:
|
||||
info.append('Name:' + cf.get(SECTION, 'Name'))
|
||||
|
||||
if 'Comment[zh_CN]' in o:
|
||||
info.append('Comment:' + cf.get(SECTION, 'Comment[zh_CN]'))
|
||||
elif 'Comment' in o:
|
||||
info.append('Comment:' + cf.get(SECTION, 'Comment'))
|
||||
else:
|
||||
info.append('Comment:')
|
||||
else:
|
||||
info.append('Name:' + cf.get(SECTION, 'Name'))
|
||||
if 'Comment' in o:
|
||||
info.append('Comment:' + cf.get(SECTION, 'Comment'))
|
||||
else:
|
||||
info.append('Comment:')
|
||||
|
||||
if 'Icon' in o:
|
||||
tempicon = cf.get(SECTION, 'Icon')
|
||||
if not tempicon.endswith('.png') and not tempicon.endswith('.jpg'):
|
||||
tempicon = tempicon + '.png'
|
||||
if os.path.exists(iconpath2 + tempicon):
|
||||
info.append('Icon:' + iconpath2 + tempicon)
|
||||
elif os.path.exists(iconpath1 + tempicon):
|
||||
info.append('Icon:' + iconpath1 + tempicon)
|
||||
else:
|
||||
info.append('Icon:/usr/share/pixmaps/autostart-default.png')
|
||||
else:
|
||||
info.append('Icon:/usr/share/pixmaps/autostart-default.png')
|
||||
|
||||
return info
|
||||
|
||||
|
||||
def interface_get_status(fobj):
|
||||
locale_language = locale.getdefaultlocale()[0]
|
||||
try:
|
||||
obj = Desktop_Autostart_Manage()
|
||||
obj.get_final_status()
|
||||
up = obj.dic.get("autostart", [])
|
||||
if up:
|
||||
for upvalue in up:
|
||||
up_list = obj.get_desktop_info(upvalue, locale_language)
|
||||
up_list.append('Status:' + 'true')
|
||||
fobj.autostartmanage_data_signal(up_list)
|
||||
|
||||
down = obj.dic.get("notautostart", [])
|
||||
if down:
|
||||
for downvalue in down:
|
||||
down_list = obj.get_desktop_info(downvalue, locale_language)
|
||||
down_list.append('Status:' + 'false')
|
||||
fobj.autostartmanage_data_signal(down_list)
|
||||
|
||||
except Exception, e:
|
||||
fobj.autostartmanage_error_signal(str(e))
|
||||
else:
|
||||
fobj.autostartmanage_status_signal("complete")
|
||||
|
||||
def interface_get_single_status(fobj, path):
|
||||
obj = Desktop_Autostart_Manage()
|
||||
status = obj.function_home(path)
|
||||
if status == "autostart":
|
||||
return True
|
||||
elif status == "notautostart":
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
|
||||
def interface_change_status(fobj, filename):
|
||||
try:
|
||||
obj = Desktop_Autostart_Manage()
|
||||
obj.change_single_status(filename)
|
||||
except Exception, e:
|
||||
fobj.autostartmanage_error_signal(str(e))
|
||||
# else:
|
||||
# fobj.autostartmanage_status_signal("complete")
|
||||
|
||||
if __name__ == "__main__":
|
||||
obj = Desktop_Autostart_Manage()
|
||||
#obj.main()
|
||||
#obj.function_home('/home/ice/.config/autostart/ubuntu-kylin-software-center-autostart.desktop')
|
||||
#obj.get_final_status()
|
||||
#obj.change_single_status('ubuntu-kylin-software-center-autostart.desktop')
|
||||
#interface_get_status()
|
||||
#interface_change_status()
|
|
@ -0,0 +1 @@
|
|||
#!/usr/bin/python
|
|
@ -0,0 +1,518 @@
|
|||
# -*- coding: UTF-8 -*-
|
||||
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
#
|
||||
# Authors: Quinn Storm (quinn@beryl-project.org)
|
||||
# Patrick Niklaus (marex@opencompositing.org)
|
||||
# Guillaume Seguin (guillaume@segu.in)
|
||||
# Christopher Williams (christopherw@verizon.net)
|
||||
# Copyright (C) 2007 Quinn Storm
|
||||
|
||||
from gi.repository import Gtk
|
||||
|
||||
from Constants import *
|
||||
from Utils import *
|
||||
|
||||
import locale
|
||||
import gettext
|
||||
locale.setlocale(locale.LC_ALL, "")
|
||||
gettext.bindtextdomain("ccsm", DataDir + "/locale")
|
||||
gettext.textdomain("ccsm")
|
||||
_ = gettext.gettext
|
||||
|
||||
class Conflict:
|
||||
def __init__(self, autoResolve):
|
||||
self.AutoResolve = autoResolve
|
||||
|
||||
# buttons = (text, type/icon, response_id)
|
||||
def Ask(self, message, buttons, custom_widgets=None):
|
||||
if self.AutoResolve:
|
||||
return Gtk.ResponseType.YES
|
||||
|
||||
dialog = Gtk.MessageDialog(flags=Gtk.DialogFlags.MODAL, type=Gtk.MessageType.WARNING)
|
||||
|
||||
for text, icon, response in buttons:
|
||||
button = Gtk.Button(text)
|
||||
button.set_image(Gtk.Image.new_from_stock(icon, Gtk.IconSize.BUTTON))
|
||||
dialog.add_action_widget(button, response)
|
||||
|
||||
if custom_widgets != None:
|
||||
for widget in custom_widgets:
|
||||
dialog.vbox.pack_start(widget, False, False)
|
||||
|
||||
dialog.set_markup(message)
|
||||
dialog.show_all()
|
||||
answer = dialog.run()
|
||||
dialog.destroy()
|
||||
|
||||
return answer
|
||||
|
||||
class ActionConflict (Conflict):
|
||||
|
||||
ActionTypes = set(('Bell', 'Button', 'Edge', 'Key'))
|
||||
|
||||
def __init__ (self, setting, settings, autoResolve):
|
||||
|
||||
def ExcludeInternal (settings):
|
||||
for setting in settings:
|
||||
if not setting.Info[0]:
|
||||
yield setting
|
||||
|
||||
Conflict.__init__(self, autoResolve)
|
||||
self.Conflicts = []
|
||||
self.Name = ""
|
||||
self.Setting = setting
|
||||
|
||||
if settings is None:
|
||||
settings = []
|
||||
|
||||
self.Settings = settings
|
||||
|
||||
# if the action is internal, include all global actions plus internal
|
||||
# actions from the same plugin. If it is global, include all actions.
|
||||
|
||||
if not settings:
|
||||
for n in self.Setting.Plugin.Context.Plugins:
|
||||
plugin = self.Setting.Plugin.Context.Plugins[n]
|
||||
if plugin.Enabled:
|
||||
pluginActions = GetSettings(plugin, types=self.ActionTypes)
|
||||
|
||||
if len(setting.Info) and setting.Info[0] and plugin is not setting.Plugin:
|
||||
settings.extend(ExcludeInternal(pluginActions))
|
||||
else:
|
||||
settings.extend(pluginActions)
|
||||
|
||||
def Resolve (self, updater = None):
|
||||
if len (self.Conflicts):
|
||||
for setting in self.Conflicts:
|
||||
answer = self.AskUser (self.Setting, setting)
|
||||
if answer == Gtk.ResponseType.YES:
|
||||
setting.Value = 'Disabled'
|
||||
if updater:
|
||||
updater.UpdateSetting (setting)
|
||||
if answer == Gtk.ResponseType.NO:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def AskUser (self, setting, conflict):
|
||||
msg = _("The new value for the %(binding)s binding for the action <b>%(action)s</b> "\
|
||||
"in plugin <b>%(plugin)s</b> conflicts with the action <b>%(action_conflict)s</b> of the <b>%(plugin_conflict)s</b> plugin.\n"\
|
||||
"Do you wish to disable <b>%(action_conflict)s</b> in the <b>%(plugin_conflict)s</b> plugin?")
|
||||
|
||||
msg_dict = {'binding': self.Name,
|
||||
'action': setting.ShortDesc,
|
||||
'plugin': setting.Plugin.ShortDesc,
|
||||
'action_conflict': conflict.ShortDesc,
|
||||
'plugin_conflict': conflict.Plugin.ShortDesc}
|
||||
|
||||
msg = msg % protect_markup_dict (msg_dict)
|
||||
|
||||
yesButton = (_("Disable %(action_conflict)s") % msg_dict, Gtk.STOCK_YES, Gtk.ResponseType.YES)
|
||||
noButton = (_("Don't set %(action)s") % msg_dict, Gtk.STOCK_NO, Gtk.ResponseType.NO)
|
||||
ignoreButton = (_("Set %(action)s anyway") % msg_dict, Gtk.STOCK_STOP, Gtk.ResponseType.REJECT)
|
||||
|
||||
return self.Ask (msg, (ignoreButton, noButton, yesButton))
|
||||
|
||||
class KeyConflict(ActionConflict):
|
||||
def __init__(self, setting, newValue, settings=None, autoResolve=False, ignoreOld=False):
|
||||
ActionConflict.__init__(self, setting, settings, autoResolve)
|
||||
self.Name = _("key")
|
||||
|
||||
if not newValue:
|
||||
return
|
||||
|
||||
newValue = newValue.lower ()
|
||||
oldValue = self.Setting.Value.lower ()
|
||||
badValues = ["disabled", "none"]
|
||||
if not ignoreOld:
|
||||
badValues.append (oldValue)
|
||||
if newValue in badValues:
|
||||
return
|
||||
|
||||
for s in self.Settings:
|
||||
if s is setting:
|
||||
continue
|
||||
if s.Type == 'Key':
|
||||
if s.Value.lower() == newValue:
|
||||
self.Conflicts.append (s)
|
||||
|
||||
class ButtonConflict(ActionConflict):
|
||||
def __init__(self, setting, newValue, settings=None, autoResolve=False, ignoreOld=False):
|
||||
ActionConflict.__init__(self, setting, settings, autoResolve)
|
||||
self.Name = _("button")
|
||||
|
||||
if not newValue:
|
||||
return
|
||||
|
||||
newValue = newValue.lower ()
|
||||
oldValue = self.Setting.Value.lower ()
|
||||
badValues = ["disabled", "none"]
|
||||
if not ignoreOld:
|
||||
badValues.append (oldValue)
|
||||
if newValue in badValues:
|
||||
return
|
||||
|
||||
for s in self.Settings:
|
||||
if s is setting:
|
||||
continue
|
||||
if s.Type == 'Button':
|
||||
if s.Value.lower() == newValue:
|
||||
self.Conflicts.append (s)
|
||||
|
||||
class EdgeConflict(ActionConflict):
|
||||
def __init__(self, setting, newValue, settings=None, autoResolve=False, ignoreOld=False):
|
||||
ActionConflict.__init__(self, setting, settings, autoResolve)
|
||||
self.Name = _("edge")
|
||||
|
||||
if not newValue:
|
||||
return
|
||||
|
||||
newEdges = set(newValue.split("|"))
|
||||
|
||||
if not ignoreOld:
|
||||
oldEdges = set(self.Setting.Value.split("|"))
|
||||
diff = newEdges - oldEdges
|
||||
if diff:
|
||||
newEdges = diff # no need to check edges that were already set
|
||||
else:
|
||||
return
|
||||
|
||||
for s in self.Settings:
|
||||
if s is setting:
|
||||
continue
|
||||
elif s.Type == 'Edge':
|
||||
settingEdges = set(s.Value.split("|"))
|
||||
union = newEdges & settingEdges
|
||||
if union:
|
||||
for edge in union:
|
||||
self.Conflicts.append ((s, edge))
|
||||
break
|
||||
|
||||
def Resolve (self, updater = None):
|
||||
if len (self.Conflicts):
|
||||
for setting, edge in self.Conflicts:
|
||||
answer = self.AskUser (self.Setting, setting)
|
||||
if answer == Gtk.ResponseType.YES:
|
||||
value = setting.Value.split ("|")
|
||||
value.remove (edge)
|
||||
setting.Value = "|".join (value)
|
||||
if updater:
|
||||
updater.UpdateSetting (setting)
|
||||
if answer == Gtk.ResponseType.NO:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
# Not used for plugin dependencies (which are handled by ccs) but own feature checking e.g. image support
|
||||
class FeatureRequirement(Conflict):
|
||||
def __init__(self, context, feature, autoResolve=False):
|
||||
Conflict.__init__(self, autoResolve)
|
||||
self.Requirements = []
|
||||
self.Context = context
|
||||
self.Feature = feature
|
||||
|
||||
self.Found = False
|
||||
for plugin in context.Plugins.values():
|
||||
if feature in plugin.Features:
|
||||
self.Found = True
|
||||
if not plugin.Enabled:
|
||||
self.Requirements.append(plugin)
|
||||
|
||||
def Resolve(self):
|
||||
if len(self.Requirements) == 0 and self.Found:
|
||||
return True
|
||||
elif not self.Found:
|
||||
answer = self.ErrorAskUser()
|
||||
if answer == Gtk.ResponseType.YES:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
for plugin in self.Requirements:
|
||||
answer = self.AskUser(plugin)
|
||||
if answer == Gtk.ResponseType.YES:
|
||||
plugin.Enabled = True
|
||||
self.Context.Write()
|
||||
return True
|
||||
|
||||
def ErrorAskUser(self):
|
||||
msg = _("You are trying to use the feature <b>%(feature)s</b> which is <b>not</b> provided by any plugin.\n"\
|
||||
"Do you wish to use this feature anyway?")
|
||||
|
||||
msg_dict = {'feature': self.Feature}
|
||||
|
||||
msg = msg % protect_markup_dict (msg_dict)
|
||||
|
||||
yesButton = (_("Use %(feature)s") % msg_dict, Gtk.STOCK_YES, Gtk.ResponseType.YES)
|
||||
noButton = (_("Don't use %(feature)s") % msg_dict, Gtk.STOCK_NO, Gtk.ResponseType.NO)
|
||||
|
||||
answer = self.Ask(msg, (noButton, yesButton))
|
||||
|
||||
return answer
|
||||
|
||||
def AskUser(self, plugin):
|
||||
msg = _("You are trying to use the feature <b>%(feature)s</b> which is provided by <b>%(plugin)s</b>.\n"\
|
||||
"This plugin is currently disabled.\n"\
|
||||
"Do you wish to enable <b>%(plugin)s</b> so the feature is available?")
|
||||
|
||||
msg_dict = {'feature': self.Feature,
|
||||
'plugin': plugin.ShortDesc}
|
||||
|
||||
msg = msg % protect_markup_dict (msg_dict)
|
||||
|
||||
yesButton = (_("Enable %(plugin)s") % msg_dict, Gtk.STOCK_YES, Gtk.ResponseType.YES)
|
||||
noButton = (_("Don't enable %(feature)s") % msg_dict, Gtk.STOCK_NO, Gtk.ResponseType.NO)
|
||||
|
||||
answer = self.Ask(msg, (noButton, yesButton))
|
||||
|
||||
return answer
|
||||
|
||||
class PluginConflict(Conflict):
|
||||
def __init__(self, plugin, conflicts, autoResolve=False):
|
||||
Conflict.__init__(self, autoResolve)
|
||||
self.Conflicts = conflicts
|
||||
self.Plugin = plugin
|
||||
|
||||
def Resolve(self):
|
||||
for conflict in self.Conflicts:
|
||||
if conflict[0] == 'ConflictFeature':
|
||||
answer = self.AskUser(self.Plugin, conflict)
|
||||
if answer == Gtk.ResponseType.YES:
|
||||
disableConflicts = conflict[2][0].DisableConflicts
|
||||
con = PluginConflict(conflict[2][0], disableConflicts,
|
||||
self.AutoResolve)
|
||||
if con.Resolve():
|
||||
conflict[2][0].Enabled = False
|
||||
else:
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
|
||||
elif conflict[0] == 'ConflictPlugin':
|
||||
answer = self.AskUser(self.Plugin, conflict)
|
||||
if answer == Gtk.ResponseType.YES:
|
||||
disableConflicts = conflict[2][0].DisableConflicts
|
||||
con = PluginConflict(conflict[2][0], disableConflicts,
|
||||
self.AutoResolve)
|
||||
if con.Resolve():
|
||||
conflict[2][0].Enabled = False
|
||||
else:
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
|
||||
elif conflict[0] == 'RequiresFeature':
|
||||
answer, choice = self.AskUser(self.Plugin, conflict)
|
||||
if answer == Gtk.ResponseType.YES:
|
||||
for plg in conflict[2]:
|
||||
if plg.ShortDesc == choice:
|
||||
enableConflicts = plg.EnableConflicts
|
||||
con = PluginConflict(plg, enableConflicts,
|
||||
self.AutoResolve)
|
||||
if con.Resolve():
|
||||
plg.Enabled = True
|
||||
else:
|
||||
return False
|
||||
break
|
||||
else:
|
||||
return False
|
||||
|
||||
elif conflict[0] == 'RequiresPlugin':
|
||||
answer = self.AskUser(self.Plugin, conflict)
|
||||
if answer == Gtk.ResponseType.YES:
|
||||
enableConflicts = conflict[2][0].EnableConflicts
|
||||
con = PluginConflict(conflict[2][0], enableConflicts,
|
||||
self.AutoResolve)
|
||||
if con.Resolve():
|
||||
conflict[2][0].Enabled = True
|
||||
else:
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
|
||||
elif conflict[0] == 'FeatureNeeded':
|
||||
answer = self.AskUser(self.Plugin, conflict)
|
||||
if answer == Gtk.ResponseType.YES:
|
||||
for plg in conflict[2]:
|
||||
disableConflicts = plg.DisableConflicts
|
||||
con = PluginConflict(plg, disableConflicts,
|
||||
self.AutoResolve)
|
||||
if con.Resolve():
|
||||
plg.Enabled = False
|
||||
else:
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
|
||||
elif conflict[0] == 'PluginNeeded':
|
||||
answer = self.AskUser(self.Plugin, conflict)
|
||||
if answer == Gtk.ResponseType.YES:
|
||||
for plg in conflict[2]:
|
||||
disableConflicts = plg.DisableConflicts
|
||||
con = PluginConflict(plg, disableConflicts,
|
||||
self.AutoResolve)
|
||||
if con.Resolve():
|
||||
plg.Enabled = False
|
||||
else:
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
|
||||
# Only when enabling a plugin
|
||||
types = []
|
||||
actionConflicts = []
|
||||
if not self.Plugin.Enabled and not self.AutoResolve:
|
||||
for setting in GetSettings(self.Plugin):
|
||||
conflict = None
|
||||
if setting.Type == 'Key':
|
||||
conflict = KeyConflict(setting, setting.Value, ignoreOld=True)
|
||||
elif setting.Type == 'Button':
|
||||
conflict = ButtonConflict(setting, setting.Value, ignoreOld=True)
|
||||
elif setting.Type == 'Edge':
|
||||
conflict = EdgeConflict(setting, setting.Value, ignoreOld=True)
|
||||
|
||||
# Conflicts were found
|
||||
if conflict and conflict.Conflicts:
|
||||
name = conflict.Name
|
||||
if name not in types:
|
||||
types.append(name)
|
||||
actionConflicts.append(conflict)
|
||||
|
||||
if actionConflicts:
|
||||
answer = self.AskUser(self.Plugin, ('ConflictAction', types))
|
||||
if answer == Gtk.ResponseType.YES:
|
||||
for conflict in actionConflicts:
|
||||
conflict.Resolve()
|
||||
|
||||
return True
|
||||
|
||||
def AskUser(self, plugin, conflict):
|
||||
msg = ""
|
||||
okMsg = ""
|
||||
cancelMsg = ""
|
||||
widgets = []
|
||||
|
||||
# CCSM custom conflict
|
||||
if conflict[0] == 'ConflictAction':
|
||||
msg = _("Some %(bindings)s bindings of Plugin <b>%(plugin)s</b> " \
|
||||
"conflict with other plugins. Do you want to resolve " \
|
||||
"these conflicts?")
|
||||
|
||||
types = conflict[1]
|
||||
bindings = ", ".join(types[:-1])
|
||||
if len(types) > 1:
|
||||
bindings = "%s and %s" % (bindings, types[-1])
|
||||
|
||||
msg_dict = {'plugin': plugin.ShortDesc,
|
||||
'bindings': bindings}
|
||||
|
||||
msg = msg % protect_markup_dict (msg_dict)
|
||||
|
||||
okMsg = _("Resolve conflicts") % msg_dict
|
||||
cancelMsg = _("Ignore conflicts") % msg_dict
|
||||
|
||||
elif conflict[0] == 'ConflictFeature':
|
||||
msg = _("Plugin <b>%(plugin_conflict)s</b> provides feature " \
|
||||
"<b>%(feature)s</b> which is also provided by " \
|
||||
"<b>%(plugin)s</b>")
|
||||
|
||||
msg_dict = {'plugin_conflict': conflict[2][0].ShortDesc,
|
||||
'feature': conflict[1],
|
||||
'plugin': plugin.ShortDesc}
|
||||
|
||||
msg = msg % protect_markup_dict (msg_dict)
|
||||
|
||||
okMsg = _("Disable %(plugin_conflict)s") % msg_dict
|
||||
cancelMsg = _("Don't enable %(plugin)s") % msg_dict
|
||||
|
||||
elif conflict[0] == 'ConflictPlugin':
|
||||
msg = _("Plugin <b>%(plugin_conflict)s</b> conflicts with " \
|
||||
"<b>%(plugin)s</b>.")
|
||||
msg = msg % protect_markup_dict (msg_dict)
|
||||
|
||||
okMsg = _("Disable %(plugin_conflict)s") % msg_dict
|
||||
cancelMsg = _("Don't enable %(plugin)s") % msg_dict
|
||||
|
||||
elif conflict[0] == 'RequiresFeature':
|
||||
pluginList = ', '.join("\"%s\"" % plugin.ShortDesc for plugin in conflict[2])
|
||||
msg = _("<b>%(plugin)s</b> requires feature <b>%(feature)s</b> " \
|
||||
"which is provided by the following " \
|
||||
"plugins:\n%(plugin_list)s")
|
||||
|
||||
msg_dict = {'plugin': plugin.ShortDesc,
|
||||
'feature': conflict[1],
|
||||
'plugin_list': pluginList}
|
||||
|
||||
msg = msg % protect_markup_dict (msg_dict)
|
||||
|
||||
cmb = Gtk.ComboBoxText()
|
||||
for plugin in conflict[2]:
|
||||
cmb.append_text(plugin.ShortDesc)
|
||||
cmb.set_active(0)
|
||||
widgets.append(cmb)
|
||||
|
||||
okMsg = _("Enable these plugins")
|
||||
cancelMsg = _("Don't enable %(plugin)s") % msg_dict
|
||||
|
||||
elif conflict[0] == 'RequiresPlugin':
|
||||
msg = _("<b>%(plugin)s</b> requires the plugin <b>%(require)s</b>.")
|
||||
|
||||
msg_dict = {'plugin': plugin.ShortDesc,
|
||||
'require': conflict[2][0].ShortDesc}
|
||||
|
||||
msg = msg % protect_markup_dict (msg_dict)
|
||||
|
||||
okMsg = _("Enable %(require)s") % msg_dict
|
||||
cancelMsg = _("Don't enable %(plugin)s") % msg_dict
|
||||
|
||||
elif conflict[0] == 'FeatureNeeded':
|
||||
pluginList = ', '.join("\"%s\"" % plugin.ShortDesc for plugin in conflict[2])
|
||||
msg = _("<b>%(plugin)s</b> provides the feature " \
|
||||
"<b>%(feature)s</b> which is required by the plugins " \
|
||||
"<b>%(plugin_list)s</b>.")
|
||||
|
||||
msg_dict = {'plugin': plugin.ShortDesc,
|
||||
'feature': conflict[1],
|
||||
'plugin_list': pluginList}
|
||||
|
||||
msg = msg % protect_markup_dict (msg_dict)
|
||||
|
||||
okMsg = _("Disable these plugins")
|
||||
cancelMsg = _("Don't disable %(plugin)s") % msg_dict
|
||||
|
||||
elif conflict[0] == 'PluginNeeded':
|
||||
pluginList = ', '.join("\"%s\"" % plugin.ShortDesc for plugin in conflict[2])
|
||||
msg = _("<b>%(plugin)s</b> is required by the plugins " \
|
||||
"<b>%(plugin_list)s</b>.")
|
||||
|
||||
msg_dict = {'plugin': plugin.ShortDesc,
|
||||
'plugin_list': pluginList}
|
||||
|
||||
msg = msg % protect_markup_dict (msg_dict)
|
||||
|
||||
okMsg = _("Disable these plugins")
|
||||
cancelMsg = _("Don't disable %(plugin)s") % msg_dict
|
||||
|
||||
okButton = (okMsg, Gtk.STOCK_OK, Gtk.ResponseType.YES)
|
||||
cancelButton = (cancelMsg, Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
|
||||
|
||||
answer = self.Ask(msg, (cancelButton, okButton), widgets)
|
||||
if conflict[0] == 'RequiresFeature':
|
||||
choice = widgets[0].get_active_text()
|
||||
return answer, choice
|
||||
|
||||
return answer
|
||||
e
|
|
@ -0,0 +1,96 @@
|
|||
# -*- coding: UTF-8 -*-
|
||||
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
#
|
||||
# Authors: Quinn Storm (quinn@beryl-project.org)
|
||||
# Patrick Niklaus (marex@opencompositing.org)
|
||||
# Guillaume Seguin (guillaume@segu.in)
|
||||
# Christopher Williams (christopherw@verizon.net)
|
||||
# Copyright (C) 2007 Quinn Storm
|
||||
|
||||
from gi.repository import Gtk, Gdk
|
||||
|
||||
# Current Screen
|
||||
#
|
||||
CurrentScreenNum = Gdk.Display.get_default().get_n_screens()
|
||||
|
||||
# Settings Table
|
||||
#
|
||||
TableDef = Gtk.AttachOptions.FILL | Gtk.AttachOptions.EXPAND
|
||||
TableX = 4
|
||||
TableY = 2
|
||||
|
||||
# Action Constants
|
||||
#
|
||||
KeyModifier = ["Shift", "Control", "Mod1", "Mod2", "Mod3", "Mod4",
|
||||
"Mod5", "Alt", "Meta", "Super", "Hyper", "ModeSwitch"]
|
||||
Edges = ["Left", "Right", "Top", "Bottom",
|
||||
"TopLeft", "TopRight", "BottomLeft", "BottomRight"]
|
||||
|
||||
# Label Styles
|
||||
#
|
||||
HeaderMarkup = "<span size='large' weight='800'>%s</span>"
|
||||
|
||||
# Image Types
|
||||
#
|
||||
ImageNone = 0
|
||||
ImagePlugin = 1
|
||||
ImageCategory = 2
|
||||
ImageThemed = 3
|
||||
ImageStock = 4
|
||||
|
||||
# Filter Levels
|
||||
#
|
||||
FilterName = 1 << 0
|
||||
FilterLongDesc = 1 << 1
|
||||
FilterValue = 1 << 2 # Settings Only
|
||||
FilterCategory = 1 << 3 # Plugins Only
|
||||
FilterAll = FilterName | FilterLongDesc | FilterValue | FilterCategory
|
||||
|
||||
# Paths
|
||||
#
|
||||
DataDir = "/usr/share"
|
||||
IconDir = DataDir+"/ccsm/icons"
|
||||
PixmapDir = DataDir+"/ccsm/images"
|
||||
|
||||
# Version
|
||||
#
|
||||
Version = "0.9.4"
|
||||
|
||||
|
||||
# Translation
|
||||
#
|
||||
import locale
|
||||
import gettext
|
||||
locale.setlocale(locale.LC_ALL, "")
|
||||
gettext.bindtextdomain("ccsm", DataDir + "/locale")
|
||||
gettext.textdomain("ccsm")
|
||||
_ = gettext.gettext
|
||||
|
||||
# Category Transaltion Table
|
||||
# Just to get them into gettext
|
||||
#
|
||||
CategoryTranslation = {
|
||||
"General": _("General"),
|
||||
"Accessibility": _("Accessibility"),
|
||||
"Desktop": _("Desktop"),
|
||||
"Extras": _("Extras"),
|
||||
"Window Management": _("Window Management"),
|
||||
"Effects": _("Effects"),
|
||||
"Image Loading": _("Image Loading"),
|
||||
"Utility": _("Utility"),
|
||||
"All": _("All"),
|
||||
"Uncategorized": _("Uncategorized")
|
||||
}
|
|
@ -0,0 +1,415 @@
|
|||
# -*- coding: UTF-8 -*-
|
||||
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
#
|
||||
# Authors: Quinn Storm (quinn@beryl-project.org)
|
||||
# Patrick Niklaus (marex@opencompositing.org)
|
||||
# Guillaume Seguin (guillaume@segu.in)
|
||||
# Christopher Williams (christopherw@verizon.net)
|
||||
# Copyright (C) 2007 Quinn Storm
|
||||
|
||||
import os
|
||||
import weakref
|
||||
|
||||
from gi.repository import GObject, Gtk, Gdk, Pango
|
||||
|
||||
from Constants import *
|
||||
from cgi import escape as protect_pango_markup
|
||||
import operator
|
||||
import itertools
|
||||
|
||||
import locale
|
||||
import gettext
|
||||
locale.setlocale(locale.LC_ALL, "")
|
||||
gettext.bindtextdomain("ccsm", DataDir + "/locale")
|
||||
gettext.textdomain("ccsm")
|
||||
_ = gettext.gettext
|
||||
|
||||
IconTheme = Gtk.IconTheme.get_default()
|
||||
#TODO
|
||||
#if not IconDir in IconTheme.get_search_path():
|
||||
# IconTheme.prepend_search_path(IconDir)
|
||||
|
||||
def gtk_process_events ():
|
||||
while Gtk.events_pending ():
|
||||
Gtk.main_iteration ()
|
||||
|
||||
def getScreens():
|
||||
screens = []
|
||||
display = Gdk.Display.get_default()
|
||||
nScreens = display.get_n_screens()
|
||||
for i in range(nScreens):
|
||||
screens.append(i)
|
||||
return screens
|
||||
|
||||
def getDefaultScreen():
|
||||
display = Gdk.Display.get_default()
|
||||
return display.get_default_screen().get_number()
|
||||
|
||||
def protect_markup_dict (dict_):
|
||||
return dict((k, protect_pango_markup (v)) for (k, v) in dict_.items())
|
||||
|
||||
class Image (Gtk.Image):
|
||||
|
||||
def __init__ (self, name = None, type = ImageNone, size = 32,
|
||||
useMissingImage = False):
|
||||
GObject.GObject.__init__ (self)
|
||||
|
||||
if not name:
|
||||
return
|
||||
|
||||
if useMissingImage:
|
||||
self.set_from_stock (Gtk.STOCK_MISSING_IMAGE,
|
||||
Gtk.IconSize.LARGE_TOOLBAR)
|
||||
return
|
||||
|
||||
try:
|
||||
if type in (ImagePlugin, ImageCategory, ImageThemed):
|
||||
pixbuf = None
|
||||
|
||||
if type == ImagePlugin:
|
||||
name = "plugin-" + name
|
||||
try:
|
||||
pixbuf = IconTheme.load_icon (name, size, 0)
|
||||
except GObject.GError:
|
||||
pixbuf = IconTheme.load_icon ("plugin-unknown", size, 0)
|
||||
|
||||
elif type == ImageCategory:
|
||||
name = "plugins-" + name
|
||||
try:
|
||||
pixbuf = IconTheme.load_icon (name, size, 0)
|
||||
except GObject.GError:
|
||||
pixbuf = IconTheme.load_icon ("plugins-unknown", size, 0)
|
||||
|
||||
else:
|
||||
pixbuf = IconTheme.load_icon (name, size, 0)
|
||||
|
||||
self.set_from_pixbuf (pixbuf)
|
||||
|
||||
elif type == ImageStock:
|
||||
self.set_from_stock (name, size)
|
||||
except GObject.GError as e:
|
||||
self.set_from_stock (Gtk.STOCK_MISSING_IMAGE, Gtk.IconSize.BUTTON)
|
||||
|
||||
class ActionImage (Gtk.Alignment):
|
||||
|
||||
map = {
|
||||
"keyboard" : "input-keyboard",
|
||||
"button" : "input-mouse",
|
||||
"edges" : "video-display",
|
||||
"bell" : "audio-x-generic"
|
||||
}
|
||||
|
||||
def __init__ (self, action):
|
||||
GObject.GObject.__init__ (self, 0, 0.5)
|
||||
self.set_padding (0, 0, 0, 10)
|
||||
if action in self.map: action = self.map[action]
|
||||
self.add (Image (name = action, type = ImageThemed, size = 22))
|
||||
|
||||
class SizedButton (Gtk.Button):
|
||||
|
||||
minWidth = -1
|
||||
minHeight = -1
|
||||
|
||||
def __init__ (self, minWidth = -1, minHeight = -1):
|
||||
super (SizedButton, self).__init__ ()
|
||||
self.minWidth = minWidth
|
||||
self.minHeight = minHeight
|
||||
self.connect ("size-request", self.adjust_size)
|
||||
|
||||
def adjust_size (self, widget, requisition):
|
||||
width, height = requisition.width, requisition.height
|
||||
newWidth = max (width, self.minWidth)
|
||||
newHeight = max (height, self.minHeight)
|
||||
self.set_size_request (newWidth, newHeight)
|
||||
|
||||
class PrettyButton (Gtk.Button):
|
||||
__gsignals__ = {
|
||||
'draw': 'override',
|
||||
}
|
||||
|
||||
_old_toplevel = None
|
||||
|
||||
def __init__ (self):
|
||||
super (PrettyButton, self).__init__ ()
|
||||
self.states = {
|
||||
"focus" : False,
|
||||
"pointer" : False
|
||||
}
|
||||
self.set_size_request (200, -1)
|
||||
self.set_relief (Gtk.ReliefStyle.NONE)
|
||||
self.connect ("focus-in-event", self.update_state_in, "focus")
|
||||
self.connect ("focus-out-event", self.update_state_out, "focus")
|
||||
self.connect ("hierarchy-changed", self.hierarchy_changed)
|
||||
|
||||
def hierarchy_changed (self, widget, old_toplevel):
|
||||
if old_toplevel == self._old_toplevel:
|
||||
return
|
||||
|
||||
if not old_toplevel and self.state != Gtk.StateType.NORMAL:
|
||||
self.set_state(Gtk.StateType.PRELIGHT)
|
||||
self.set_state(Gtk.StateType.NORMAL)
|
||||
|
||||
self._old_toplevel = old_toplevel
|
||||
|
||||
|
||||
def update_state_in (self, *args):
|
||||
state = args[-1]
|
||||
self.set_state (Gtk.StateType.PRELIGHT)
|
||||
self.states[state] = True
|
||||
|
||||
def update_state_out (self, *args):
|
||||
state = args[-1]
|
||||
self.states[state] = False
|
||||
if True in self.states.values ():
|
||||
self.set_state (Gtk.StateType.PRELIGHT)
|
||||
else:
|
||||
self.set_state (Gtk.StateType.NORMAL)
|
||||
|
||||
def do_expose_event (self, event):
|
||||
has_focus = self.flags () & Gtk.HAS_FOCUS
|
||||
if has_focus:
|
||||
self.unset_flags (Gtk.HAS_FOCUS)
|
||||
|
||||
ret = super (PrettyButton, self).do_expose_event (self, event)
|
||||
|
||||
if has_focus:
|
||||
self.set_flags (Gtk.HAS_FOCUS)
|
||||
|
||||
return ret
|
||||
|
||||
class Label(Gtk.Label):
|
||||
def __init__(self, value = "", wrap = 160):
|
||||
GObject.GObject.__init__(self, value)
|
||||
self.props.xalign = 0
|
||||
self.props.wrap_mode = Pango.WrapMode.WORD
|
||||
self.set_line_wrap(True)
|
||||
self.set_size_request(wrap, -1)
|
||||
|
||||
class NotFoundBox(Gtk.Alignment):
|
||||
def __init__(self, value=""):
|
||||
GObject.GObject.__init__(self, 0.5, 0.5, 0.0, 0.0)
|
||||
|
||||
box = Gtk.HBox()
|
||||
self.Warning = Gtk.Label()
|
||||
self.Markup = _("<span size=\"large\"><b>No matches found.</b> </span><span>\n\n Your filter \"<b>%s</b>\" does not match any items.</span>")
|
||||
value = protect_pango_markup(value)
|
||||
self.Warning.set_markup(self.Markup % value)
|
||||
image = Image("face-surprise", ImageThemed, 48)
|
||||
|
||||
box.pack_start(image, False, False, 0)
|
||||
box.pack_start(self.Warning, True, True, 15)
|
||||
self.add(box)
|
||||
|
||||
def update(self, value):
|
||||
value = protect_pango_markup(value)
|
||||
self.Warning.set_markup(self.Markup % value)
|
||||
|
||||
class IdleSettingsParser:
|
||||
def __init__(self, context, main):
|
||||
def FilterPlugin (p):
|
||||
return not p.Initialized and p.Enabled
|
||||
|
||||
self.Context = context
|
||||
self.Main = main
|
||||
self.PluginList = [p for p in self.Context.Plugins.items() if FilterPlugin(p[1])]
|
||||
nCategories = len (main.MainPage.RightWidget._boxes)
|
||||
self.CategoryLoadIconsList = list(range(3, nCategories)) # Skip the first 3
|
||||
print('Loading icons...')
|
||||
|
||||
GObject.timeout_add (150, self.Wait)
|
||||
|
||||
def Wait(self):
|
||||
if not self.PluginList:
|
||||
return False
|
||||
|
||||
if len (self.CategoryLoadIconsList) == 0: # If we're done loading icons
|
||||
GObject.idle_add (self.ParseSettings)
|
||||
else:
|
||||
GObject.idle_add (self.LoadCategoryIcons)
|
||||
|
||||
return False
|
||||
|
||||
def ParseSettings(self):
|
||||
name, plugin = self.PluginList[0]
|
||||
|
||||
if not plugin.Initialized:
|
||||
plugin.Update ()
|
||||
self.Main.RefreshPage(plugin)
|
||||
|
||||
self.PluginList.remove (self.PluginList[0])
|
||||
|
||||
GObject.timeout_add (200, self.Wait)
|
||||
|
||||
return False
|
||||
|
||||
def LoadCategoryIcons(self):
|
||||
from ccm.Widgets import PluginButton
|
||||
|
||||
catIndex = self.CategoryLoadIconsList[0]
|
||||
pluginWindow = self.Main.MainPage.RightWidget
|
||||
categoryBox = pluginWindow._boxes[catIndex]
|
||||
for (pluginIndex, plugin) in \
|
||||
enumerate (categoryBox.get_unfiltered_plugins()):
|
||||
categoryBox._buttons[pluginIndex] = PluginButton (plugin)
|
||||
categoryBox.rebuild_table (categoryBox._current_cols, True)
|
||||
pluginWindow.connect_buttons (categoryBox)
|
||||
|
||||
self.CategoryLoadIconsList.remove (self.CategoryLoadIconsList[0])
|
||||
|
||||
GObject.timeout_add (150, self.Wait)
|
||||
|
||||
return False
|
||||
|
||||
# Updates all registered setting when they where changed through CompizConfig
|
||||
class Updater:
|
||||
|
||||
def __init__ (self):
|
||||
self.VisibleSettings = {}
|
||||
self.Plugins = []
|
||||
self.Block = 0
|
||||
|
||||
def SetContext (self, context):
|
||||
self.Context = context
|
||||
|
||||
GObject.timeout_add (2000, self.Update)
|
||||
|
||||
def Append (self, widget):
|
||||
reference = weakref.ref(widget)
|
||||
setting = widget.Setting
|
||||
self.VisibleSettings.setdefault((setting.Plugin.Name, setting.Name), []).append(reference)
|
||||
|
||||
def AppendPlugin (self, plugin):
|
||||
self.Plugins.append (plugin)
|
||||
|
||||
def Remove (self, widget):
|
||||
setting = widget.Setting
|
||||
l = self.VisibleSettings.get((setting.Plugin.Name, setting.Name))
|
||||
if not l:
|
||||
return
|
||||
for i, ref in enumerate(list(l)):
|
||||
if ref() is widget:
|
||||
l.remove(ref)
|
||||
break
|
||||
|
||||
def UpdatePlugins(self):
|
||||
for plugin in self.Plugins:
|
||||
plugin.Read()
|
||||
|
||||
def UpdateSetting (self, setting):
|
||||
widgets = self.VisibleSettings.get((setting.Plugin.Name, setting.Name))
|
||||
if not widgets:
|
||||
return
|
||||
for reference in widgets:
|
||||
widget = reference()
|
||||
if widget is not None:
|
||||
widget.Read()
|
||||
|
||||
def Update (self):
|
||||
if self.Block > 0:
|
||||
return True
|
||||
|
||||
if self.Context.ProcessEvents():
|
||||
changed = self.Context.ChangedSettings
|
||||
if [s for s in changed if s.Plugin.Name == "core" and s.Name == "active_plugins"]:
|
||||
self.UpdatePlugins()
|
||||
|
||||
for setting in list(changed):
|
||||
widgets = self.VisibleSettings.get((setting.Plugin.Name, setting.Name))
|
||||
if widgets:
|
||||
for reference in widgets:
|
||||
widget = reference()
|
||||
if widget is not None:
|
||||
widget.Read()
|
||||
if widget.List:
|
||||
widget.ListWidget.Read()
|
||||
changed.remove(setting)
|
||||
|
||||
self.Context.ChangedSettings = changed
|
||||
|
||||
return True
|
||||
|
||||
GlobalUpdater = Updater ()
|
||||
|
||||
class PluginSetting:
|
||||
|
||||
def __init__ (self, plugin, widget, handler):
|
||||
self.Widget = widget
|
||||
self.Plugin = plugin
|
||||
self.Handler = handler
|
||||
GlobalUpdater.AppendPlugin (self)
|
||||
|
||||
def Read (self):
|
||||
widget = self.Widget
|
||||
widget.handler_block(self.Handler)
|
||||
widget.set_active (self.Plugin.Enabled)
|
||||
widget.set_sensitive (self.Plugin.Context.AutoSort)
|
||||
widget.handler_unblock(self.Handler)
|
||||
|
||||
class PureVirtualError(Exception):
|
||||
pass
|
||||
|
||||
def SettingKeyFunc(value):
|
||||
return value.Plugin.Ranking[value.Name]
|
||||
|
||||
def CategoryKeyFunc(category):
|
||||
if 'General' == category:
|
||||
return ''
|
||||
else:
|
||||
return category or 'zzzzzzzz'
|
||||
|
||||
def GroupIndexKeyFunc(item):
|
||||
return item[1][0]
|
||||
|
||||
FirstItemKeyFunc = operator.itemgetter(0)
|
||||
|
||||
EnumSettingKeyFunc = operator.itemgetter(1)
|
||||
|
||||
PluginKeyFunc = operator.attrgetter('ShortDesc')
|
||||
|
||||
def HasOnlyType (settings, stype):
|
||||
return settings and not [s for s in settings if s.Type != stype]
|
||||
|
||||
def GetSettings(group, types=None):
|
||||
|
||||
def TypeFilter (settings, types):
|
||||
for setting in settings:
|
||||
if setting.Type in types:
|
||||
yield setting
|
||||
|
||||
if types:
|
||||
screen = TypeFilter(iter(group.Screen.values()), types)
|
||||
else:
|
||||
screen = iter(group.Screen.values())
|
||||
|
||||
return screen
|
||||
|
||||
# Support python 2.4
|
||||
try:
|
||||
any
|
||||
all
|
||||
except NameError:
|
||||
def any(iterable):
|
||||
for element in iterable:
|
||||
if element:
|
||||
return True
|
||||
return False
|
||||
|
||||
def all(iterable):
|
||||
for element in iterable:
|
||||
if not element:
|
||||
return False
|
||||
return True
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
from Conflicts import *
|
||||
from Constants import *
|
||||
from Utils import *
|
|
@ -0,0 +1,598 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import ConfigParser
|
||||
import os, sys
|
||||
import threading
|
||||
import gsettings
|
||||
from shutil import copy
|
||||
|
||||
class CloudConfig(threading.Thread):
|
||||
def __init__(self, sysdaemon):
|
||||
self.sysdaemon = sysdaemon
|
||||
self.conf = ConfigParser.ConfigParser()
|
||||
self.home = os.path.expandvars('$HOME')
|
||||
self.youker_path = './'
|
||||
self.kuaipan_path = ''
|
||||
|
||||
# write profiles
|
||||
def write_conf(self, section, conf_id, conf_schema, conf_path, conf_key, conf_type):
|
||||
value = gsettings.get(conf_schema, conf_path, conf_key, conf_type)
|
||||
if (conf_id in section):
|
||||
self.conf.set(conf_id, 'value', str(value))
|
||||
else:
|
||||
self.conf.add_section(conf_id)
|
||||
self.conf.set(conf_id, 'schema', conf_schema)
|
||||
self.conf.set(conf_id, 'path', conf_path)
|
||||
self.conf.set(conf_id, 'key', conf_key)
|
||||
self.conf.set(conf_id, 'type', conf_type)
|
||||
self.conf.set(conf_id, 'value', str(value))
|
||||
|
||||
# Save system configuration
|
||||
def save_configuration_to_local_file(self, file_name):
|
||||
pass
|
||||
# self.conf.read(file_name)
|
||||
# sections = self.conf.sections()
|
||||
|
||||
# # 桌面图标显示控制-----------------------------
|
||||
# self.write_conf(sections, 'show_desktop_icons',
|
||||
# 'org.gnome.desktop.background',
|
||||
# None, 'show-desktop-icons', 'boolean')
|
||||
# self.write_conf(sections, 'show_homefolder',
|
||||
# 'org.gnome.nautilus.desktop',
|
||||
# None, 'home-icon-visible', 'boolean')
|
||||
# self.write_conf(sections, 'show_network',
|
||||
# 'org.gnome.nautilus.desktop',
|
||||
# None, 'network-icon-visible', 'boolean')
|
||||
# self.write_conf(sections, 'show_trash',
|
||||
# 'org.gnome.nautilus.desktop',
|
||||
# None, 'trash-icon-visible', 'boolean')
|
||||
# self.write_conf(sections, 'show_devices',
|
||||
# 'org.gnome.nautilus.desktop',
|
||||
# None, 'volumes-visible', 'boolean')
|
||||
|
||||
# # 启动器设置----------------------------------
|
||||
# self.write_conf(sections, 'launcher_autohide',
|
||||
# 'org.compiz.unityshell',
|
||||
# '/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
# 'launcher-hide-mode', 'int')
|
||||
# self.write_conf(sections, 'launcher_icon_size',
|
||||
# 'org.compiz.unityshell',
|
||||
# '/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
# 'icon-size', 'int')
|
||||
|
||||
# # 触摸板设置-----------------------------------
|
||||
## self.write_conf(sections, 'touchpad_enable',
|
||||
## 'org.gnome.settings-daemon.peripherals.touchpad',
|
||||
## None, 'touchpad-enabled', 'boolean')
|
||||
## self.write_conf(sections, 'touch_horizontal_scrolling',
|
||||
## 'org.gnome.settings-daemon.peripherals.touchpad',
|
||||
## None, 'horiz-scroll-enabled', 'boolean')
|
||||
## self.write_conf(sections, 'type_scroll_bar',
|
||||
## 'com.canonical.desktop.interface',
|
||||
## None, 'scrollbar-mode', 'string')
|
||||
## self.write_conf(sections, 'touchpad_scrolling_mode',
|
||||
## 'org.gnome.settings-daemon.peripherals.touchpad',
|
||||
## None, 'scroll-method', 'string')
|
||||
|
||||
# # 字体设置-------------------------------------
|
||||
# self.write_conf(sections, 'default_font',
|
||||
# 'org.gnome.desktop.interface',
|
||||
# None, 'font-name', 'string')
|
||||
# self.write_conf(sections, 'desktop_font',
|
||||
# 'org.gnome.nautilus.desktop',
|
||||
# None, 'font', 'string')
|
||||
# self.write_conf(sections, 'document_font',
|
||||
# 'org.gnome.desktop.interface',
|
||||
# None, 'document-font-name', 'string')
|
||||
# self.write_conf(sections, 'monospace_font',
|
||||
# 'org.gnome.desktop.interface',
|
||||
# None, 'monospace-font-name', 'string')
|
||||
# self.write_conf(sections, 'window_title_font',
|
||||
# 'org.gnome.desktop.wm.preferences',
|
||||
# None, 'titlebar-font', 'string')
|
||||
# self.write_conf(sections, 'font_zoom',
|
||||
# 'org.gnome.desktop.interface',
|
||||
# None, 'text-scaling-factor', 'double')
|
||||
# self.write_conf(sections, 'font_hinting',
|
||||
# 'org.gnome.settings-daemon.plugins.xsettings',
|
||||
# None, 'hinting', 'string')
|
||||
# self.write_conf(sections, 'font_antialiasing',
|
||||
# 'org.gnome.settings-daemon.plugins.xsettings',
|
||||
# None, 'antialiasing', 'string')
|
||||
|
||||
# # 主题设置-------------------------------------
|
||||
# #self.write_conf(sections, 'gtk_theme',
|
||||
# # 'org.gnome.desktop.interface',
|
||||
# # None, 'gtk-theme', 'string')
|
||||
## self.write_conf(sections, 'window_theme',
|
||||
## 'org.gnome.desktop.wm.preferences',
|
||||
## None, 'theme', 'string')
|
||||
# self.write_conf(sections, 'icon_theme',
|
||||
# 'org.gnome.desktop.interface',
|
||||
# None, 'icon-theme', 'string')
|
||||
|
||||
# # 窗口设置--------------------------------------
|
||||
# self.write_conf(sections, 'window_button',
|
||||
# 'org.gnome.desktop.wm.preferences',
|
||||
# None, 'button-layout', 'string')
|
||||
# self.write_conf(sections, 'menus_have_icons',
|
||||
# 'org.gnome.desktop.interface',
|
||||
# None, 'menus-have-icons', 'boolean')
|
||||
# self.write_conf(sections, 'titlebar_wheel',
|
||||
# 'org.compiz.gwd',
|
||||
# None, 'mouse-wheel-action', 'string')
|
||||
# self.write_conf(sections, 'titlebar_double',
|
||||
# 'org.gnome.desktop.wm.preferences',
|
||||
# None, 'action-double-click-titlebar', 'string')
|
||||
# self.write_conf(sections, 'titlebar_middle',
|
||||
# 'org.gnome.desktop.wm.preferences',
|
||||
# None, 'action-middle-click-titlebar', 'string')
|
||||
# self.write_conf(sections, 'titlebar_right',
|
||||
# 'org.gnome.desktop.wm.preferences',
|
||||
# None, 'action-right-click-titlebar', 'string')
|
||||
|
||||
# # 文件管理器-----------------------------------
|
||||
# self.write_conf(sections, 'location_replace_pathbar',
|
||||
# 'org.gnome.nautilus.preferences',
|
||||
# None, 'always-use-location-entry', 'boolean')
|
||||
# self.write_conf(sections, 'auto_mount_media',
|
||||
# 'org.gnome.desktop.media-handling',
|
||||
# None, 'automount', 'boolean')
|
||||
# self.write_conf(sections, 'auto_open_folder',
|
||||
# 'org.gnome.desktop.media-handling',
|
||||
# None, 'automount-open', 'boolean')
|
||||
# self.write_conf(sections, 'prompt_autorun_programs',
|
||||
# 'org.gnome.desktop.media-handling',
|
||||
# None, 'autorun-never', 'boolean')
|
||||
# self.write_conf(sections, 'thumbnail_icon_size',
|
||||
# 'org.gnome.nautilus.icon-view',
|
||||
# None, 'thumbnail-size', 'int')
|
||||
# self.write_conf(sections, 'thumbnail_cache_time',
|
||||
# 'org.gnome.desktop.thumbnail-cache',
|
||||
# None, 'maximum-age', 'int')
|
||||
# self.write_conf(sections, 'thumbnail_cache_size',
|
||||
# 'org.gnome.desktop.thumbnail-cache',
|
||||
# None, 'maximum-size', 'int')
|
||||
|
||||
# fd = open(file_name, 'w')
|
||||
# self.conf.write(fd)
|
||||
# fd.close()
|
||||
|
||||
# system settings
|
||||
def setconf(self, conf_id):
|
||||
conf_schema = self.conf.get(conf_id, 'schema')
|
||||
conf_path = self.conf.get(conf_id, 'path')
|
||||
if conf_path == 'None':
|
||||
conf_path = None
|
||||
conf_key = self.conf.get(conf_id, 'key')
|
||||
conf_type = self.conf.get(conf_id, 'type')
|
||||
if conf_type == 'boolean' :
|
||||
conf_value = self.conf.getboolean(conf_id, 'value')
|
||||
elif conf_type == 'int' :
|
||||
conf_value = self.conf.getint(conf_id, 'value')
|
||||
elif conf_type == 'double' or conf_type == 'float' :
|
||||
conf_value = self.conf.getfloat(conf_id, 'value')
|
||||
else :
|
||||
conf_value = self.conf.get(conf_id, 'value')
|
||||
#gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
|
||||
if conf_id == 'window_button':
|
||||
value = gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'button-layout', 'string')
|
||||
left_list = ['close,minimize,maximize:', 'close,maximize,minimize:']
|
||||
right_list = [':minimize,maximize,close', ':maximize,minimize,close']
|
||||
if value in left_list and conf_value in right_list:
|
||||
gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
self.sysdaemon.download_cloud_conf_signal('window_button')
|
||||
elif value in right_list and conf_value in left_list:
|
||||
gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
self.sysdaemon.download_cloud_conf_signal('window_button')
|
||||
else:
|
||||
value = gsettings.get(conf_schema, conf_path, conf_key, conf_type)
|
||||
if value != conf_value:
|
||||
gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
self.sysdaemon.download_cloud_conf_signal(conf_id)
|
||||
|
||||
#----------------desktop icon settings----------------
|
||||
#if conf_id == 'show_desktop_icons':
|
||||
# value = gsettings.get('org.gnome.desktop.background',
|
||||
# None, 'show-desktop-icons', 'boolean')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('show_desktop_icons')
|
||||
#elif conf_id == 'show_homefolder':
|
||||
# value = gsettings.get('org.gnome.nautilus.desktop',
|
||||
# None, 'home-icon-visible', 'boolean')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('show_homefolder')
|
||||
#elif conf_id == 'show_network':
|
||||
# value = gsettings.get('org.gnome.nautilus.desktop',
|
||||
# None, 'network-icon-visible', 'boolean')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('show_network')
|
||||
#elif conf_id == 'show_trash':
|
||||
# value = gsettings.get('org.gnome.nautilus.desktop',
|
||||
# None, 'trash-icon-visible', 'boolean')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('show_trash')
|
||||
#elif conf_id == 'show_devices':
|
||||
# value = gsettings.get('org.gnome.nautilus.desktop',
|
||||
# None, 'volumes-visible', 'boolean')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('show_devices')
|
||||
|
||||
#----------------launcher settings----------------
|
||||
#elif conf_id == 'launcher_autohide':
|
||||
# value = gsettings.get('org.compiz.unityshell',
|
||||
# '/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
# 'launcher-hide-mode', 'int')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('launcher_autohide')
|
||||
#elif conf_id == 'launcher_icon_size':
|
||||
# value = gsettings.get('org.compiz.unityshell',
|
||||
# '/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
# 'icon-size', 'int')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('launcher_icon_size')
|
||||
|
||||
#----------------touchpad settings----------------
|
||||
#elif conf_id == 'touchpad_enable':
|
||||
# value = gsettings.get('org.gnome.settings-daemon.peripherals.touchpad',
|
||||
# None, 'touchpad-enabled', 'boolean')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('touchpad_enable')
|
||||
#elif conf_id == 'touch_horizontal_scrolling':
|
||||
# value = gsettings.get('org.gnome.settings-daemon.peripherals.touchpad',
|
||||
# None, 'horiz-scroll-enabled', 'boolean')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('touch_horizontal_scrolling')
|
||||
#elif conf_id == 'type_scroll_bar':
|
||||
# value = gsettings.get('com.canonical.desktop.interface',
|
||||
# None, 'scrollbar-mode', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('type_scroll_bar')
|
||||
#elif conf_id == 'touchpad_scrolling_mode':
|
||||
# value = gsettings.get('org.gnome.settings-daemon.peripherals.touchpad',
|
||||
# None, 'scroll-method', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('touchpad_scrolling_mode')
|
||||
|
||||
#----------------font settings----------------
|
||||
#elif conf_id == 'default_font':
|
||||
# value = gsettings.get('org.gnome.desktop.interface',
|
||||
# None, 'font-name', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('default_font')
|
||||
#elif conf_id == 'desktop_font':
|
||||
# value = gsettings.get('org.gnome.nautilus.desktop',
|
||||
# None, 'font', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('desktop_font')
|
||||
#elif conf_id == 'document_font':
|
||||
# value = gsettings.get('org.gnome.desktop.interface',
|
||||
# None, 'document-font-name', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('document_font')
|
||||
#elif conf_id == 'monospace_font':
|
||||
# value = gsettings.get('org.gnome.desktop.interface',
|
||||
# None, 'monospace-font-name', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('monospace_font')
|
||||
#elif conf_id == 'window_title_font':
|
||||
# value = gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
# None, 'titlebar-font', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('window_title_font')
|
||||
#elif conf_id == 'font_zoom':
|
||||
# value = gsettings.get('org.gnome.desktop.interface',
|
||||
# None, 'text-scaling-factor', 'double')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('font_zoom')
|
||||
#elif conf_id == 'font_hinting':
|
||||
# value = gsettings.get('org.gnome.settings-daemon.plugins.xsettings',
|
||||
# None, 'hinting', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('font_hinting')
|
||||
#elif conf_id == 'font_antialiasing':
|
||||
# value = gsettings.get('org.gnome.settings-daemon.plugins.xsettings',
|
||||
# None, 'antialiasing', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('font_antialiasing')
|
||||
|
||||
|
||||
#----------------theme settings----------------
|
||||
#elif conf_id == 'gtk_theme':
|
||||
# value = gsettings.get('org.gnome.desktop.interface',
|
||||
# None, 'gtk-theme', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('gtk_theme')
|
||||
#elif conf_id == 'window_theme':
|
||||
# value = gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
# None, 'theme', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('window_theme')
|
||||
#elif conf_id == 'icon_theme':
|
||||
# value = gsettings.get('org.gnome.desktop.interface',
|
||||
# None, 'icon-theme', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('icon_theme')
|
||||
|
||||
#----------------window settings----------------
|
||||
#elif conf_id == 'window_button':
|
||||
# value = gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
# None, 'button-layout', 'string')
|
||||
# left_list = ['close,minimize,maximize:', 'close,maximize,minimize:']
|
||||
# right_list = [':minimize,maximize,close', ':maximize,minimize,close']
|
||||
# if value in left_list and conf_value in right_list:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('window_button')
|
||||
# elif value in right_list and conf_value in left_list:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('window_button')
|
||||
#elif conf_id == 'menus_have_icons':
|
||||
# value = gsettings.get('org.gnome.desktop.interface',
|
||||
# None, 'menus-have-icons', 'boolean')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('menus_have_icons')
|
||||
#elif conf_id == 'titlebar_wheel':
|
||||
# value = gsettings.get('org.compiz.gwd',
|
||||
# None, 'mouse-wheel-action', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('titlebar_wheel')
|
||||
#elif conf_id == 'titlebar_double':
|
||||
# value = gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
# None, 'action-double-click-titlebar', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('titlebar_double')
|
||||
#elif conf_id == 'titlebar_middle':
|
||||
# value = gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
# None, 'action-middle-click-titlebar', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('titlebar_middle')
|
||||
#elif conf_id == 'titlebar_right':
|
||||
# value = gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
# None, 'action-right-click-titlebar', 'string')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('titlebar_right')
|
||||
|
||||
#----------------file manager----------------
|
||||
#elif conf_id == 'location_replace_pathbar':
|
||||
# value = gsettings.get('org.gnome.nautilus.preferences',
|
||||
# None, 'always-use-location-entry', 'boolean')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('location_replace_pathbar')
|
||||
#elif conf_id == 'auto_mount_media':
|
||||
# value = gsettings.get('org.gnome.desktop.media-handling',
|
||||
# None, 'automount', 'boolean')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('auto_mount_media')
|
||||
#elif conf_id == 'auto_open_folder':
|
||||
# value = gsettings.get('org.gnome.desktop.media-handling',
|
||||
# None, 'automount-open', 'boolean')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('auto_open_folder')
|
||||
#elif conf_id == 'prompt_autorun_programs':
|
||||
# value = gsettings.get('org.gnome.desktop.media-handling',
|
||||
# None, 'autorun-never', 'boolean')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('prompt_autorun_programs')
|
||||
#elif conf_id == 'thumbnail_icon_size':
|
||||
# value = gsettings.get('org.gnome.nautilus.icon-view',
|
||||
# None, 'thumbnail-size', 'int')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('thumbnail_icon_size')
|
||||
#elif conf_id == 'thumbnail_cache_time':
|
||||
# value = gsettings.get('org.gnome.desktop.thumbnail-cache',
|
||||
# None, 'maximum-age', 'int')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('thumbnail_cache_time')
|
||||
#elif conf_id == 'thumbnail_cache_size':
|
||||
# value = gsettings.get('org.gnome.desktop.thumbnail-cache',
|
||||
# None, 'maximum-size', 'int')
|
||||
# if value != conf_value:
|
||||
# gsettings.set(conf_schema, conf_path, conf_key, conf_type, conf_value)
|
||||
# self.sysdaemon.download_cloud_conf_signal('thumbnail_cache_size')
|
||||
|
||||
# desktop icon settings
|
||||
#if conf_id == 'show_desktop_icons':
|
||||
# self.sysdaemon.download_cloud_conf_signal('show_desktop_icons')
|
||||
#elif conf_id == 'show_homefolder':
|
||||
# self.sysdaemon.download_cloud_conf_signal('show_homefolder')
|
||||
#elif conf_id == 'show_network':
|
||||
# self.sysdaemon.download_cloud_conf_signal('show_network')
|
||||
#elif conf_id == 'show_trash':
|
||||
# self.sysdaemon.download_cloud_conf_signal('show_trash')
|
||||
#elif conf_id == 'show_devices':
|
||||
# self.sysdaemon.download_cloud_conf_signal('show_devices')
|
||||
|
||||
# launcher settings
|
||||
#elif conf_id == 'launcher_autohide':
|
||||
# self.sysdaemon.download_cloud_conf_signal('launcher_autohide')
|
||||
#elif conf_id == 'launcher_icon_size':
|
||||
# self.sysdaemon.download_cloud_conf_signal('launcher_icon_size')
|
||||
|
||||
# touchpad settings
|
||||
#elif conf_id == 'touchpad_enable':
|
||||
# self.sysdaemon.download_cloud_conf_signal('touchpad_enable')
|
||||
#elif conf_id == 'touch_horizontal_scrolling':
|
||||
# self.sysdaemon.download_cloud_conf_signal('touch_horizontal_scrolling')
|
||||
#elif conf_id == 'type_scroll_bar':
|
||||
# self.sysdaemon.download_cloud_conf_signal('type_scroll_bar')
|
||||
#elif conf_id == 'touchpad_scrolling_mode':
|
||||
# self.sysdaemon.download_cloud_conf_signal('touchpad_scrolling_mode')
|
||||
|
||||
# font settings
|
||||
#elif conf_id == 'default_font':
|
||||
# self.sysdaemon.download_cloud_conf_signal('default_font')
|
||||
#elif conf_id == 'desktop_font':
|
||||
# self.sysdaemon.download_cloud_conf_signal('desktop_font')
|
||||
#elif conf_id == 'document_font':
|
||||
# self.sysdaemon.download_cloud_conf_signal('document_font')
|
||||
#elif conf_id == 'monospace_font':
|
||||
# self.sysdaemon.download_cloud_conf_signal('monospace_font')
|
||||
#elif conf_id == 'window_title_font':
|
||||
# self.sysdaemon.download_cloud_conf_signal('window_title_font')
|
||||
#elif conf_id == 'font_zoom':
|
||||
# self.sysdaemon.download_cloud_conf_signal('font_zoom')
|
||||
#elif conf_id == 'font_hinting':
|
||||
# self.sysdaemon.download_cloud_conf_signal('font_hinting')
|
||||
#elif conf_id == 'font_antialiasing':
|
||||
# self.sysdaemon.download_cloud_conf_signal('font_antialiasing')
|
||||
|
||||
# theme settings
|
||||
#elif conf_id == 'gtk_theme':
|
||||
# self.sysdaemon.download_cloud_conf_signal('gtk_theme')
|
||||
#elif conf_id == 'window_theme':
|
||||
# self.sysdaemon.download_cloud_conf_signal('window_theme')
|
||||
#elif conf_id == 'icon_theme':
|
||||
# self.sysdaemon.download_cloud_conf_signal('icon_theme')
|
||||
|
||||
# window settings
|
||||
#elif conf_id == 'window_button':
|
||||
# self.sysdaemon.download_cloud_conf_signal('window_button')
|
||||
#elif conf_id == 'menus_have_icons':
|
||||
# self.sysdaemon.download_cloud_conf_signal('menus_have_icons')
|
||||
#elif conf_id == 'titlebar_wheel':
|
||||
# self.sysdaemon.download_cloud_conf_signal('titlebar_wheel')
|
||||
#elif conf_id == 'titlebar_double':
|
||||
# self.sysdaemon.download_cloud_conf_signal('titlebar_double')
|
||||
#elif conf_id == 'titlebar_middle':
|
||||
# self.sysdaemon.download_cloud_conf_signal('titlebar_middle')
|
||||
#elif conf_id == 'titlebar_right':
|
||||
# self.sysdaemon.download_cloud_conf_signal('titlebar_right')
|
||||
|
||||
# file manager
|
||||
#elif conf_id == 'location_replace_pathbar':
|
||||
# self.sysdaemon.download_cloud_conf_signal('location_replace_pathbar')
|
||||
#elif conf_id == 'auto_mount_media':
|
||||
# self.sysdaemon.download_cloud_conf_signal('auto_mount_media')
|
||||
#elif conf_id == 'auto_open_folder':
|
||||
# self.sysdaemon.download_cloud_conf_signal('auto_open_folder')
|
||||
#elif conf_id == 'prompt_autorun_programs':
|
||||
# self.sysdaemon.download_cloud_conf_signal('prompt_autorun_programs')
|
||||
#elif conf_id == 'thumbnail_icon_size':
|
||||
# self.sysdaemon.download_cloud_conf_signal('thumbnail_icon_size')
|
||||
#elif conf_id == 'thumbnail_cache_time':
|
||||
# self.sysdaemon.download_cloud_conf_signal('thumbnail_cache_time')
|
||||
#elif conf_id == 'thumbnail_cache_size':
|
||||
# self.sysdaemon.download_cloud_conf_signal('thumbnail_cache_size')
|
||||
|
||||
|
||||
# Restore the system configuration
|
||||
def use_cloud_configuration(self, file_name):
|
||||
print file_name
|
||||
self.conf.read(file_name)
|
||||
sections = self.conf.sections()
|
||||
for conf_id in sections:
|
||||
self.setconf(conf_id)
|
||||
return True
|
||||
|
||||
# Get kuaipan directory address
|
||||
def get_kuaipan_path(self):
|
||||
kpconf = ConfigParser.ConfigParser()
|
||||
kpconf.read(self.home + '/.config/ubuntukylin/kuaipan4uk.conf')
|
||||
return kpconf.get('client-info', 'Root')
|
||||
|
||||
# Determine whether kuaipan process starts
|
||||
def kuaipan_run(self):
|
||||
ps = os.popen('pgrep kuaipan4uk')
|
||||
kuaipan_ps = ps.read()
|
||||
ps.close()
|
||||
return kuaipan_ps
|
||||
|
||||
# Configuration file upload
|
||||
def real_upload_kysoft_cloud_conf(self):
|
||||
if not self.kuaipan_run():
|
||||
# 快盘没有启动或没有安装,提示用户安装并启动快盘才能上传
|
||||
self.sysdaemon.upload_cloud_conf_signal('upload_norun')
|
||||
return
|
||||
self.kuaipan_path = self.get_kuaipan_path() + '/[Ubuntu Kylin Sync]'
|
||||
if not os.path.isdir(self.kuaipan_path):
|
||||
os.makedirs(self.kuaipan_path)
|
||||
self.kuaipan_path = self.kuaipan_path + '/youker-assistant'
|
||||
if not os.path.isdir(self.kuaipan_path):
|
||||
os.makedirs(self.kuaipan_path)
|
||||
self.youker_path = self.home + '/.config/ubuntukylin/youker-assistant/'
|
||||
youker_abs_path = self.youker_path + 'youker-settings-cloud.conf'
|
||||
self.save_configuration_to_local_file(youker_abs_path)
|
||||
copy(youker_abs_path, self.kuaipan_path)
|
||||
self.sysdaemon.upload_cloud_conf_signal('upload_ok')
|
||||
|
||||
# Configuration file download
|
||||
def real_download_kysoft_cloud_conf(self):
|
||||
if not self.kuaipan_run():
|
||||
# 快盘没有启动或没有安装,提示用户安装并启动快盘才能下载
|
||||
self.sysdaemon.download_cloud_conf_signal('download_norun')
|
||||
return
|
||||
self.youker_path = self.home + '/.config/ubuntukylin/youker-assistant/'
|
||||
youker_abs_path = self.youker_path + 'youker-settings-cloud.conf'
|
||||
if not os.path.exists(youker_abs_path):
|
||||
os.mknod(youker_abs_path)
|
||||
cloud_abs_path = self.get_kuaipan_path() + '/[Ubuntu Kylin Sync]/youker-assistant/youker-settings-cloud.conf'
|
||||
if not os.path.isfile(cloud_abs_path):
|
||||
# 云端没有备份的配置文件
|
||||
self.sysdaemon.download_cloud_conf_signal('download_notconf')
|
||||
return
|
||||
copy(cloud_abs_path, self.youker_path)
|
||||
self.use_cloud_configuration(youker_abs_path)
|
||||
self.sysdaemon.download_cloud_conf_signal('download_ok')
|
||||
|
||||
def upload_kysoft_cloud_conf(self):
|
||||
threading.Thread(target=self.real_upload_kysoft_cloud_conf, name='UpLoad').start()
|
||||
|
||||
def download_kysoft_cloud_conf(self):
|
||||
threading.Thread(target=self.real_download_kysoft_cloud_conf, name='DownLoad').start()
|
||||
|
||||
if __name__ == '__main__':
|
||||
pass
|
||||
#cc = CloudConfig(None)
|
||||
#cc.upload_kysoft_cloud_conf()
|
||||
#cc.download_kysoft_cloud_conf()
|
||||
|
|
@ -0,0 +1,185 @@
|
|||
#! /usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (C) 2007-2011 Tualatrix Chou <tualatrix@gmail.com>
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
|
||||
|
||||
import glob
|
||||
import logging
|
||||
import ConfigParser
|
||||
|
||||
from lxml import etree
|
||||
|
||||
log = logging.getLogger('CommonSetting')
|
||||
|
||||
class RawConfigSetting(object):
|
||||
'''Just pass the file path'''
|
||||
def __init__(self, path, type=type):
|
||||
self._type = type
|
||||
|
||||
self._path = path
|
||||
|
||||
self.init_configparser()
|
||||
|
||||
def _type_convert_set(self, value):
|
||||
if type(value) == bool:
|
||||
if value == True:
|
||||
value = 'true'
|
||||
elif value == False:
|
||||
value = 'false'
|
||||
|
||||
# This is a hard code str type, so return '"xxx"' instead of 'xxx'
|
||||
if self._type == str:
|
||||
value = "'%s'" % value
|
||||
|
||||
return value
|
||||
|
||||
def _type_convert_get(self, value):
|
||||
if value == 'false':
|
||||
value = False
|
||||
elif value == 'true':
|
||||
value = True
|
||||
|
||||
# This is a hard code str type, so return '"xxx"' instead of 'xxx'
|
||||
if self._type == str or type(value) == str:
|
||||
if (value.startswith('"') and value.endswith('"')) or \
|
||||
(value.startswith("'") and value.endswith("'")):
|
||||
value = eval(value)
|
||||
|
||||
return value
|
||||
|
||||
def init_configparser(self):
|
||||
self._configparser = ConfigParser.ConfigParser()
|
||||
self._configparser.read(self._path)
|
||||
|
||||
def sections(self):
|
||||
return self._configparser.sections()
|
||||
|
||||
def options(self, section):
|
||||
return self._configparser.options(section)
|
||||
|
||||
def set_value(self, section, option, value):
|
||||
value = self._type_convert_set(value)
|
||||
|
||||
if not self._configparser.has_section(section):
|
||||
self._configparser.add_section(section)
|
||||
|
||||
self._configparser.set(section, option, value)
|
||||
with open(self._path, 'wb') as configfile:
|
||||
self._configparser.write(configfile)
|
||||
|
||||
self.init_configparser()
|
||||
|
||||
def get_value(self, section, option):
|
||||
if self._type:
|
||||
if self._type == int:
|
||||
getfunc = getattr(self._configparser, 'getint')
|
||||
elif self._type == float:
|
||||
getfunc = getattr(self._configparser, 'getfloat')
|
||||
elif self._type == bool:
|
||||
getfunc = getattr(self._configparser, 'getboolean')
|
||||
else:
|
||||
getfunc = getattr(self._configparser, 'get')
|
||||
|
||||
value = getfunc(section, option)
|
||||
else:
|
||||
log.debug("No type message, so use the generic get")
|
||||
value = self._configparser.get(section, option)
|
||||
|
||||
value = self._type_convert_get(value)
|
||||
|
||||
return value
|
||||
|
||||
class Schema(object):
|
||||
cached_schema = {}
|
||||
cached_schema_tree = {}
|
||||
cached_override = {}
|
||||
|
||||
@classmethod
|
||||
def load_override(cls):
|
||||
log.debug("\tLoading override")
|
||||
for override in glob.glob('/usr/share/glib-2.0/schemas/*.gschema.override'):
|
||||
try:
|
||||
cs = RawConfigSetting(override)
|
||||
for section in cs.sections():
|
||||
cls.cached_override[section] = {}
|
||||
for option in cs.options(section):
|
||||
cls.cached_override[section][option] = cs.get_value(section, option)
|
||||
except Exception, e:
|
||||
log.error('Error while parsing override file: %s' % override)
|
||||
|
||||
@classmethod
|
||||
def load_schema(cls, schema_id, key):
|
||||
log.debug("Loading schema value for: %s/%s" % (schema_id, key))
|
||||
if not cls.cached_override:
|
||||
cls.load_override()
|
||||
|
||||
if schema_id in cls.cached_override and \
|
||||
key in cls.cached_override[schema_id]:
|
||||
return cls.cached_override[schema_id][key]
|
||||
|
||||
if schema_id in cls.cached_schema and \
|
||||
key in cls.cached_schema[schema_id]:
|
||||
return cls.cached_schema[schema_id][key]
|
||||
|
||||
schema_defaults = {}
|
||||
|
||||
for schema_path in glob.glob('/usr/share/glib-2.0/schemas/*'):
|
||||
if not schema_path.endswith('.gschema.xml') and not schema_path.endswith('.enums.xml'):
|
||||
#TODO deal with enums
|
||||
continue
|
||||
|
||||
if schema_path in cls.cached_schema_tree:
|
||||
tree = cls.cached_schema_tree[schema_path]
|
||||
else:
|
||||
tree = etree.parse(open(schema_path))
|
||||
|
||||
for schema_node in tree.findall('schema'):
|
||||
if schema_node.attrib.get('id') == schema_id:
|
||||
for key_node in schema_node.findall('key'):
|
||||
if key_node.findall('default'):
|
||||
schema_defaults[key_node.attrib['name']] = cls.parse_value(key_node)
|
||||
else:
|
||||
continue
|
||||
|
||||
cls.cached_schema[schema_id] = schema_defaults
|
||||
if key in schema_defaults:
|
||||
return schema_defaults[key]
|
||||
else:
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def parse_value(cls, key_node):
|
||||
log.debug("Try to get type for value: %s" % key_node.items())
|
||||
value = key_node.find('default').text
|
||||
|
||||
#TODO enum type
|
||||
if key_node.attrib.get('type'):
|
||||
type = key_node.attrib['type']
|
||||
|
||||
if type == 'b':
|
||||
if value == 'true':
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
elif type == 'i':
|
||||
return int(value)
|
||||
elif type == 'd':
|
||||
return float(value)
|
||||
elif type == 'as':
|
||||
return eval(value)
|
||||
|
||||
return eval(value)
|
|
@ -0,0 +1,110 @@
|
|||
#! /usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (C) 2007-2011 Tualatrix Chou <tualatrix@gmail.com>
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
|
||||
|
||||
import logging
|
||||
|
||||
import ccm
|
||||
import compizconfig
|
||||
|
||||
log = logging.getLogger('CompizSetting')
|
||||
|
||||
class CompizPlugin:
|
||||
context = compizconfig.Context()
|
||||
|
||||
def __init__(self, name):
|
||||
self._plugin = self.context.Plugins[name]
|
||||
|
||||
@classmethod
|
||||
def set_plugin_active(cls, name, active):
|
||||
try:
|
||||
plugin = cls.context.Plugins[name]
|
||||
plugin.Enabled = int(active)
|
||||
cls.context.Write()
|
||||
except:
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def get_plugin_active(cls, name):
|
||||
try:
|
||||
plugin = cls.context.Plugins[name]
|
||||
return bool(plugin.Enabled)
|
||||
except:
|
||||
return False
|
||||
|
||||
def set_enabled(self, bool):
|
||||
self._plugin.Enabled = int(bool)
|
||||
self.save()
|
||||
|
||||
def get_enabled(self):
|
||||
return self._plugin.Enabled
|
||||
|
||||
def save(self):
|
||||
self.context.Write()
|
||||
|
||||
def resolve_conflict(self):
|
||||
conflicts = self.get_enabled() and self._plugin.DisableConflicts or \
|
||||
self._plugin.EnableConflicts
|
||||
conflict = ccm.PluginConflict(self._plugin, conflicts)
|
||||
return conflict.Resolve()
|
||||
|
||||
@classmethod
|
||||
def is_available(cls, name, setting):
|
||||
return cls.context.Plugins.has_key(name) and \
|
||||
cls.context.Plugins[name].Screen.has_key(setting)
|
||||
|
||||
def create_setting(self, key, target):
|
||||
settings = self._plugin.Screen
|
||||
|
||||
if type(settings) == list:
|
||||
return settings[0][key]
|
||||
else:
|
||||
return settings[key]
|
||||
|
||||
|
||||
class CompizSetting(object):
|
||||
def __init__(self, key, target=''):
|
||||
plugin_name, setting_name = key.split('.')
|
||||
self.key = key
|
||||
self._plugin = CompizPlugin(plugin_name)
|
||||
|
||||
if not self._plugin.get_enabled():
|
||||
self._plugin.set_enabled(True)
|
||||
|
||||
self._setting = self._plugin.create_setting(setting_name, target)
|
||||
|
||||
def set_value(self, value):
|
||||
self._setting.Value = value
|
||||
self._plugin.save()
|
||||
|
||||
def get_value(self):
|
||||
return self._setting.Value
|
||||
|
||||
def is_default_and_enabled(self):
|
||||
return self._setting.Value == self._setting.DefaultValue and \
|
||||
self._plugin.get_enabled()
|
||||
|
||||
def reset(self):
|
||||
self._setting.Reset()
|
||||
self._plugin.save()
|
||||
|
||||
def resolve_conflict(self):
|
||||
return self._plugin.resolve_conflict()
|
||||
|
||||
def get_schema_value(self):
|
||||
return self._setting.DefaultValue
|
|
@ -0,0 +1,251 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
import gsettings
|
||||
|
||||
class Desktop:
|
||||
desktop = None
|
||||
|
||||
def __init__(self):
|
||||
self.desktop = os.getenv('XDG_CURRENT_DESKTOP')
|
||||
if self.desktop is None:
|
||||
self.desktop = os.getenv('XDG_SESSION_DESKTOP')
|
||||
|
||||
# ---------------desktopicon---------------
|
||||
# -----------------默认值-----------------
|
||||
# Get Default Value
|
||||
def get_default_schema_value(self, schema, key):
|
||||
return gsettings.get_schema_value(schema, key)
|
||||
|
||||
# Set Default Value
|
||||
def set_default_schema_value(self, schema, key, type):
|
||||
default_value = self.get_default_schema_value(schema, key)
|
||||
if default_value is not None:
|
||||
return gsettings.set(schema, None, key, type, default_value)
|
||||
else:
|
||||
raise NotImplemented
|
||||
# ----------------------------------
|
||||
|
||||
|
||||
# show desktop icons, True/False
|
||||
def set_show_desktop_icons(self, flag):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.background',
|
||||
None,
|
||||
'show-desktop-icons',
|
||||
'boolean', flag)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.background',
|
||||
None,
|
||||
'show-desktop-icons',
|
||||
'boolean', flag)
|
||||
|
||||
# get is show desktop icons
|
||||
def get_show_desktop_icons(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.background',
|
||||
None, 'show-desktop-icons', 'boolean')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.background',
|
||||
None, 'show-desktop-icons', 'boolean')
|
||||
|
||||
def set_show_computer(self, flag):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.caja.desktop',
|
||||
None,
|
||||
'computer-icon-visible',
|
||||
'boolean', flag)
|
||||
|
||||
def get_show_computer(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.caja.desktop',
|
||||
None, 'computer-icon-visible', 'boolean')
|
||||
|
||||
# show home folder
|
||||
def set_show_homefolder(self, flag):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.caja.desktop',
|
||||
None,
|
||||
'home-icon-visible',
|
||||
'boolean', flag)
|
||||
else:
|
||||
return gsettings.set('org.gnome.nautilus.desktop',
|
||||
None,
|
||||
'home-icon-visible',
|
||||
'boolean', flag)
|
||||
|
||||
# get show homefolder
|
||||
def get_show_homefolder(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.caja.desktop',
|
||||
None, 'home-icon-visible', 'boolean')
|
||||
else:
|
||||
return gsettings.get('org.gnome.nautilus.desktop',
|
||||
None, 'home-icon-visible', 'boolean')
|
||||
|
||||
# show network
|
||||
def set_show_network(self, flag):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.caja.desktop',
|
||||
None,
|
||||
'network-icon-visible',
|
||||
'boolean', flag)
|
||||
else:
|
||||
return gsettings.set('org.gnome.nautilus.desktop',
|
||||
None,
|
||||
'network-icon-visible',
|
||||
'boolean', flag)
|
||||
|
||||
# get show network
|
||||
def get_show_network(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.caja.desktop',
|
||||
None, 'network-icon-visible', 'boolean')
|
||||
else:
|
||||
return gsettings.get('org.gnome.nautilus.desktop',
|
||||
None, 'network-icon-visible', 'boolean')
|
||||
|
||||
# show trash
|
||||
def set_show_trash(self, flag):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.caja.desktop',
|
||||
None,
|
||||
'trash-icon-visible',
|
||||
'boolean', flag)
|
||||
else:
|
||||
return gsettings.set('org.gnome.nautilus.desktop',
|
||||
None,
|
||||
'trash-icon-visible',
|
||||
'boolean', flag)
|
||||
|
||||
# get show trash
|
||||
def get_show_trash(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.caja.desktop',
|
||||
None, 'trash-icon-visible', 'boolean')
|
||||
else:
|
||||
return gsettings.get('org.gnome.nautilus.desktop',
|
||||
None, 'trash-icon-visible', 'boolean')
|
||||
|
||||
# show devices
|
||||
def set_show_devices(self, flag):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.caja.desktop',
|
||||
None,
|
||||
'volumes-visible',
|
||||
'boolean', flag)
|
||||
else:
|
||||
return gsettings.set('org.gnome.nautilus.desktop',
|
||||
None,
|
||||
'volumes-visible',
|
||||
'boolean', flag)
|
||||
|
||||
# get show devices
|
||||
def get_show_devices(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.caja.desktop',
|
||||
None, 'volumes-visible', 'boolean')
|
||||
else:
|
||||
return gsettings.get('org.gnome.nautilus.desktop',
|
||||
None, 'volumes-visible', 'boolean')
|
||||
|
||||
|
||||
#-------------------------cinnamon--------------------------------
|
||||
# show desktop icons, True/False
|
||||
def set_show_cinnamon_desktop_icons(self, flag):
|
||||
return gsettings.set('org.nemo.desktop',
|
||||
None,
|
||||
'show-desktop-icons',
|
||||
'boolean', flag)
|
||||
|
||||
# get is show desktop icons
|
||||
def get_show_cinnamon_desktop_icons(self):
|
||||
return gsettings.get('org.nemo.desktop',
|
||||
None, 'show-desktop-icons', 'boolean')
|
||||
|
||||
def set_show_cinnamon_computer(self, flag):
|
||||
return gsettings.set('org.nemo.desktop',
|
||||
None,
|
||||
'computer-icon-visible',
|
||||
'boolean', flag)
|
||||
|
||||
def get_show_cinnamon_computer(self):
|
||||
return gsettings.get('org.nemo.desktop',
|
||||
None, 'computer-icon-visible', 'boolean')
|
||||
|
||||
# show home folder
|
||||
def set_show_cinnamon_homefolder(self, flag):
|
||||
return gsettings.set('org.nemo.desktop',
|
||||
None,
|
||||
'home-icon-visible',
|
||||
'boolean', flag)
|
||||
|
||||
# get show homefolder
|
||||
def get_show_cinnamon_homefolder(self):
|
||||
return gsettings.get('org.nemo.desktop',
|
||||
None, 'home-icon-visible', 'boolean')
|
||||
|
||||
# show network
|
||||
def set_show_cinnamon_network(self, flag):
|
||||
return gsettings.set('org.nemo.desktop',
|
||||
None,
|
||||
'network-icon-visible',
|
||||
'boolean', flag)
|
||||
|
||||
# get show network
|
||||
def get_show_cinnamon_network(self):
|
||||
return gsettings.get('org.nemo.desktop',
|
||||
None, 'network-icon-visible', 'boolean')
|
||||
|
||||
# show trash
|
||||
def set_show_cinnamon_trash(self, flag):
|
||||
return gsettings.set('org.nemo.desktop',
|
||||
None,
|
||||
'trash-icon-visible',
|
||||
'boolean', flag)
|
||||
|
||||
# get show trash
|
||||
def get_show_cinnamon_trash(self):
|
||||
return gsettings.get('org.nemo.desktop',
|
||||
None, 'trash-icon-visible', 'boolean')
|
||||
|
||||
# show devices
|
||||
def set_show_cinnamon_devices(self, flag):
|
||||
return gsettings.set('org.nemo.desktop',
|
||||
None,
|
||||
'volumes-visible',
|
||||
'boolean', flag)
|
||||
|
||||
# get show devices
|
||||
def get_show_cinnamon_devices(self):
|
||||
return gsettings.get('org.nemo.desktop',
|
||||
None, 'volumes-visible', 'boolean')
|
||||
|
||||
# if __name__ == '__main__':
|
||||
# ddd = Desktop()
|
||||
# print ddd.get_show_desktop_icons()
|
||||
# print ddd.get_show_homefolder()
|
||||
# print ddd.get_show_network()
|
||||
# print ddd.get_show_trash()
|
||||
# print ddd.get_show_devices()
|
||||
# ddd.set_show_desktop_icons(True)
|
||||
# ddd.set_show_homefolder(True)
|
||||
# ddd.set_show_network(True)
|
||||
# ddd.set_show_trash(True)
|
||||
# ddd.set_show_devices(True)
|
|
@ -0,0 +1,267 @@
|
|||
#! /usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin Ltd
|
||||
#
|
||||
# Author: Kobe Lee <xiangli@ubuntukylin.com>
|
||||
# Maintainer: Ubuntu Kylin
|
||||
#
|
||||
# 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
import gsettings
|
||||
|
||||
class FileManager:
|
||||
|
||||
desktop = None
|
||||
|
||||
def __init__(self):
|
||||
self.desktop = os.getenv('XDG_CURRENT_DESKTOP')
|
||||
if self.desktop is None:
|
||||
self.desktop = os.getenv('XDG_SESSION_DESKTOP')
|
||||
|
||||
# -----------------默认值-----------------
|
||||
# Get Default Value
|
||||
def get_default_schema_value(self, schema, key):
|
||||
return gsettings.get_schema_value(schema, key)
|
||||
|
||||
# Set Default Value
|
||||
def set_default_schema_value(self, schema, key, type):
|
||||
default_value = self.get_default_schema_value(schema, key)
|
||||
if default_value is not None:
|
||||
return gsettings.set(schema, None, key, type, default_value)
|
||||
else:
|
||||
raise NotImplemented
|
||||
|
||||
# -----------------使用路径输入框取代路径栏-----------------
|
||||
# Get: Use the location entry instead of the pathbar
|
||||
def get_location_replace_pathbar(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.caja.preferences',
|
||||
None, 'always-use-location-entry', 'boolean')
|
||||
else:
|
||||
return gsettings.get('org.gnome.nautilus.preferences',
|
||||
None, 'always-use-location-entry', 'boolean')
|
||||
|
||||
# Set: Use the location entry instead of the pathbar
|
||||
def set_location_replace_pathbar(self, flag):
|
||||
#gstheme = gsettings.get_schema('org.gnome.desktop.sound')
|
||||
#gstheme.set_string('theme-name',theme)
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.caja.preferences',
|
||||
None,
|
||||
'always-use-location-entry',
|
||||
'boolean', flag)
|
||||
else:
|
||||
return gsettings.set('org.gnome.nautilus.preferences',
|
||||
None,
|
||||
'always-use-location-entry',
|
||||
'boolean', flag)
|
||||
|
||||
# -----------------自动挂载媒体-----------------
|
||||
# Get: Automatically mount media
|
||||
def get_auto_mount_media(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.media-handling',
|
||||
None, 'automount', 'boolean')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.media-handling',
|
||||
None, 'automount', 'boolean')
|
||||
|
||||
# Set: Automatically mount media
|
||||
def set_auto_mount_media(self, flag):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.media-handling',
|
||||
None,
|
||||
'automount',
|
||||
'boolean', flag)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.media-handling',
|
||||
None,
|
||||
'automount',
|
||||
'boolean', flag)
|
||||
|
||||
# -----------------自动打开文件夹-----------------
|
||||
# Get: Automatically open a folder
|
||||
def get_auto_open_folder(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.media-handling',
|
||||
None, 'automount-open', 'boolean')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.media-handling',
|
||||
None, 'automount-open', 'boolean')
|
||||
|
||||
# Set: Automatically open a folder
|
||||
def set_auto_open_folder(self, flag):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.media-handling',
|
||||
None,
|
||||
'automount-open',
|
||||
'boolean', flag)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.media-handling',
|
||||
None,
|
||||
'automount-open',
|
||||
'boolean', flag)
|
||||
|
||||
# -----------------提示自动运行的程序-----------------
|
||||
# Get: Prompt or autorun/autostart programs
|
||||
def get_prompt_autorun_programs(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.media-handling',
|
||||
None, 'autorun-never', 'boolean')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.media-handling',
|
||||
None, 'autorun-never', 'boolean')
|
||||
|
||||
# Set: Prompt or autorun/autostart programs
|
||||
def set_prompt_autorun_programs(self, flag):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.media-handling',
|
||||
None,
|
||||
'autorun-never',
|
||||
'boolean', flag)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.media-handling',
|
||||
None,
|
||||
'autorun-never',
|
||||
'boolean', flag)
|
||||
|
||||
# -----------------缩略图图标尺寸(像素) min=16, max=512, step=16, default=64-----------------
|
||||
# Get: Thumbnail icon size (pixels)
|
||||
def get_thumbnail_icon_size(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.caja.icon-view',
|
||||
None, 'thumbnail-size', 'int')
|
||||
else:
|
||||
return gsettings.get('org.gnome.nautilus.icon-view',
|
||||
None, 'thumbnail-size', 'int')
|
||||
|
||||
# Set: Thumbnail icon size (pixels)
|
||||
def set_thumbnail_icon_size(self, size):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.caja.icon-view',
|
||||
None,
|
||||
'thumbnail-size',
|
||||
'int', size)
|
||||
else:
|
||||
return gsettings.set('org.gnome.nautilus.icon-view',
|
||||
None,
|
||||
'thumbnail-size',
|
||||
'int', size)
|
||||
|
||||
# -----------------缩略图缓存时间(天数) min=-1, max=180, step=1, default=180-----------------
|
||||
# Get: Thumbnail cache time (days)
|
||||
def get_thumbnail_cache_time(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.thumbnail-cache',
|
||||
None, 'maximum-age', 'int')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.thumbnail-cache',
|
||||
None, 'maximum-age', 'int')
|
||||
|
||||
# Set: Thumbnail cache time (days)
|
||||
def set_thumbnail_cache_time(self, value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.thumbnail-cache',
|
||||
None,
|
||||
'maximum-age',
|
||||
'int', value)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.thumbnail-cache',
|
||||
None,
|
||||
'maximum-age',
|
||||
'int', value)
|
||||
|
||||
# -----------------最大缩略图缓存尺寸(MB) min=-1, max=512, step=1, default=512-----------------
|
||||
# Get: Maximum thumbnail cache size (MB)
|
||||
def get_thumbnail_cache_size(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.thumbnail-cache',
|
||||
None, 'maximum-size', 'int')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.thumbnail-cache',
|
||||
None, 'maximum-size', 'int')
|
||||
|
||||
# Set: Maximum thumbnail cache size (MB)
|
||||
def set_thumbnail_cache_size(self, size):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.thumbnail-cache',
|
||||
None,
|
||||
'maximum-size',
|
||||
'int', size)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.thumbnail-cache',
|
||||
None,
|
||||
'maximum-size',
|
||||
'int', size)
|
||||
|
||||
if __name__ == '__main__':
|
||||
pass
|
||||
# fm = FileManager()
|
||||
#value = fm.get_location_replace_pathbar()
|
||||
#if(value):
|
||||
# print "yes"
|
||||
# fm.set_location_replace_pathbar(False)
|
||||
#else:
|
||||
# print "False"
|
||||
# fm.set_location_replace_pathbar(True)
|
||||
|
||||
#value = fm.get_auto_mount_media()
|
||||
#if(value):
|
||||
# fm.set_auto_mount_media(False)
|
||||
#else:
|
||||
# fm.set_auto_mount_media(True)
|
||||
|
||||
#value = fm.get_auto_open_folder()
|
||||
#if(value):
|
||||
# fm.set_auto_open_folder(False)
|
||||
#else:
|
||||
# fm.set_auto_open_folder(True)
|
||||
|
||||
#value = fm.get_prompt_autorun_programs()
|
||||
#if(value):
|
||||
# fm.set_prompt_autorun_programs(False)
|
||||
#else:
|
||||
# fm.set_prompt_autorun_programs(True)
|
||||
|
||||
#value = fm.get_thumbnail_icon_size()
|
||||
#if(value == 64):
|
||||
# fm.set_thumbnail_icon_size(48)
|
||||
#else:
|
||||
# fm.set_thumbnail_icon_size(64)
|
||||
|
||||
#value = fm.get_thumbnail_cache_time()
|
||||
#if(value == 180):
|
||||
# fm.set_thumbnail_cache_time(120)
|
||||
#else:
|
||||
# fm.set_thumbnail_cache_time(180)
|
||||
|
||||
#value = fm.get_thumbnail_cache_size()
|
||||
#aa = fm.test()
|
||||
#print aa
|
||||
#if(value == 512):
|
||||
# fm.set_thumbnail_cache_size(500)
|
||||
#else:
|
||||
# fm.set_thumbnail_cache_size(512)
|
||||
|
||||
# aa = fm.get_default_schema_value('org.gnome.desktop.media-handling', 'automount')
|
||||
# print aa
|
||||
# #aa = fm.get_default_schema_value('org.gnome.desktop.media-handling', 'automount')
|
||||
# #print aa
|
||||
# #fm.set_default_schema_value('org.gnome.desktop.media-handling', 'automount', 'boolean')
|
||||
|
||||
# bb = fm.get_default_schema_value('org.gnome.nautilus.desktop', 'font')
|
||||
# print bb
|
|
@ -0,0 +1,92 @@
|
|||
#! /usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin Ltd
|
||||
#
|
||||
# Author: Kobe Lee <xiangli@ubuntukylin.com>
|
||||
# Maintainer: Ubuntu Kylin
|
||||
#
|
||||
# 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
from settings import Settings
|
||||
import types
|
||||
|
||||
class GeditManager:
|
||||
def __init__(self):
|
||||
self.default = None
|
||||
self.settings = Settings("org.gnome.gedit.preferences.encodings")
|
||||
|
||||
# -----------------默认值-----------------
|
||||
# Get Default Value
|
||||
def get_default_schema_value(self, schema, key):
|
||||
return self.settings.get_schema_value(schema, key)
|
||||
|
||||
# Set Default Value
|
||||
def set_default_schema_value(self, schema, key, type):
|
||||
default_value = self.get_default_schema_value(schema, key)
|
||||
if default_value is not None:
|
||||
return self.settings.set_value(key, type, default_value)
|
||||
else:
|
||||
raise NotImplemented
|
||||
|
||||
# 在Gedit中自动检测简体中文编码
|
||||
# on=['GB18030', 'UTF-8', 'CURRENT', 'ISO-8859-15', 'UTF-16']
|
||||
# off=['UTF-8', 'CURRENT', 'ISO-8859-15', 'UTF-16']
|
||||
# default = off
|
||||
# Get: Auto detect text encoding for Simplified Chinese in Gedit
|
||||
def get_detect_chinese_encoding(self):
|
||||
return self.settings.get_value("auto-detected", types.ListType)
|
||||
|
||||
# Set: Auto detect text encoding for Simplified Chinese in Gedit
|
||||
def set_detect_chinese_encoding(self, flag):
|
||||
list_on = ['GB18030', 'UTF-8', 'CURRENT', 'ISO-8859-15', 'UTF-16']
|
||||
list_off = ['UTF-8', 'CURRENT', 'ISO-8859-15', 'UTF-16']
|
||||
if(flag):
|
||||
self.settings.set_value("auto-detected", types.ListType, list_off)
|
||||
else:
|
||||
self.settings.set_value("auto-detected", types.ListType, list_on)
|
||||
|
||||
|
||||
# Get Default Value: Auto detect text encoding for Simplified Chinese in Gedit
|
||||
#def get_default_detect_chinese_encoding(self):
|
||||
# self.default = self.settings.get_schema_value("auto-detected")
|
||||
|
||||
# Set Default Value: Auto detect text encoding for Simplified Chinese in Gedit
|
||||
#def set_default_detect_chinese_encoding(self):
|
||||
# if self.default is not None:
|
||||
# self.settings.set_value("auto-detected", types.ListType, self.default)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gm = GeditManager()
|
||||
#aa = gm.get_detect_chinese_encoding()
|
||||
#print aa
|
||||
#list_on = ['GB18030', 'UTF-8', 'CURRENT', 'ISO-8859-15', 'UTF-16']
|
||||
#list_off = ['UTF-8', 'CURRENT', 'ISO-8859-15', 'UTF-16']
|
||||
#if aa == list_off:
|
||||
# gm.set_detect_chinese_encoding(False)
|
||||
#else:
|
||||
# gm.set_detect_chinese_encoding(True)
|
||||
|
||||
|
||||
#gm.get_default_detect_chinese_encoding()
|
||||
#print "default->"
|
||||
#print gm.default
|
||||
#gm.set_default_detect_chinese_encoding()
|
||||
|
||||
#aa = gm.get_default_schema_value("org.gnome.gedit.preferences.encodings", "auto-detected")
|
||||
#print aa
|
||||
gm.set_default_schema_value("org.gnome.gedit.preferences.encodings", "auto-detected", types.ListType)
|
|
@ -0,0 +1,51 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
from gi.repository import Gio as gio
|
||||
from common import Schema
|
||||
import logging
|
||||
|
||||
logger=logging.getLogger('youker-assistant-daemon')
|
||||
|
||||
def get(schema, path, key, type):
|
||||
try:
|
||||
gs = gio.Settings(schema, path)
|
||||
return gs.__getattribute__('get_' + type)(key)
|
||||
except:
|
||||
logger.debug("gsettings.get: can't find value for %s" % gs)
|
||||
return None
|
||||
|
||||
def set(schema, path, key, type, value):
|
||||
try:
|
||||
gs = gio.Settings(schema, path)
|
||||
gs.__getattribute__('set_' + type)(key, value)
|
||||
return True
|
||||
except:
|
||||
logger.debug("gsettings.set: can't find value for %s" % gs)
|
||||
return False
|
||||
|
||||
def get_schema(schema):
|
||||
return gio.Settings(schema)
|
||||
|
||||
# added by kobe: access default schema value
|
||||
def get_schema_value(schema, key):
|
||||
schema_default = Schema.load_schema(schema, key)
|
||||
if schema_default is not None:
|
||||
return schema_default
|
||||
else:
|
||||
raise NotImplemented
|
|
@ -0,0 +1,155 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import Image
|
||||
# from _pyio import open
|
||||
|
||||
class Others:
|
||||
|
||||
# custom plymouth bg by plymouthName
|
||||
def custom_plymouth_bg(self, plymouthName):
|
||||
plymouthName = plymouthName.encode('utf-8')
|
||||
existingDir = '/var/lib/youker-assistant-daemon/plymouth/existing/'
|
||||
linkFileDir = '/lib/plymouth/themes/default.plymouth'
|
||||
|
||||
# replace the config file
|
||||
shutil.copy(existingDir + plymouthName + '/default.plymouth', linkFileDir)
|
||||
|
||||
# add new custom plymouth
|
||||
def add_new_plymouth(self, customBG, plymouthName):
|
||||
# if plymouthName exist return false
|
||||
existingPlymouth = self.get_existing_plymouth_list()
|
||||
customBG = customBG.encode('utf-8')
|
||||
plymouthName = plymouthName.encode('utf-8')
|
||||
plymouthName
|
||||
if(plymouthName in existingPlymouth):
|
||||
return False
|
||||
else:
|
||||
existingDir = '/var/lib/youker-assistant-daemon/plymouth/existing/'
|
||||
customScript = '/var/lib/youker-assistant-daemon/plymouth/defaults/only_background.script'
|
||||
defaultplymouthfile = '/var/lib/youker-assistant-daemon/plymouth/defaults/default.plymouth'
|
||||
|
||||
# add new plymouth conf dir
|
||||
os.mkdir(existingDir + plymouthName)
|
||||
shutil.copy(defaultplymouthfile, existingDir + plymouthName + '/default.plymouth')
|
||||
# modify config file
|
||||
fileHandle = open(existingDir + plymouthName + '/default.plymouth', 'a')
|
||||
fileHandle.write('ImageDir=/lib/plymouth/themes/' + plymouthName + '\n')
|
||||
fileHandle.write('ScriptFile=/lib/plymouth/themes/' + plymouthName + '/youker.script')
|
||||
fileHandle.close()
|
||||
|
||||
# add new system plymouth dir
|
||||
os.mkdir('/lib/plymouth/themes/' + plymouthName)
|
||||
shutil.copy(customScript, '/lib/plymouth/themes/' + plymouthName + '/youker.script')
|
||||
#shutil.copy(customBG, '/lib/plymouth/themes/' + plymouthName + '/customBG.png')
|
||||
Image.open(customBG).save('/lib/plymouth/themes/' + plymouthName + '/customBG.png')
|
||||
|
||||
return True
|
||||
|
||||
# get existing plymouth list
|
||||
def get_existing_plymouth_list(self):
|
||||
result = []
|
||||
edir = ('/var/lib/youker-assistant-daemon/plymouth/existing')
|
||||
if os.path.isdir(edir):
|
||||
for f in os.listdir(edir):
|
||||
if os.path.isdir(os.path.join(edir, f)):
|
||||
result.append(f)
|
||||
result.sort()
|
||||
return result
|
||||
|
||||
# check and save current plymouth when init
|
||||
def plymouth_init_check(self):
|
||||
existingDir = '/var/lib/youker-assistant-daemon/plymouth/existing/'
|
||||
linkFileDir = '/lib/plymouth/themes/default.plymouth'
|
||||
|
||||
# add 0619
|
||||
if(os.path.exists('/lib/plymouth/themes/ubuntukylin-logo') == False):
|
||||
shutil.copytree('/var/lib/youker-assistant-daemon/plymouth/ubuntukylin-logo/', '/lib/plymouth/themes/ubuntukylin-logo')
|
||||
|
||||
# locate the current plymouth theme dir
|
||||
linkFile = open(linkFileDir)
|
||||
fullString = linkFile.read()
|
||||
linkFile.close()
|
||||
index = fullString.find('ScriptFile=')
|
||||
theLine = fullString[index:]
|
||||
# cut 'ScriptFile=' & '\n'
|
||||
scriptFile = theLine[theLine.find('/'):theLine.find('\n')]
|
||||
# scriptFile = theLine[theLine.find('/'):]
|
||||
scriptDir = scriptFile[0:scriptFile.rfind('/')]
|
||||
scriptName = scriptFile[scriptFile.rfind('/') + 1:]
|
||||
plymouthName = scriptDir[scriptDir.rfind('/') + 1:]
|
||||
|
||||
# check and save current pl linkFile.close()ymouth
|
||||
if(os.path.exists(existingDir + plymouthName) == False):
|
||||
os.mkdir(existingDir + plymouthName)
|
||||
shutil.copy(scriptFile, existingDir + plymouthName + '/' + scriptName)
|
||||
shutil.copy(linkFileDir, existingDir + plymouthName + '/default.plymouth')
|
||||
|
||||
def get_image_path(self,name):
|
||||
name = name.encode('utf-8')
|
||||
# if not os.path.exists('/lib/plymouth/themes/' + name + '/customBG.png') :
|
||||
if not os.path.exists('/lib/plymouth/themes/' + name + '/' + name + '.script') :
|
||||
if not os.path.exists('/lib/plymouth/themes/' + name + '/youker.script') :
|
||||
if not os.path.exists('/lib/plymouth/themes/' + name + '/customBG.png') :
|
||||
return "False"
|
||||
else:
|
||||
return "True"
|
||||
else:
|
||||
return "True"
|
||||
else :
|
||||
return "True"
|
||||
# path = '/lib/plymouth/themes/' + name + '/customBG.png'
|
||||
# return path
|
||||
|
||||
def delete_plymouth(self,plymouthName):
|
||||
plymouthName = plymouthName.encode('utf-8')
|
||||
fd = open('/lib/plymouth/themes/default.plymouth','r')
|
||||
animation = fd.read()
|
||||
fd.close()
|
||||
used = animation[animation.index('themes/')+len('themes/'):]
|
||||
used = used[:used.index('\n')]
|
||||
if used == plymouthName :
|
||||
return 'use'
|
||||
elif plymouthName == 'ubuntukylin-logo':
|
||||
return 'sys'
|
||||
else :
|
||||
shutil.rmtree('/var/lib/youker-assistant-daemon/plymouth/existing/' + plymouthName)
|
||||
shutil.rmtree('/lib/plymouth/themes/' + plymouthName)
|
||||
return 'ok'
|
||||
# plymouthName = plymouthName.encode('utf-8')
|
||||
# fd = open('/lib/plymouth/themes/default.plymouth','r')
|
||||
# animation = fd.read()
|
||||
# fd.close()
|
||||
# used = animation[animation.index('themes/')+len('themes/'):]
|
||||
# used = used[:used.index('\n')]
|
||||
# if used == plymouthName :
|
||||
# return False
|
||||
# else :
|
||||
# shutil.rmtree('/var/lib/youker-assistant-daemon/plymouth/existing/' + plymouthName)
|
||||
# shutil.rmtree('/lib/plymouth/themes/' + plymouthName)
|
||||
# return True
|
||||
|
||||
if __name__ == '__main__':
|
||||
ooo = Others()
|
||||
# print ooo.get_existing_plymouth_list()
|
||||
# ooo.add_new_plymouth('/home/shine/heihei.png', 'hoho')
|
||||
# ooo.custom_plymouth_bg('hoho')
|
||||
# ooo.plymouth_init_check()
|
|
@ -0,0 +1,115 @@
|
|||
#! /usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin Ltd
|
||||
#
|
||||
# Author: Kobe Lee <xiangli@ubuntukylin.com>
|
||||
# Maintainer: Ubuntu Kylin
|
||||
#
|
||||
# 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
|
||||
from gi.repository import Gio as gio
|
||||
import os, sys
|
||||
import types
|
||||
from common import Schema
|
||||
|
||||
#http://lazka.github.io/pgi-docs/api/Gio_2.0/classes/Settings.html
|
||||
|
||||
class Settings:
|
||||
#db = None
|
||||
#BASE_KEY = "org.gnome.gedit.preferences.encodings"
|
||||
def __init__(self, schema):
|
||||
self.db = gio.Settings.new(schema)
|
||||
|
||||
#def open_settings_db(self):
|
||||
# try:
|
||||
# self.db = gio.Settings.new(self.BASE_KEY)
|
||||
# except Exception as e:
|
||||
# print e
|
||||
|
||||
def get_value(self, key, type):
|
||||
try:
|
||||
setting_type = type
|
||||
get_func = {
|
||||
types.IntType: self.db.get_int,
|
||||
types.StringType: self.db.get_string,
|
||||
types.BooleanType: self.db.get_boolean,
|
||||
types.ListType: self.db.get_strv,
|
||||
types.DictType: self.db.get_string,
|
||||
types.NoneType: self.db.get_value,
|
||||
}[setting_type]
|
||||
return get_func(key)
|
||||
except Exception as e:
|
||||
print e
|
||||
return None
|
||||
|
||||
def set_value(self, key, type, value):
|
||||
try:
|
||||
setting_type = type
|
||||
set_func = {
|
||||
types.IntType: self.db.set_int,
|
||||
types.StringType: self.db.set_string,
|
||||
types.BooleanType: self.db.set_boolean,
|
||||
types.ListType: self.db.set_strv,
|
||||
types.DictType: self.db.set_string,
|
||||
types.NoneType: self.db.set_value,
|
||||
}[setting_type]
|
||||
set_func(key, value)
|
||||
except Exception as e:
|
||||
print e
|
||||
|
||||
def get_schema_value(self, schema, key):
|
||||
schema_default = Schema.load_schema(schema, key)
|
||||
if schema_default is not None:
|
||||
return schema_default
|
||||
else:
|
||||
raise NotImplemented
|
||||
|
||||
# kobe: test notify func
|
||||
# def connect_notify(self):
|
||||
# #def connect_notify(self, func, data=None):
|
||||
## gs = gio.Settings("org.gnome.nautilus.desktop", None)
|
||||
# self.db.connect("changed::home-icon-visible", self.kobe_test)
|
||||
|
||||
# def kobe_test(self, settings, key):
|
||||
# print "notify test success----------------------------"
|
||||
|
||||
if __name__ == '__main__':
|
||||
#list_on = ['GB18030', 'UTF-8', 'CURRENT', 'ISO-8859-15', 'UTF-16']
|
||||
#list_off = ['UTF-8', 'CURRENT', 'ISO-8859-15', 'UTF-16']
|
||||
settings = Settings("org.gnome.gedit.preferences.encodings")
|
||||
##settings.open_settings_db()
|
||||
#value = settings.get_value("auto-detected", types.ListType)
|
||||
#print type(value)#<type 'list'>
|
||||
#print value
|
||||
#if value == list_off:
|
||||
# settings.set_value("auto-detected", types.ListType, list_on)
|
||||
#else:
|
||||
# settings.set_value("auto-detected", types.ListType, list_off)
|
||||
|
||||
#settings = Settings("org.gnome.nautilus.preferences")
|
||||
#value = settings.get_value("always-use-location-entry", types.BooleanType)
|
||||
#settings = Settings("org.gnome.desktop.media-handling")
|
||||
#value = settings.get_value("automount", types.BooleanType)
|
||||
#print type(value)#<type 'list'>
|
||||
#print value
|
||||
|
||||
default_value = settings.get_schema_value("org.gnome.gedit.preferences.encodings", "auto-detected")
|
||||
print "default_value->"
|
||||
print default_value
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,222 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import gsettings
|
||||
import utils
|
||||
|
||||
class Sound:
|
||||
homedir = ''
|
||||
desktop = None
|
||||
|
||||
def __init__(self):
|
||||
self.homedir = utils.get_home_dir()
|
||||
self.desktop = os.getenv('XDG_CURRENT_DESKTOP')
|
||||
if self.desktop is None:
|
||||
self.desktop = os.getenv('XDG_SESSION_DESKTOP')
|
||||
|
||||
# sometimes need set homedir manual fe:the backend run by root dbus
|
||||
def set_homedir(self, homedir):
|
||||
self.homedir = homedir
|
||||
|
||||
# -----------------默认值-----------------
|
||||
# Get Default Value
|
||||
def get_default_schema_value(self, schema, key):
|
||||
return gsettings.get_schema_value(schema, key)
|
||||
|
||||
# Set Default Value
|
||||
def set_default_schema_value(self, schema, key, type):
|
||||
default_value = self.get_default_schema_value(schema, key)
|
||||
if default_value is not None:
|
||||
return gsettings.set(schema, None, key, type, default_value)
|
||||
else:
|
||||
raise NotImplemented
|
||||
# ----------------------------------
|
||||
def set_input_feedback_sounds_enable(self, flag):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.sound',
|
||||
None,
|
||||
'input-feedback-sounds',
|
||||
'boolean', flag)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.sound',
|
||||
None,
|
||||
'input-feedback-sounds',
|
||||
'boolean', flag)
|
||||
|
||||
def get_input_feedback_sounds_enable(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.sound',
|
||||
None, 'input-feedback-sounds', 'boolean')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.sound',
|
||||
None, 'input-feedback-sounds', 'boolean')
|
||||
|
||||
def set_sound_event_enable(self, flag):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.sound',
|
||||
None,
|
||||
'event-sounds',
|
||||
'boolean', flag)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.sound',
|
||||
None,
|
||||
'event-sounds',
|
||||
'boolean', flag)
|
||||
|
||||
def get_sound_event_enable(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.sound',
|
||||
None, 'event-sounds', 'boolean')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.sound',
|
||||
None, 'event-sounds', 'boolean')
|
||||
|
||||
# enable the login music
|
||||
def set_login_music_enable(self, flag):
|
||||
configdir = self.homedir + '/.config/autostart'
|
||||
desktopfile = '/var/lib/youker-assistant-daemon/autostart/libcanberra-login-sound.desktop'
|
||||
targetfile = configdir + '/libcanberra-login-sound.desktop'
|
||||
|
||||
if flag:
|
||||
if os.path.exists(configdir):
|
||||
pass
|
||||
else:
|
||||
os.makedirs(configdir)
|
||||
shutil.copy(desktopfile, targetfile)
|
||||
else:
|
||||
if os.path.exists(targetfile):
|
||||
os.remove(targetfile)
|
||||
else:
|
||||
pass
|
||||
|
||||
# get enable the login music. need fix text check in 'libcanberra-login-sound.desktop'
|
||||
def get_login_music_enable(self):
|
||||
targetfile = self.homedir + '/.config/autostart/libcanberra-login-sound.desktop'
|
||||
|
||||
if os.path.exists(targetfile):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
# get sound themes & check and bak sounds
|
||||
def get_sound_themes(self):
|
||||
bakDir = '/var/lib/youker-assistant-daemon/sound-theme/'
|
||||
dirs = ('/usr/share/sounds', os.path.join(self.homedir, ".sounds"))
|
||||
filters = ('index.theme', '')
|
||||
valid = utils.check_dirs(dirs, filters, True)
|
||||
valid.sort()
|
||||
|
||||
# check and bak sounds
|
||||
for st in valid:
|
||||
if(os.path.exists(bakDir + st) == False):
|
||||
if(os.path.exists('/usr/share/sounds/' + st)):
|
||||
shutil.copytree('/usr/share/sounds/' + st, bakDir + st)
|
||||
else:
|
||||
shutil.copytree(self.homedir + '.sounds/' + st, bakDir + st)
|
||||
|
||||
return valid
|
||||
|
||||
# get current sound theme
|
||||
def get_sound_theme(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.sound',
|
||||
None, 'theme-name', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.sound',
|
||||
None, 'theme-name', 'string')
|
||||
|
||||
# set sound theme
|
||||
def set_sound_theme(self, theme):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
gstheme = gsettings.get_schema('org.mate.sound')
|
||||
gstheme.set_string('theme-name',theme)
|
||||
else:
|
||||
gstheme = gsettings.get_schema('org.gnome.desktop.sound')
|
||||
gstheme.set_string('theme-name',theme)
|
||||
|
||||
# get sounds in current theme
|
||||
def get_sounds(self):
|
||||
results = []
|
||||
currentTheme = self.get_sound_theme()
|
||||
if(os.path.exists(os.path.join(self.homedir, ".sounds") + currentTheme)):
|
||||
soundDir = os.path.join(self.homedir, ".sounds") + currentTheme
|
||||
elif(os.path.exists('/usr/share/sounds/' + currentTheme)):
|
||||
soundDir = '/usr/share/sounds/' + currentTheme
|
||||
else:
|
||||
return results
|
||||
|
||||
for sound in os.listdir(soundDir + '/stereo'):
|
||||
# pass the link file
|
||||
if(os.path.islink(soundDir + '/stereo/' + sound) == False):
|
||||
results.append(soundDir + '/stereo/' + sound)
|
||||
results.sort()
|
||||
return results
|
||||
|
||||
# replace sound file
|
||||
def replace_sound_file(self, newSoundFile, targetSoundFile):
|
||||
newSoundFile = newSoundFile.encode('utf-8')
|
||||
targetSoundFile = targetSoundFile.encode('utf-8')
|
||||
currentTheme = self.get_sound_theme()
|
||||
if(os.path.exists(os.path.join(self.homedir, ".sounds") + currentTheme)):
|
||||
soundDir = os.path.join(self.homedir, ".sounds") + currentTheme
|
||||
elif(os.path.exists('/usr/share/sounds/' + currentTheme)):
|
||||
soundDir = '/usr/share/sounds/' + currentTheme
|
||||
else:
|
||||
pass
|
||||
|
||||
shutil.copy(newSoundFile, soundDir + '/stereo/' + targetSoundFile)
|
||||
|
||||
# restore sound file
|
||||
def restore_sound_file(self, targetSoundFile):
|
||||
targetSoundFile = targetSoundFile.encode('utf-8')
|
||||
bakDir = '/var/lib/youker-assistant-daemon/sound-theme/'
|
||||
currentTheme = self.get_sound_theme()
|
||||
if(os.path.exists(os.path.join(self.homedir, ".sounds") + currentTheme)):
|
||||
soundDir = os.path.join(self.homedir, ".sounds") + currentTheme
|
||||
elif(os.path.exists('/usr/share/sounds/' + currentTheme)):
|
||||
soundDir = '/usr/share/sounds/' + currentTheme
|
||||
else:
|
||||
pass
|
||||
|
||||
shutil.copy(bakDir + currentTheme + '/stereo/' + targetSoundFile, soundDir + '/stereo/' + targetSoundFile)
|
||||
|
||||
# restore all sound file in current sound theme
|
||||
def restore_all_sound_file(self, soundTheme):
|
||||
bakSoundThemeDir = '/var/lib/youker-assistant-daemon/sound-theme/' + soundTheme
|
||||
if(os.path.exists(os.path.join(self.homedir, ".sounds") + soundTheme)):
|
||||
soundDir = os.path.join(self.homedir, ".sounds") + soundTheme
|
||||
elif(os.path.exists('/usr/share/sounds/' + soundTheme)):
|
||||
soundDir = '/usr/share/sounds/' + soundTheme
|
||||
else:
|
||||
pass
|
||||
|
||||
for soundFile in os.listdir(bakSoundThemeDir + '/stereo'):
|
||||
shutil.copy(bakSoundThemeDir + '/stereo/' + soundFile, soundDir + '/stereo/' + soundFile)
|
||||
|
||||
if __name__ == '__main__':
|
||||
sss = Sound()
|
||||
# print sss.get_sound_themes()
|
||||
# sss.restore_all_sound_file('ubuntu')
|
||||
# print sss.get_login_music_enable()
|
||||
# sss.set_login_music_enable(False)
|
||||
# print sss.get_sound_themes()
|
||||
# print sss.get_sound_theme()
|
||||
print sss.get_sounds()
|
||||
# sss.set_sound_theme('freedesktop')
|
|
@ -0,0 +1,633 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
import gsettings
|
||||
import platform
|
||||
from gi.repository import Gio as gio
|
||||
|
||||
class System():
|
||||
|
||||
desktop = None
|
||||
touchpad_remove = False
|
||||
|
||||
def __init__(self, sysdaemon):
|
||||
self.sysdaemon = sysdaemon
|
||||
self.desktop = os.getenv('XDG_CURRENT_DESKTOP')
|
||||
if self.desktop is None:
|
||||
self.desktop = os.getenv('XDG_SESSION_DESKTOP')
|
||||
release_info = platform.platform()
|
||||
# 20160119
|
||||
if "org.gnome.settings-daemon.peripherals.touchpad" in gio.Settings.list_schemas():
|
||||
self.touchpad_remove = False
|
||||
else:
|
||||
self.touchpad_remove = True
|
||||
# if "15.10-wily" in release_info:
|
||||
# self.touchpad_remove = True
|
||||
|
||||
# -----------------默认值-----------------
|
||||
# Get Default Value
|
||||
def get_default_schema_value(self, schema, key):
|
||||
return gsettings.get_schema_value(schema, key)
|
||||
|
||||
# Set Default Value
|
||||
def set_default_schema_value(self, schema, key, type):
|
||||
#fp = open("/tmp/default.txt", "w")
|
||||
#print >> fp, "--------------"
|
||||
#fp.close()
|
||||
default_value = self.get_default_schema_value(schema, key)
|
||||
if default_value is not None:
|
||||
gsettings.set(schema, None, key, type, default_value)
|
||||
if schema == "org.gnome.desktop.wm.preferences" and key == "button-layout":
|
||||
if default_value == 'close,maximize,minimize:' or default_value == 'close,minimize,maximize:':
|
||||
self.sysdaemon.change_titlebar_position('left')
|
||||
elif default_value == ':minimize,maximize,close':
|
||||
self.sysdaemon.change_titlebar_position('right')
|
||||
else:
|
||||
raise NotImplemented
|
||||
|
||||
# ---------------scrollbars---------------
|
||||
|
||||
# set scrollbars mode overlay
|
||||
def set_scrollbars_mode_overlay(self):
|
||||
return gsettings.set('com.canonical.desktop.interface',
|
||||
None,
|
||||
'scrollbar-mode',
|
||||
'string', 'overlay-auto')
|
||||
|
||||
# set scrollbars mode legacy
|
||||
def set_scrollbars_mode_legacy(self):
|
||||
return gsettings.set('com.canonical.desktop.interface',
|
||||
None,
|
||||
'scrollbar-mode',
|
||||
'string', 'normal')
|
||||
|
||||
# get scrollbars mode
|
||||
def get_scrollbars_mode(self):
|
||||
return gsettings.get('com.canonical.desktop.interface',
|
||||
None, 'scrollbar-mode', 'string')
|
||||
|
||||
# ---------------touchpad---------------
|
||||
|
||||
# enable/disable the touchpad
|
||||
def set_touchpad_enable(self, flag):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.peripherals-touchpad',
|
||||
None,
|
||||
'touchpad-enabled',
|
||||
'boolean', flag)
|
||||
else:
|
||||
# kobe1510
|
||||
if self.touchpad_remove:
|
||||
return False
|
||||
else:
|
||||
return gsettings.set('org.gnome.settings-daemon.peripherals.touchpad',
|
||||
None,
|
||||
'touchpad-enabled',
|
||||
'boolean', flag)
|
||||
|
||||
# get is touchpad enable
|
||||
def get_touchpad_enable(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.peripherals-touchpad',
|
||||
None, 'touchpad-enabled', 'boolean')
|
||||
else:
|
||||
# kobe1510
|
||||
if self.touchpad_remove:
|
||||
return False
|
||||
else:
|
||||
return gsettings.get('org.gnome.settings-daemon.peripherals.touchpad',
|
||||
None, 'touchpad-enabled', 'boolean')
|
||||
|
||||
def set_touchscrolling_mode_disabled(self):
|
||||
# kobe1510
|
||||
if self.touchpad_remove:
|
||||
return gsettings.set('org.gnome.desktop.peripherals.touchpad',
|
||||
None,
|
||||
'scroll-method',
|
||||
'string', 'disabled')
|
||||
else:
|
||||
return gsettings.set('org.gnome.settings-daemon.peripherals.touchpad',
|
||||
None,
|
||||
'scroll-method',
|
||||
'string', 'disabled')
|
||||
|
||||
# set touch scrolling mode edge
|
||||
def set_touchscrolling_mode_edge(self):
|
||||
# kobe1510
|
||||
if self.touchpad_remove:
|
||||
return gsettings.set('org.gnome.desktop.peripherals.touchpad',
|
||||
None,
|
||||
'scroll-method',
|
||||
'string', 'edge-scrolling')
|
||||
else:
|
||||
return gsettings.set('org.gnome.settings-daemon.peripherals.touchpad',
|
||||
None,
|
||||
'scroll-method',
|
||||
'string', 'edge-scrolling')
|
||||
|
||||
# set touch scrolling mode two-finger
|
||||
def set_touchscrolling_mode_twofinger(self):
|
||||
# kobe1510
|
||||
if self.touchpad_remove:
|
||||
return gsettings.set('org.gnome.desktop.peripherals.touchpad',
|
||||
None,
|
||||
'scroll-method',
|
||||
'string', 'two-finger-scrolling')
|
||||
else:
|
||||
return gsettings.set('org.gnome.settings-daemon.peripherals.touchpad',
|
||||
None,
|
||||
'scroll-method',
|
||||
'string', 'two-finger-scrolling')
|
||||
|
||||
# get touchpad scrolling mode
|
||||
def get_touchscrolling_mode(self):
|
||||
# kobe1510
|
||||
if self.touchpad_remove:
|
||||
return gsettings.get('org.gnome.desktop.peripherals.touchpad',
|
||||
None, 'scroll-method', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.settings-daemon.peripherals.touchpad',
|
||||
None, 'scroll-method', 'string')
|
||||
|
||||
#----------------------------mate--------------------------
|
||||
#选择触摸板滚动模式。支持的值有:0 - 禁止,1 - 边界滚动,2 - 双指滚动
|
||||
def set_mate_touchscrolling_mode(self, value):
|
||||
return gsettings.set('org.mate.peripherals-touchpad',
|
||||
None,
|
||||
'scroll-method',
|
||||
'int', value)
|
||||
|
||||
def get_mate_touchscrolling_mode(self):
|
||||
return gsettings.get('org.mate.peripherals-touchpad',
|
||||
None, 'scroll-method', 'int')
|
||||
|
||||
# set touch scrolling use horizontal True/False
|
||||
def set_touchscrolling_use_horizontal(self, flag):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.peripherals-touchpad',
|
||||
None,
|
||||
'horiz-scroll-enabled',
|
||||
'boolean', flag)
|
||||
else:
|
||||
# kobe1510
|
||||
if self.touchpad_remove:
|
||||
return False
|
||||
else:
|
||||
return gsettings.set('org.gnome.settings-daemon.peripherals.touchpad',
|
||||
None,
|
||||
'horiz-scroll-enabled',
|
||||
'boolean', flag)
|
||||
|
||||
# get is touch scrolling use horizontal
|
||||
def get_touchscrolling_use_horizontal(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.peripherals-touchpad',
|
||||
None, 'horiz-scroll-enabled', 'boolean')
|
||||
else:
|
||||
# kobe1510
|
||||
if self.touchpad_remove:
|
||||
return False
|
||||
else:
|
||||
return gsettings.get('org.gnome.settings-daemon.peripherals.touchpad',
|
||||
None, 'horiz-scroll-enabled', 'boolean')
|
||||
|
||||
# ---------------window---------------
|
||||
|
||||
# set window button alignment left
|
||||
def set_window_button_align_left(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
value = gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'button-layout', 'string')
|
||||
if "menu" in value:
|
||||
gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'button-layout',
|
||||
'string', 'close,maximize,minimize:menu')
|
||||
else:
|
||||
gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'button-layout',
|
||||
'string', 'close,maximize,minimize')
|
||||
else:
|
||||
gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'button-layout',
|
||||
'string', 'close,maximize,minimize:')
|
||||
self.sysdaemon.change_titlebar_position("left")
|
||||
#return gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
# None,
|
||||
# 'button-layout',
|
||||
# 'string', 'close,maximize,minimize:')#close,minimize,maximize:
|
||||
|
||||
# set window button alignment right
|
||||
def set_window_button_align_right(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
value = gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'button-layout', 'string')
|
||||
if "menu" in value:
|
||||
gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'button-layout',
|
||||
'string', 'menu:minimize,maximize,close')
|
||||
else:
|
||||
gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'button-layout',
|
||||
'string', ':minimize,maximize,close')
|
||||
else:
|
||||
gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'button-layout',
|
||||
'string', ':minimize,maximize,close')
|
||||
self.sysdaemon.change_titlebar_position("right")
|
||||
#return gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
# None,
|
||||
# 'button-layout',
|
||||
# 'string', ':minimize,maximize,close')
|
||||
|
||||
# get window button alignment
|
||||
def get_window_button_align(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
value = gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'button-layout', 'string')
|
||||
if value == 'close,maximize,minimize:menu' or value == 'close,minimize,maximize:menu' or value == 'close,minimize,maximize:' or value == 'close,maximize,minimize:':
|
||||
return 'left'
|
||||
elif value == 'menu:minimize,maximize,close' or value == 'menu:maximize,minimize,close' or value == ':minimize,maximize,close' or value == ':maximize,minimize,close':
|
||||
return 'right'
|
||||
else:
|
||||
value = gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'button-layout', 'string')
|
||||
if value == 'close,maximize,minimize:' or value == 'close,minimize,maximize:':
|
||||
return 'left'
|
||||
elif value == ':minimize,maximize,close' or value == ':maximize,minimize,close':
|
||||
return 'right'
|
||||
#elif value == 'close,minimize,maximize:':
|
||||
# return 'default'
|
||||
else:
|
||||
return 'custom'
|
||||
|
||||
# set right click menus have icons 菜单带图标 是否可在菜单项旁显示图标。
|
||||
def set_menus_have_icons(self, flag):
|
||||
return gsettings.set('org.gnome.desktop.interface',
|
||||
None,
|
||||
'menus-have-icons',
|
||||
'boolean', flag)
|
||||
|
||||
# get is right click menus have icons
|
||||
def get_menus_have_icons(self):
|
||||
return gsettings.get('org.gnome.desktop.interface',
|
||||
None, 'menus-have-icons', 'boolean')
|
||||
|
||||
#-----------------------窗口控制按钮位置----------------------
|
||||
# get window button
|
||||
#def get_window_button(self):
|
||||
# return ['close,minimize,maximize:', ':minimize,maximize,close'] #左边/右边
|
||||
|
||||
# get current window button
|
||||
#def get_current_window_button(self):
|
||||
# return gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
# None, 'button-layout', 'string')
|
||||
|
||||
# set window button
|
||||
#def set_window_button(self, value):
|
||||
# return gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
# None,
|
||||
# 'button-layout',
|
||||
# 'string', value)
|
||||
|
||||
#-----------------------标题栏鼠标滚轮动作---------------------
|
||||
# get titlebar wheel
|
||||
def get_titlebar_wheel(self):
|
||||
return ['none', 'shade']
|
||||
|
||||
# get current titlebar wheel
|
||||
def get_current_titlebar_wheel(self):
|
||||
return gsettings.get('org.compiz.gwd',
|
||||
None, 'mouse-wheel-action', 'string')
|
||||
|
||||
# set titlebar wheel
|
||||
def set_titlebar_wheel(self, value):
|
||||
return gsettings.set('org.compiz.gwd',
|
||||
None,
|
||||
'mouse-wheel-action',
|
||||
'string', value)
|
||||
|
||||
#-------------------------标题栏双击动作-------------------------
|
||||
# “toggle-shade”卷起/展开窗口,“toggle-maximize”最大化/还原窗口,
|
||||
#“toggle-maximize-horizontally”及“toggle-maximize-vertically”横向及纵向最大化/还原窗口,
|
||||
#“minimize”最小化窗口,“shade”卷起窗口,
|
||||
#“menu”显示窗口菜单,“lower”将窗口降低到所有窗口之下,还有“none”什么也不做。
|
||||
# get titlebar double
|
||||
def get_titlebar_options(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return ['none', 'toggle_maximize', 'toggle_maximize_horizontally', 'toggle_maximize_vertically', 'minimize', 'toggle_shade', 'lower', 'menu', 'last']
|
||||
else:
|
||||
return ['none', 'toggle-maximize', 'toggle-maximize-horizontally', 'toggle-maximize-vertically', 'minimize', 'toggle-shade', 'lower', 'menu', 'last']
|
||||
|
||||
# get current titlebar double
|
||||
def get_current_titlebar_double(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'action-double-click-titlebar', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'action-double-click-titlebar', 'string')
|
||||
|
||||
# set titlebar double
|
||||
def set_titlebar_double(self, value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'action-double-click-titlebar',
|
||||
'string', value)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'action-double-click-titlebar',
|
||||
'string', value)
|
||||
|
||||
#-------------------------标题栏中键动作-------------------------
|
||||
# get titlebar middle
|
||||
def get_titlebar_middle(self):
|
||||
return ['none', 'toggle-maximize', 'toggle-maximize-horizontally', 'toggle-maximize-vertically', 'minimize', 'toggle-shade', 'lower', 'menu', 'last']
|
||||
|
||||
# get current titlebar middle
|
||||
def get_current_titlebar_middle(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'action-middle-click-titlebar', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'action-middle-click-titlebar', 'string')
|
||||
|
||||
# set titlebar middle
|
||||
def set_titlebar_middle(self, value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'action-middle-click-titlebar',
|
||||
'string', value)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'action-middle-click-titlebar',
|
||||
'string', value)
|
||||
|
||||
#-------------------------标题栏右键动作-------------------------
|
||||
# get titlebar right
|
||||
def get_titlebar_right(self):
|
||||
return ['none', 'toggle-maximize', 'toggle-maximize-horizontally', 'toggle-maximize-vertically', 'minimize', 'toggle-shade', 'lower', 'menu', 'last']
|
||||
|
||||
# get current titlebar right
|
||||
def get_current_titlebar_right(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'action-right-click-titlebar', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'action-right-click-titlebar', 'string')
|
||||
|
||||
# set titlebar right
|
||||
def set_titlebar_right(self, value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'action-right-click-titlebar',
|
||||
'string', value)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'action-right-click-titlebar',
|
||||
'string', value)
|
||||
|
||||
def get_current_idle_delay(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.session',
|
||||
None, 'idle-delay', 'int')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.session',
|
||||
None, 'idle-delay', 'uint')
|
||||
|
||||
def set_current_idle_delay(self, value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
gsettings.set('org.mate.session',
|
||||
None,
|
||||
'idle-delay',
|
||||
'int', value)
|
||||
else:
|
||||
gsettings.set('org.gnome.desktop.session',
|
||||
None,
|
||||
'idle-delay',
|
||||
'uint', value)
|
||||
|
||||
def get_lock_enabled(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.screensaver',
|
||||
None, 'lock-enabled', 'boolean')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.screensaver',
|
||||
None, 'lock-enabled', 'boolean')
|
||||
|
||||
def set_lock_enabled(self, value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
gsettings.set('org.mate.screensaver',
|
||||
None,
|
||||
'lock-enabled',
|
||||
'boolean', value)
|
||||
else:
|
||||
gsettings.set('org.gnome.desktop.screensaver',
|
||||
None,
|
||||
'lock-enabled',
|
||||
'boolean', value)
|
||||
|
||||
def get_current_lock_delay(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.screensaver',
|
||||
None, 'lock-delay', 'int')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.screensaver',
|
||||
None, 'lock-delay', 'uint')
|
||||
|
||||
def set_current_lock_delay(self, value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
gsettings.set('org.mate.screensaver',
|
||||
None,
|
||||
'lock-delay',
|
||||
'int', value)
|
||||
else:
|
||||
gsettings.set('org.gnome.desktop.screensaver',
|
||||
None,
|
||||
'lock-delay',
|
||||
'uint', value)
|
||||
|
||||
def get_current_critical_low(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.power-manager',
|
||||
None, 'action-critical-battery', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.settings-daemon.plugins.power',
|
||||
None, 'critical-battery-action', 'string')
|
||||
|
||||
def set_current_critical_low(self, value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
gsettings.set('org.mate.power-manager',
|
||||
None,
|
||||
'action-critical-battery',
|
||||
'string', value)
|
||||
else:
|
||||
gsettings.set('org.gnome.settings-daemon.plugins.power',
|
||||
None,
|
||||
'critical-battery-action',
|
||||
'string', value)
|
||||
|
||||
def get_current_lid_battery(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.power-manager',
|
||||
None, 'button-lid-battery', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.settings-daemon.plugins.power',
|
||||
None, 'lid-close-battery-action', 'string')
|
||||
|
||||
def set_current_lid_battery(self, value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
gsettings.set('org.mate.power-manager',
|
||||
None,
|
||||
'button-lid-battery',
|
||||
'string', value)
|
||||
else:
|
||||
gsettings.set('org.gnome.settings-daemon.plugins.power',
|
||||
None,
|
||||
'lid-close-battery-action',
|
||||
'string', value)
|
||||
|
||||
def get_current_lid_ac(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.power-manager',
|
||||
None, 'button-lid-ac', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.settings-daemon.plugins.power',
|
||||
None, 'lid-close-ac-action', 'string')
|
||||
|
||||
def set_current_lid_ac(self, value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
gsettings.set('org.mate.power-manager',
|
||||
None,
|
||||
'button-lid-ac',
|
||||
'string', value)
|
||||
else:
|
||||
gsettings.set('org.gnome.settings-daemon.plugins.power',
|
||||
None,
|
||||
'lid-close-ac-action',
|
||||
'string', value)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def get_current_sleep_timeout_display_battery(self):
|
||||
return gsettings.get('org.mate.power-manager',
|
||||
None, 'sleep-display-battery', 'int')
|
||||
|
||||
def set_current_sleep_timeout_display_battery(self, value):
|
||||
gsettings.set('org.mate.power-manager',
|
||||
None,
|
||||
'sleep-display-battery',
|
||||
'int', value)
|
||||
|
||||
def get_current_sleep_timeout_display_ac(self):
|
||||
return gsettings.get('org.mate.power-manager',
|
||||
None, 'sleep-display-ac', 'int')
|
||||
|
||||
def set_current_sleep_timeout_display_ac(self, value):
|
||||
gsettings.set('org.mate.power-manager',
|
||||
None,
|
||||
'sleep-display-ac',
|
||||
'int', value)
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
def get_current_sleep_timeout_battery(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.power-manager',
|
||||
None, 'sleep-computer-battery', 'int')
|
||||
else:
|
||||
return gsettings.get('org.gnome.settings-daemon.plugins.power',
|
||||
None, 'sleep-inactive-battery-timeout', 'int')
|
||||
|
||||
def set_current_sleep_timeout_battery(self, value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
gsettings.set('org.mate.power-manager',
|
||||
None,
|
||||
'sleep-computer-battery',
|
||||
'int', value)
|
||||
else:
|
||||
gsettings.set('org.gnome.settings-daemon.plugins.power',
|
||||
None,
|
||||
'sleep-inactive-battery-timeout',
|
||||
'int', value)
|
||||
|
||||
def get_current_sleep_timeout_ac(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.power-manager',
|
||||
None, 'sleep-computer-ac', 'int')
|
||||
else:
|
||||
return gsettings.get('org.gnome.settings-daemon.plugins.power',
|
||||
None, 'sleep-inactive-ac-timeout', 'int')
|
||||
|
||||
def set_current_sleep_timeout_ac(self, value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
gsettings.set('org.mate.power-manager',
|
||||
None,
|
||||
'sleep-computer-ac',
|
||||
'int', value)
|
||||
else:
|
||||
gsettings.set('org.gnome.settings-daemon.plugins.power',
|
||||
None,
|
||||
'sleep-inactive-ac-timeout',
|
||||
'int', value)
|
||||
|
||||
if __name__ == '__main__':
|
||||
gsettings.set('org.compiz.gwd',None,'mouse-wheel-action', 'string', 'shade')
|
||||
# sss = System(None)
|
||||
# print sss.set_titlebar_wheel('shade')
|
||||
|
||||
#aa = sss.get_default_schema_value('org.gnome.settings-daemon.peripherals.touchpad', 'touchpad-enabled')
|
||||
#print aa#True
|
||||
#sss.set_default_schema_value('org.gnome.settings-daemon.peripherals.touchpad', 'touchpad-enabled', 'boolean')
|
||||
#bb = sss.get_default_schema_value('com.canonical.desktop.interface', 'scrollbar-mode')
|
||||
#print bb#overlay-auto
|
||||
#sss.set_default_schema_value('com.canonical.desktop.interface', 'scrollbar-mode', 'string')
|
||||
#cc = sss.get_default_schema_value('org.gnome.settings-daemon.peripherals.touchpad', 'scroll-method')
|
||||
#print cc#two-finger-scrolling
|
||||
#sss.set_default_schema_value('org.gnome.settings-daemon.peripherals.touchpad', 'scroll-method', 'string')
|
||||
# dd = sss.get_default_schema_value('org.gnome.settings-daemon.peripherals.touchpad', 'horiz-scroll-enabled')
|
||||
# print dd#True
|
||||
#sss.set_default_schema_value('org.gnome.settings-daemon.peripherals.touchpad', 'horiz-scroll-enabled', 'boolean')
|
||||
|
||||
#print sss.get_scrollbars_mode()
|
||||
#print sss.get_touchpad_enable()
|
||||
#print sss.get_touchscrolling_mode()
|
||||
#print sss.get_touchscrolling_use_horizontal()
|
||||
#print sss.get_window_button_align()
|
||||
#print sss.get_menus_have_icons()
|
||||
# sss.set_menus_have_icons(True)
|
||||
# sss.set_touchpad_enable(True)
|
||||
#sss.set_scrollbars_mode_overlay()
|
||||
# sss.set_scrollbars_mode_legacy()
|
||||
# sss.set_touchscrolling_mode_edge()
|
||||
#sss.set_touchscrolling_mode_twofinger()
|
||||
#sss.set_touchscrolling_use_horizontal(True)
|
||||
# sss.set_window_button_align_left()
|
||||
# sss.set_window_button_align_right()
|
|
@ -0,0 +1,446 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
import gsettings
|
||||
import utils
|
||||
|
||||
class Theme:
|
||||
homedir = ''
|
||||
desktop = None
|
||||
|
||||
def __init__(self):
|
||||
self.homedir = utils.get_home_dir()
|
||||
self.desktop = os.getenv('XDG_CURRENT_DESKTOP')
|
||||
if self.desktop is None:
|
||||
self.desktop = os.getenv('XDG_SESSION_DESKTOP')
|
||||
|
||||
# ---------------themes---------------
|
||||
def set_ubuntukylin_default_setting(self, schema, title, key, type, default_value):
|
||||
if title == 'unity':
|
||||
return gsettings.set(schema, '/org/compiz/profiles/unity/plugins/unityshell/', key, type, default_value)
|
||||
else:
|
||||
return gsettings.set(schema, None, key, type, default_value)
|
||||
|
||||
# -----------------默认值-----------------
|
||||
# Get Default Value
|
||||
def get_default_schema_value(self, schema, key):
|
||||
default_value = gsettings.get_schema_value(schema, key)
|
||||
if self.desktop != "mate" and self.desktop != "MATE":
|
||||
if (default_value in (None, '') and schema == 'org.gnome.nautilus.desktop' and key == 'font'):
|
||||
default_value = 'Ubuntu 11'
|
||||
return default_value
|
||||
|
||||
# Set Default Value
|
||||
def set_default_schema_value(self, schema, key, type):
|
||||
default_value = self.get_default_schema_value(schema, key)
|
||||
if (default_value in (None, '') and schema == 'org.gnome.nautilus.desktop' and key == 'font'):
|
||||
default_value = 'Ubuntu 11'
|
||||
if default_value is not None:
|
||||
return gsettings.set(schema, None, key, type, default_value)
|
||||
else:
|
||||
raise NotImplemented
|
||||
# ----------------------------------
|
||||
|
||||
# get themes
|
||||
def get_themes(self):
|
||||
dirs = ('/usr/share/themes', os.path.join(self.homedir, ".themes"))
|
||||
filters = ('gtk-2.0', 'gtk-3.0', 'metacity-1')
|
||||
valid = utils.check_dirs(dirs, filters, True)
|
||||
valid.sort()
|
||||
return valid
|
||||
|
||||
# get current theme
|
||||
def get_theme(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.interface',
|
||||
None, 'gtk-theme', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.interface',
|
||||
None, 'gtk-theme', 'string')
|
||||
|
||||
# set GTK theme and window theme
|
||||
def set_theme(self, theme):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
gstheme = gsettings.get_schema('org.mate.interface')
|
||||
gstheme.set_string('gtk-theme',theme)
|
||||
else:
|
||||
gstheme = gsettings.get_schema('org.gnome.desktop.interface')
|
||||
gstheme.set_string('gtk-theme',theme)
|
||||
_gstheme = gsettings.get_schema('org.gnome.desktop.wm.preferences')
|
||||
_gstheme.set_string('theme',theme)
|
||||
|
||||
#------------------------窗口主题设置
|
||||
# get window theme
|
||||
def get_window_themes(self):
|
||||
dirs = ('/usr/share/themes', os.path.join(self.homedir, ".themes"))
|
||||
filters = ['metacity-1']
|
||||
valid = utils.check_dirs(dirs, filters, True)
|
||||
valid.sort()
|
||||
return valid
|
||||
|
||||
# get current window theme
|
||||
def get_current_window_theme(self):
|
||||
return gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'theme', 'string')
|
||||
|
||||
# set window theme
|
||||
def set_window_theme(self, theme):
|
||||
return gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'theme',
|
||||
'string', theme)
|
||||
|
||||
|
||||
|
||||
# get icon themes
|
||||
def get_icon_themes(self):
|
||||
dirs = ('/usr/share/icons', os.path.join(self.homedir, ".icons"))
|
||||
|
||||
'''filters: if use only one filter string,
|
||||
the 'for' block in check_dirs() will split the filter string to single chars...'''
|
||||
filters = ('cursors', '#')
|
||||
valid = utils.check_dirs(dirs, filters, False)
|
||||
valid.sort()
|
||||
return valid
|
||||
|
||||
# get current icon theme
|
||||
def get_icon_theme(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.interface',
|
||||
None, 'icon-theme', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.interface',
|
||||
None, 'icon-theme', 'string')
|
||||
|
||||
# set icon theme
|
||||
def set_icon_theme(self, theme):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
gstheme = gsettings.get_schema('org.mate.interface')
|
||||
gstheme.set_string('icon-theme',theme)
|
||||
else:
|
||||
gstheme = gsettings.get_schema('org.gnome.desktop.interface')
|
||||
gstheme.set_string('icon-theme',theme)
|
||||
|
||||
# get cursor themes
|
||||
def get_cursor_themes(self):
|
||||
dirs = ('/usr/share/icons', os.path.join(self.homedir, ".icons"))
|
||||
|
||||
'''filters: if use only one filter string,
|
||||
the 'for' block in check_dirs() will split the filter string to single chars...'''
|
||||
filters = ('cursors', '')
|
||||
valid = utils.check_dirs(dirs, filters, True)
|
||||
valid.sort()
|
||||
return valid
|
||||
|
||||
# get current cursor theme
|
||||
def get_cursor_theme(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.peripherals-mouse',
|
||||
None, 'cursor-theme', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.interface',
|
||||
None, 'cursor-theme', 'string')
|
||||
|
||||
# set cursor theme
|
||||
def set_cursor_theme(self, theme):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
gstheme = gsettings.get_schema('org.mate.peripherals-mouse')
|
||||
gstheme.set_string('cursor-theme', theme)
|
||||
else:
|
||||
gstheme = gsettings.get_schema('org.gnome.desktop.interface')
|
||||
gstheme.set_string('cursor-theme', theme)
|
||||
|
||||
def set_cursor_theme_with_root(self, theme):
|
||||
try :
|
||||
fd = open('/usr/share/icons/default/index.theme','w')
|
||||
fd.write('[Icon Theme]\n')
|
||||
fd.write('Inherits=' + theme + '\n')
|
||||
fd.close()
|
||||
return True
|
||||
except Exception,e :
|
||||
return False
|
||||
|
||||
# get cursor size
|
||||
def get_cursor_size(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.peripherals-mouse',
|
||||
None, 'cursor-size', 'int')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.interface',
|
||||
None, 'cursor-size', 'int')
|
||||
|
||||
# set cursor size
|
||||
def set_cursor_size(self, size):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
gstheme = gsettings.get_schema('org.mate.peripherals-mouse')
|
||||
gstheme.set_int('cursor-size', size)
|
||||
else:
|
||||
gstheme = gsettings.get_schema('org.gnome.desktop.interface')
|
||||
gstheme.set_int('cursor-size', size)
|
||||
|
||||
|
||||
|
||||
# ---------------fonts---------------
|
||||
|
||||
# get font
|
||||
def get_font(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.interface',
|
||||
None, 'font-name', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.interface',
|
||||
None, 'font-name', 'string')
|
||||
|
||||
# set font
|
||||
def set_font(self, font):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.interface',
|
||||
None,
|
||||
'font-name',
|
||||
'string', font)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.interface',
|
||||
None,
|
||||
'font-name',
|
||||
'string', font)
|
||||
|
||||
# get desktop font
|
||||
def get_desktop_font(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.caja.desktop',
|
||||
None, 'font', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.nautilus.desktop',
|
||||
None, 'font', 'string')
|
||||
|
||||
# set desktop font
|
||||
def set_desktop_font(self, font):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.caja.desktop',
|
||||
None,
|
||||
'font',
|
||||
'string', font)
|
||||
else:
|
||||
return gsettings.set('org.gnome.nautilus.desktop',
|
||||
None,
|
||||
'font',
|
||||
'string', font)
|
||||
|
||||
# get document font
|
||||
def get_document_font(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.interface',
|
||||
None, 'document-font-name', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.interface',
|
||||
None, 'document-font-name', 'string')
|
||||
|
||||
# set document font
|
||||
def set_document_font(self, font):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.interface',
|
||||
None,
|
||||
'document-font-name',
|
||||
'string', font)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.interface',
|
||||
None,
|
||||
'document-font-name',
|
||||
'string', font)
|
||||
|
||||
# get monospace font
|
||||
def get_monospace_font(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.interface',
|
||||
None, 'monospace-font-name', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.interface',
|
||||
None, 'monospace-font-name', 'string')
|
||||
|
||||
# set monospace font (use this func to change document font in ubuntu)
|
||||
def set_monospace_font(self, font):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.interface',
|
||||
None,
|
||||
'monospace-font-name',
|
||||
'string', font)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.interface',
|
||||
None,
|
||||
'monospace-font-name',
|
||||
'string', font)
|
||||
|
||||
# get window title font
|
||||
def get_window_title_font(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'titlebar-font', 'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.desktop.wm.preferences',
|
||||
None, 'titlebar-font', 'string')
|
||||
|
||||
# set window title font
|
||||
def set_window_title_font(self, font):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'titlebar-font',
|
||||
'string', font)
|
||||
else:
|
||||
return gsettings.set('org.gnome.desktop.wm.preferences',
|
||||
None,
|
||||
'titlebar-font',
|
||||
'string', font)
|
||||
|
||||
# get font zoom
|
||||
def get_font_zoom(self):
|
||||
return gsettings.get('org.gnome.desktop.interface',
|
||||
None, 'text-scaling-factor', 'double')
|
||||
|
||||
# set font zoom
|
||||
def set_font_zoom(self, zoom):
|
||||
return gsettings.set('org.gnome.desktop.interface',
|
||||
None,
|
||||
'text-scaling-factor',
|
||||
'double', zoom)
|
||||
|
||||
# -------------------------平滑性----------------------------------
|
||||
# get all hinting value. none:'No hinting',slight:'Basic',medium:'Moderate',full:'Maximum'
|
||||
def get_all_hinting(self):
|
||||
return ['none', 'slight', 'medium', 'full']
|
||||
|
||||
# get current hinting
|
||||
def get_hinting(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.font-rendering',
|
||||
None,
|
||||
'hinting',
|
||||
'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.settings-daemon.plugins.xsettings',
|
||||
None,
|
||||
'hinting',
|
||||
'string')
|
||||
|
||||
# set hinting
|
||||
def set_hinting(self, value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.font-rendering',
|
||||
None,
|
||||
'hinting',
|
||||
'string', value)
|
||||
else:
|
||||
return gsettings.set('org.gnome.settings-daemon.plugins.xsettings',
|
||||
None,
|
||||
'hinting',
|
||||
'string', value)
|
||||
|
||||
# -------------------------反锯齿----------------------------------
|
||||
# get all antialiasing value. none:'No antialiasing', grayscale:'Standard grayscale antialiasing',rgba:'Subpixel antialiasing (LCD screens only)'
|
||||
def get_all_antialiasing(self):
|
||||
return ['none', 'grayscale', 'rgba']
|
||||
|
||||
# get current antialiasing
|
||||
def get_antialiasing(self):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.get('org.mate.font-rendering',
|
||||
None,
|
||||
'antialiasing',
|
||||
'string')
|
||||
else:
|
||||
return gsettings.get('org.gnome.settings-daemon.plugins.xsettings',
|
||||
None,
|
||||
'antialiasing',
|
||||
'string')
|
||||
|
||||
# set antialiasing
|
||||
def set_antialiasing(self,value):
|
||||
if self.desktop == "mate" or self.desktop == "MATE" or self.desktop == "ukui" or self.desktop == "UKUI":
|
||||
return gsettings.set('org.mate.font-rendering',
|
||||
None,
|
||||
'antialiasing',
|
||||
'string', value)
|
||||
else:
|
||||
return gsettings.set('org.gnome.settings-daemon.plugins.xsettings',
|
||||
None,
|
||||
'antialiasing',
|
||||
'string', value)
|
||||
|
||||
if __name__ == '__main__':
|
||||
ttt = Theme()
|
||||
# print ttt.get_window_theme()
|
||||
# print ttt.get_current_window_theme()
|
||||
# print ttt.set_window_theme('Crux')
|
||||
# print ttt.get_current_hinting()
|
||||
# print ttt.get_current_antialiasing()
|
||||
# print ttt.set_hinting('none')
|
||||
# print ttt.set_antialiasing('none')
|
||||
# print ttt.get_font()
|
||||
# print ttt.set_font('Ubuntu 14')
|
||||
# print ttt.get_font_zoom()
|
||||
# ttt.set_font_zoom(1.0)
|
||||
#ttt.set_monospace_font('Ubuntu Mono 13')
|
||||
#print ttt.get_monospace_font()
|
||||
|
||||
#aa = ttt.get_default_schema_value('org.gnome.nautilus.desktop', 'font')
|
||||
#print aa
|
||||
#ttt.set_default_schema_value('org.gnome.nautilus.desktop', 'font', 'string')
|
||||
#aa = ttt.get_default_schema_value('org.gnome.settings-daemon.plugins.xsettings', 'hinting')
|
||||
#print aa
|
||||
#ttt.set_default_schema_value('org.gnome.settings-daemon.plugins.xsettings', 'hinting', 'string')
|
||||
#bb = ttt.get_default_schema_value('org.gnome.settings-daemon.plugins.xsettings', 'antialiasing')
|
||||
#print bb
|
||||
|
||||
aa = ttt.get_default_schema_value('org.gnome.desktop.interface', 'cursor-size')
|
||||
print aa
|
||||
bb = ttt.get_cursor_size()
|
||||
print bb
|
||||
ttt.set_default_schema_value('org.gnome.desktop.interface', 'cursor-size', 'int')
|
||||
|
||||
#aa = ttt.get_default_schema_value('org.gnome.desktop.interface', 'font-name')
|
||||
#print aa
|
||||
# ttt.set_default_schema_value('org.gnome.desktop.interface', 'font-name', 'string')
|
||||
# print ttt.get_theme()
|
||||
# print ttt.get_icon_theme()
|
||||
# print ttt.get_cursor_theme()
|
||||
# print ttt.get_cursor_size()
|
||||
# ttt.set_font('Ubuntu 11')
|
||||
# print ttt.get_document_font()
|
||||
# ttt.set_document_font('Sans 15')
|
||||
# ttt.set_window_title_font('Ubuntu Bold 11')
|
||||
# print ttt.get_font()
|
||||
# ttt.set_desktop_font('Ubuntu 11')
|
||||
# print ttt.get_desktop_font()
|
||||
# print ttt.get_document_font()
|
||||
# print ttt.get_window_title_font()
|
||||
# themes = ttt.get_themes()
|
||||
# print themes
|
||||
# print ttt.get_theme()
|
||||
# ttt.set_theme('ubuntukylin-theme')
|
||||
# ttt.set_theme('Radiance')
|
||||
# ttt.set_theme('Ambiance')
|
||||
# ttt.set_theme('HighContrast')
|
||||
# iconthemes = ttt.get_icon_themes()
|
||||
# print iconthemes
|
||||
# ttt.set_icon_theme('ubuntukylin-icon-theme')
|
||||
# cursorthemes = ttt.get_cursor_themes()
|
||||
# print cursorthemes
|
||||
# print ttt.get_cursor_theme()
|
||||
# ttt.set_cursor_theme(cursorthemes[1])
|
||||
# ttt.set_cursor_size(24)
|
|
@ -0,0 +1,451 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
import gsettings
|
||||
from compizsettings import CompizSetting
|
||||
|
||||
class Unity:
|
||||
'''if compiz: key is icon_size; else if gsettins: key is icon-size'''
|
||||
desktop = None
|
||||
|
||||
def __init__(self):
|
||||
self.desktop = os.getenv('XDG_CURRENT_DESKTOP')
|
||||
if self.desktop is None:
|
||||
self.desktop = os.getenv('XDG_SESSION_DESKTOP')
|
||||
# self.setting = CompizSetting("%s.%s" % (name, key))
|
||||
|
||||
# ---------------launcher---------------
|
||||
# -----------------默认值-----------------
|
||||
# Get Default Value
|
||||
def get_default_schema_value(self, name, key):
|
||||
compizsetting = CompizSetting("%s.%s" % (name, key))
|
||||
return compizsetting.get_schema_value()
|
||||
|
||||
# Set Default Value min=32, max=64, step=16, key="unityshell.icon_size"
|
||||
#def set_default_schema_value(self, key, name, type, value):
|
||||
def set_default_schema_value(self, key, type, value):
|
||||
#default_value = self.get_default_schema_value(name, key)
|
||||
#if default_value is not None:
|
||||
return gsettings.set('org.compiz.unityshell',
|
||||
'/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
key, type, value)
|
||||
#else:
|
||||
# raise NotImplemented
|
||||
|
||||
# launcher auto hide mode, True/False
|
||||
def set_launcher_autohide(self, flag):
|
||||
return gsettings.set('org.compiz.unityshell',
|
||||
'/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
'launcher-hide-mode',
|
||||
'int', flag)
|
||||
|
||||
# get launcher auto hide mode
|
||||
def get_launcher_autohide(self):
|
||||
try:
|
||||
value = gsettings.get('org.compiz.unityshell',
|
||||
'/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
'launcher-hide-mode', 'int')
|
||||
if value == 0:
|
||||
return False
|
||||
elif value == 1:
|
||||
return True
|
||||
else:
|
||||
return None
|
||||
except Exception, e:
|
||||
return False
|
||||
|
||||
# launcher icon size 32-64
|
||||
def set_launcher_icon_size(self, size):
|
||||
return gsettings.set('org.compiz.unityshell',
|
||||
'/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
'icon-size',
|
||||
'int', size)
|
||||
|
||||
# get launcher icon size
|
||||
def get_launcher_icon_size(self):
|
||||
try:
|
||||
return gsettings.get('org.compiz.unityshell',
|
||||
'/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
'icon-size', 'int')
|
||||
except Exception, e:
|
||||
return 0
|
||||
|
||||
# launcher 'show desktop' icon True/False
|
||||
def set_launcher_have_showdesktopicon(self, flag):
|
||||
launcher = gsettings.get_schema('com.canonical.Unity.Launcher')
|
||||
icons = launcher.get_strv('favorites')
|
||||
desktop = 'unity://desktop-icon'
|
||||
if flag == True:
|
||||
if desktop not in icons:
|
||||
icons.append(desktop)
|
||||
launcher.set_strv('favorites', icons)
|
||||
else:
|
||||
if desktop in icons:
|
||||
icons.remove(desktop)
|
||||
launcher.set_strv('favorites', icons)
|
||||
|
||||
# get is launcher have 'show desktop' icon
|
||||
def get_launcher_have_showdesktopicon(self):
|
||||
launcher = gsettings.get_schema('com.canonical.Unity.Launcher')
|
||||
icons = launcher.get_strv('favorites')
|
||||
desktop = 'unity://desktop-icon'
|
||||
if desktop in icons:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def get_default_launcher_have_showdesktopicon(self):
|
||||
return self.get_launcher_have_showdesktopicon()
|
||||
|
||||
def set_default_launcher_have_showdesktopicon(self):
|
||||
self.set_launcher_have_showdesktopicon(True)
|
||||
|
||||
|
||||
|
||||
#add by kobe
|
||||
# 透明度
|
||||
def get_launcher_transparency(self):
|
||||
try:
|
||||
return gsettings.get('org.compiz.unityshell',
|
||||
'/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
'launcher-opacity', 'double')
|
||||
except Exception, e:
|
||||
return 0.0
|
||||
|
||||
# 'min' : 0.2, # TODO : Check these min max. Most prolly wrong.
|
||||
# 'max' : 1.0, # But fine since they are ignored anyway.
|
||||
# 'ticks' : [(0.666, Gtk.PositionType.BOTTOM, None)]
|
||||
def set_launcher_transparency(self, opacity):
|
||||
return gsettings.set('org.compiz.unityshell',
|
||||
'/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
'launcher-opacity',
|
||||
'double', opacity)
|
||||
|
||||
# 图标背景
|
||||
def get_all_launcher_icon_colourings(self):
|
||||
# return ['0:0', '1:1', '2:2', '3:3', '4:4']
|
||||
return ['all programs', 'only run app', 'no coloring', 'edge coloring', 'each workspace alternating coloring']
|
||||
|
||||
def get_launcher_icon_colouring(self):
|
||||
try:
|
||||
return gsettings.get('org.compiz.unityshell',
|
||||
'/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
'backlight-mode', 'int')
|
||||
except Exception, e:
|
||||
return 0
|
||||
|
||||
# 'map' : {0:0,1:1,2:2,3:3,4:4} 0:所有程序,1:仅打开的应用程序,2:不着色,3:边缘着色,4:每个工作区交替着色
|
||||
def set_launcher_icon_colouring(self, colouring):
|
||||
return gsettings.set('org.compiz.unityshell',
|
||||
'/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
'backlight-mode',
|
||||
'int', colouring)
|
||||
|
||||
def get_all_launcher_position(self):
|
||||
return ['Left', 'Bottom']
|
||||
|
||||
def get_current_launcher_position(self):
|
||||
return gsettings.get('com.canonical.Unity.Launcher',
|
||||
None,
|
||||
'launcher-position',
|
||||
'string')
|
||||
|
||||
def set_launcher_position(self, position):
|
||||
return gsettings.set('com.canonical.Unity.Launcher',
|
||||
None,
|
||||
'launcher-position',
|
||||
'string', position)
|
||||
|
||||
#Dash背景模糊类型
|
||||
def get_dash_blur_experimental(self):
|
||||
try:
|
||||
return gsettings.get('org.compiz.unityshell',
|
||||
'/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
'dash-blur-experimental', 'int')
|
||||
except Exception, e:
|
||||
return 0
|
||||
|
||||
# 活动模糊smart: 2 静态模糊static:1 非模糊0
|
||||
def set_dash_blur_experimental(self, blur):
|
||||
return gsettings.set('org.compiz.unityshell',
|
||||
'/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
'dash-blur-experimental',
|
||||
'int', blur)
|
||||
|
||||
#面板菜单透明度
|
||||
def get_panel_transparency(self):
|
||||
try:
|
||||
return gsettings.get('org.compiz.unityshell',
|
||||
'/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
'panel-opacity', 'double')
|
||||
except Exception, e:
|
||||
return 0.0
|
||||
|
||||
# 'min' : 0.2, # TODO : Check these min max. Most prolly wrong.
|
||||
# 'max' : 8.0, # But fine since they are ignored anyway.
|
||||
# 'ticks' : [(0.666, Gtk.PositionType.BOTTOM, None)]
|
||||
def set_panel_transparency(self, opacity):
|
||||
return gsettings.set('org.compiz.unityshell',
|
||||
'/org/compiz/profiles/unity/plugins/unityshell/',
|
||||
'panel-opacity',
|
||||
'double', opacity)
|
||||
|
||||
#日期时间格式
|
||||
def get_all_time_format(self):
|
||||
return ['locale-default', '12-hour' , '24-hour', 'custom']
|
||||
|
||||
def get_time_format(self):
|
||||
# if self.desktop == "mate":
|
||||
# return gsettings.get('org.mate.panel',
|
||||
# '/org/mate/panel/objects/clock/prefs/',
|
||||
# 'format',
|
||||
# 'string')
|
||||
# else:
|
||||
return gsettings.get('com.canonical.indicator.datetime',
|
||||
None,
|
||||
'time-format',
|
||||
'string')
|
||||
|
||||
def set_time_format(self, format):
|
||||
# if self.desktop == "mate":
|
||||
# return gsettings.set('org.mate.panel',
|
||||
# '/org/mate/panel/objects/clock/prefs/',
|
||||
# 'format',
|
||||
# 'string', format)
|
||||
# else:
|
||||
return gsettings.set('com.canonical.indicator.datetime',
|
||||
None,
|
||||
'time-format',
|
||||
'string', format)
|
||||
# 秒
|
||||
def get_show_seconds(self):
|
||||
return gsettings.get('com.canonical.indicator.datetime',
|
||||
None,
|
||||
'show-seconds',
|
||||
'boolean')
|
||||
|
||||
def set_show_seconds(self, flag):
|
||||
return gsettings.set('com.canonical.indicator.datetime',
|
||||
None,
|
||||
'show-seconds',
|
||||
'boolean', flag)
|
||||
|
||||
#星期
|
||||
def get_show_week(self):
|
||||
return gsettings.get('com.canonical.indicator.datetime',
|
||||
None,
|
||||
'show-day',
|
||||
'boolean')
|
||||
|
||||
def set_show_week(self, flag):
|
||||
return gsettings.set('com.canonical.indicator.datetime',
|
||||
None,
|
||||
'show-day',
|
||||
'boolean', flag)
|
||||
|
||||
#日期
|
||||
def get_show_date(self):
|
||||
return gsettings.get('com.canonical.indicator.datetime',
|
||||
None,
|
||||
'show-date',
|
||||
'boolean')
|
||||
|
||||
def set_show_date(self, flag):
|
||||
return gsettings.set('com.canonical.indicator.datetime',
|
||||
None,
|
||||
'show-date',
|
||||
'boolean', flag)
|
||||
|
||||
# 电源
|
||||
# present:电源总是可见 charge:当机器充电/放电时可见 never:总是不可见
|
||||
def get_all_power_icon_policy(self):
|
||||
return ['present', 'charge', 'never']
|
||||
|
||||
def get_power_icon_policy(self):
|
||||
return gsettings.get('com.canonical.indicator.power',
|
||||
None,
|
||||
'icon-policy',
|
||||
'string')
|
||||
|
||||
def set_power_icon_policy(self, flag):
|
||||
return gsettings.set('com.canonical.indicator.power',
|
||||
None,
|
||||
'icon-policy',
|
||||
'string', flag)
|
||||
|
||||
#电源时间
|
||||
def get_show_power_time(self):
|
||||
return gsettings.get('com.canonical.indicator.power',
|
||||
None,
|
||||
'show-time',
|
||||
'boolean')
|
||||
|
||||
def set_show_power_time(self, flag):
|
||||
return gsettings.set('com.canonical.indicator.power',
|
||||
None,
|
||||
'show-time',
|
||||
'boolean', flag)
|
||||
|
||||
#电源百分比
|
||||
def get_show_power_percentage(self):
|
||||
return gsettings.get('com.canonical.indicator.power',
|
||||
None,
|
||||
'show-percentage',
|
||||
'boolean')
|
||||
|
||||
def set_show_power_percentage(self, flag):
|
||||
return gsettings.set('com.canonical.indicator.power',
|
||||
None,
|
||||
'show-percentage',
|
||||
'boolean', flag)
|
||||
|
||||
#-----------------mate----------------------------
|
||||
def set_mate_panel_icon_size(self, position, size):
|
||||
if position == "top":
|
||||
return gsettings.set('org.mate.panel.toplevel',
|
||||
'/org/mate/panel/toplevels/top/',
|
||||
'size',
|
||||
'int', size)
|
||||
elif position == "bottom":
|
||||
return gsettings.set('org.mate.panel.toplevel',
|
||||
'/org/mate/panel/toplevels/bottom/',
|
||||
'size',
|
||||
'int', size)
|
||||
else:
|
||||
return False
|
||||
|
||||
# get launcher icon size
|
||||
def get_mate_panel_icon_size(self, position):
|
||||
if position == "top":
|
||||
return gsettings.get('org.mate.panel.toplevel',
|
||||
'/org/mate/panel/toplevels/top/',
|
||||
'size', 'int')
|
||||
elif position == "bottom":
|
||||
return gsettings.get('org.mate.panel.toplevel',
|
||||
'/org/mate/panel/toplevels/bottom/',
|
||||
'size', 'int')
|
||||
else:
|
||||
return False
|
||||
|
||||
def set_mate_panel_autohide(self, position, flag):
|
||||
if position == "top":
|
||||
return gsettings.set('org.mate.panel.toplevel',
|
||||
'/org/mate/panel/toplevels/top/',
|
||||
'auto-hide',
|
||||
'boolean', flag)
|
||||
elif position == "bottom":
|
||||
return gsettings.set('org.mate.panel.toplevel',
|
||||
'/org/mate/panel/toplevels/bottom/',
|
||||
'auto-hide',
|
||||
'boolean', flag)
|
||||
else:
|
||||
return False
|
||||
|
||||
def get_mate_panel_autohide(self, position):
|
||||
if position == "top":
|
||||
return gsettings.get('org.mate.panel.toplevel',
|
||||
'/org/mate/panel/toplevels/top/',
|
||||
'auto-hide', 'boolean')
|
||||
elif position == "bottom":
|
||||
return gsettings.get('org.mate.panel.toplevel',
|
||||
'/org/mate/panel/toplevels/bottom/',
|
||||
'auto-hide', 'boolean')
|
||||
else:
|
||||
return False
|
||||
|
||||
def get_show_apps(self):
|
||||
return gsettings.get('org.mate.panel.menubar',
|
||||
None,
|
||||
'show-applications',
|
||||
'boolean')
|
||||
|
||||
def set_show_apps(self, flag):
|
||||
return gsettings.set('org.mate.panel.menubar',
|
||||
None,
|
||||
'show-applications',
|
||||
'boolean', flag)
|
||||
|
||||
def get_show_desktop(self):
|
||||
return gsettings.get('org.mate.panel.menubar',
|
||||
None,
|
||||
'show-desktop',
|
||||
'boolean')
|
||||
|
||||
def set_show_desktop(self, flag):
|
||||
return gsettings.set('org.mate.panel.menubar',
|
||||
None,
|
||||
'show-desktop',
|
||||
'boolean', flag)
|
||||
|
||||
def get_show_icon(self):
|
||||
return gsettings.get('org.mate.panel.menubar',
|
||||
None,
|
||||
'show-icon',
|
||||
'boolean')
|
||||
|
||||
def set_show_icon(self, flag):
|
||||
return gsettings.set('org.mate.panel.menubar',
|
||||
None,
|
||||
'show-icon',
|
||||
'boolean', flag)
|
||||
|
||||
def get_show_places(self):
|
||||
return gsettings.get('org.mate.panel.menubar',
|
||||
None,
|
||||
'show-places',
|
||||
'boolean')
|
||||
|
||||
def set_show_places(self, flag):
|
||||
return gsettings.set('org.mate.panel.menubar',
|
||||
None,
|
||||
'show-places',
|
||||
'boolean', flag)
|
||||
|
||||
if __name__ == '__main__':
|
||||
uuu = Unity()
|
||||
# print uuu.get_launcher_icon_colouring()
|
||||
# print uuu.set_launcher_icon_colouring(1)
|
||||
print uuu.get_time_format()
|
||||
# bb = uuu.get_default_schema_value("unityshell", "icon_size")
|
||||
# aa = uuu.get_default_schema_value("unityshell", "launcher_hide_mode")
|
||||
#aa = uuu.get_default_schema_value('org.gnome.desktop.media-handling', 'automount')
|
||||
#uuu = Unity("unityshell", "icon_size")
|
||||
#aa = uuu.get_launcher_icon_size_test()
|
||||
#print "bb->"
|
||||
#print bb
|
||||
#print "aa->"
|
||||
#print aa
|
||||
#uuu.set_default_schema_value('icon-size', 'int', bb)
|
||||
# cc = uuu.get_default_launcher_have_showdesktopicon()
|
||||
# print cc
|
||||
|
||||
#uuu.set_default_schema_value('launcher-hide-mode', 'int', aa)
|
||||
|
||||
#bb = uuu.get_default_launcher_icon_size()
|
||||
#print "bb->"
|
||||
#print bb
|
||||
#print(type(bb))
|
||||
#uuu.reset_default_launcher_icon_size(bb)
|
||||
#uuu.set_launcher_icon_size(48)
|
||||
# print uuu.get_launcher_icon_size()
|
||||
# print uuu.get_launcher_have_showdesktopicon()
|
||||
# uuu.set_launcher_autohide(0)
|
||||
# print uuu.get_launcher_autohide()
|
||||
# uuu.set_launcher_have_showdesktopicon(True)
|
||||
# uuu.set_launcher_icon_size(48)
|
|
@ -0,0 +1,57 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
|
||||
# get ~ dir
|
||||
def get_home_dir():
|
||||
return os.path.expanduser('~')
|
||||
|
||||
# check dirs with given filters and filtertype
|
||||
def check_dirs(dirs, filters, filtertype):
|
||||
result = []
|
||||
try:
|
||||
for onedir in dirs:
|
||||
if os.path.isdir(onedir):
|
||||
for f in os.listdir(onedir):
|
||||
if use_filters(os.path.join(onedir, f), filters, filtertype):
|
||||
result.append(f)
|
||||
except:
|
||||
pass
|
||||
return result
|
||||
|
||||
# check the fpathdir with filters filtertype: True == include, False == exlude
|
||||
def use_filters(fpath, filters, filtertype):
|
||||
# not a directory
|
||||
if os.path.isdir(fpath) == False:
|
||||
return False
|
||||
|
||||
if filtertype:
|
||||
for onefilter in filters:
|
||||
if os.path.exists(os.path.join(fpath, onefilter)):
|
||||
continue
|
||||
else:
|
||||
return False
|
||||
return True
|
||||
else:
|
||||
for onefilter in filters:
|
||||
if os.path.exists(os.path.join(fpath, onefilter)):
|
||||
return False
|
||||
else:
|
||||
continue
|
||||
return True
|
|
@ -0,0 +1 @@
|
|||
#!/usr/bin/python
|
|
@ -0,0 +1,87 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin Ltd
|
||||
# Author: Kobe Lee
|
||||
#
|
||||
# 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
#sudo apt-get install python-pygame
|
||||
import os, sys
|
||||
import time
|
||||
import pygame
|
||||
import pygame.camera
|
||||
from pygame.locals import *
|
||||
import threading
|
||||
|
||||
def get_local_format_time():
|
||||
'''
|
||||
year-month-day hour:minute:second
|
||||
2014-05-07 13:51:30
|
||||
'''
|
||||
local_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
|
||||
return local_date
|
||||
|
||||
#class Capture(object):
|
||||
class Capture(threading.Thread):
|
||||
def __init__(self):
|
||||
threading.Thread.__init__(self)
|
||||
pygame.init()
|
||||
pygame.camera.init()
|
||||
|
||||
def judge_camera(self):
|
||||
clist = pygame.camera.list_cameras()#['/dev/video0']
|
||||
if not clist:
|
||||
return False
|
||||
# raise ValueError("Sorry, no cameras detected.")
|
||||
else:
|
||||
return True
|
||||
|
||||
def call_camera(self):
|
||||
threading.Thread(target=self.call_camera_real, name='Capture').start()
|
||||
|
||||
def call_camera_real(self):
|
||||
self.size = (640,480)
|
||||
self.clist = pygame.camera.list_cameras()#['/dev/video0']
|
||||
self.display = pygame.display.set_mode(self.size, 0)
|
||||
self.snapshot = pygame.surface.Surface(self.size, 0, self.display)
|
||||
self.cam = pygame.camera.Camera(self.clist[0], self.size,"RGB")
|
||||
self.cam.start()
|
||||
going = True
|
||||
timevalue = "00-00-00"
|
||||
while going:
|
||||
events = pygame.event.get()
|
||||
for e in events:
|
||||
if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
|
||||
self.cam.stop()
|
||||
pic_name = get_local_format_time() + '.png'
|
||||
print pic_name
|
||||
going = False
|
||||
if self.cam.query_image():
|
||||
self.snapshot = self.cam.get_image(self.snapshot)
|
||||
self.display.blit(self.snapshot, (0,0))
|
||||
pygame.display.flip()
|
||||
pic_path = os.path.expanduser('~') + '/' + pic_name
|
||||
#pic_path = os.path.join('/home/trusty', pic_name)
|
||||
#os.path.expanduser('~')
|
||||
#pic_name = '/home/trusty/' + timevalue + '.png'
|
||||
pygame.image.save(self.snapshot, pic_path)
|
||||
pygame.quit()
|
||||
#exit(0)
|
||||
|
||||
#if __name__ == '__main__':
|
||||
# mycam=Capture()
|
||||
# if mycam.judge_camera():
|
||||
# mycam.call_camera()
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
import os
|
||||
from common import get_dir_size
|
||||
from common import confirm_filesize_unit
|
||||
|
||||
|
||||
class CacheClean():
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def get_apt_cache(self):
|
||||
apt_cache = '/var/cache/apt/archives'
|
||||
#aptcachelist = map(lambda filename: '%s/%s<2_2>%s' % (apt_cache, filename, str(os.path.getsize('%s/%s' % (apt_cache, filename)))), filter(lambda filestr: filestr.endswith('deb'), os.listdir(apt_cache)))
|
||||
aptcachelist = ['%s/%s<2_2>%s' % (apt_cache,filename, confirm_filesize_unit(os.path.getsize('%s/%s' % (apt_cache, filename)))) for filename in os.listdir(apt_cache) if filename.endswith('deb')]
|
||||
return aptcachelist
|
||||
|
||||
def scan_apt_cache(self, path):
|
||||
aptcache_list = []
|
||||
if os.path.exists(path):
|
||||
aptcache_list = ['%s/%s' % (path, filename) for filename in os.listdir(path) if filename.endswith('deb')]
|
||||
|
||||
return aptcache_list
|
||||
|
||||
def public_scan_cache(self, path):
|
||||
publiccache_list = []
|
||||
if os.path.exists(path):
|
||||
publiccache_list = ['%s/%s' % (path, filename) for filename in os.listdir(path)]
|
||||
|
||||
return publiccache_list
|
||||
|
||||
def firefox_scan_cache(self, path):
|
||||
firefoxcache_list = []
|
||||
if os.path.exists(path):
|
||||
firefoxcache_list = ['%s/%s' % (path, filename) for filename in os.listdir(path) if filename in 'Cache']
|
||||
return firefoxcache_list
|
||||
|
||||
def get_softwarecenter_cache(self, homedir):
|
||||
centercachelist = []
|
||||
if homedir:
|
||||
softwarecenter_cache = '%s/.cache/software-center/' % homedir
|
||||
else:
|
||||
softwarecenter_cache = os.path.expanduser('~/.cache/software-center/')
|
||||
full_path = softwarecenter_cache
|
||||
if os.path.exists(full_path):
|
||||
for one in os.listdir(full_path):
|
||||
tmp_path = full_path + one
|
||||
if os.path.isdir(tmp_path):
|
||||
size = get_dir_size(tmp_path)
|
||||
centercachelist.append('%s<2_2>%s' % (tmp_path, confirm_filesize_unit(size)))
|
||||
else:
|
||||
centercachelist.append('%s<2_2>%s' % (tmp_path, confirm_filesize_unit(os.path.getsize(tmp_path))))
|
||||
return centercachelist
|
||||
|
||||
if __name__ == "__main__":
|
||||
obja = CacheClean()
|
||||
obja.get_apt_cache()
|
||||
obja.get_softwarecenter_cache()
|
|
@ -0,0 +1,159 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
import ConfigParser
|
||||
import apt
|
||||
import apt_pkg
|
||||
import psutil
|
||||
import re
|
||||
|
||||
HOMEDIR = ''
|
||||
|
||||
def confirm_filesize_unit(size):
|
||||
unit_list = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
flag = 0
|
||||
while True:
|
||||
if size > 512:
|
||||
size /= 1024.0
|
||||
flag += 1
|
||||
else: break
|
||||
tmp = "%.2f" % size
|
||||
finalsize = tmp + ' ' + unit_list[flag]
|
||||
return finalsize
|
||||
|
||||
def get_dir_size(path):
|
||||
size = 0L
|
||||
for root, dirs, files in os.walk(path):
|
||||
size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
|
||||
return size
|
||||
|
||||
def process_pid(pname):
|
||||
pid = None
|
||||
processinfo = psutil.process_iter()
|
||||
for one in processinfo:
|
||||
one_str = str(one)
|
||||
patt = re.compile(pname, re.I)
|
||||
if patt.search(one_str):
|
||||
pid = int(one_str.split('pid=')[1].split(',')[0])
|
||||
return pid
|
||||
|
||||
def get_cache_list():
|
||||
cache = None
|
||||
#apt_pkg.InitConfig()
|
||||
#apt_pkg.InitSystem()
|
||||
apt_pkg.init_config()
|
||||
apt_pkg.init_system()
|
||||
cache = apt.Cache()
|
||||
return cache
|
||||
|
||||
#def get_homedir_sysdaemon(homedir):
|
||||
# global HOMEDIR
|
||||
# HOMEDIR = homedir
|
||||
|
||||
def return_homedir_sysdaemon():
|
||||
global HOMEDIR
|
||||
return HOMEDIR
|
||||
|
||||
def return_homedir_sesdaemon():
|
||||
return os.path.expanduser('~')
|
||||
|
||||
def analytical_profiles_file(homedir):
|
||||
count = 0
|
||||
tmp_pro_section = []
|
||||
flag_pro_section = ''
|
||||
finalpath = ''
|
||||
|
||||
app_path = '%s/.mozilla/firefox' % homedir
|
||||
profiles_path = '%s/profiles.ini' % app_path
|
||||
if os.path.exists(profiles_path):
|
||||
cfg = ConfigParser.ConfigParser()
|
||||
cfg.read(profiles_path)
|
||||
complete_section = cfg.sections()
|
||||
for section in complete_section:
|
||||
if section.startswith('Profile'):
|
||||
tmp_pro_section.append(section)
|
||||
complete_option = cfg.options(section)
|
||||
try:
|
||||
cfg.getint(section, 'Default') == 1
|
||||
except Exception, e:
|
||||
pass
|
||||
else:
|
||||
flag_pro_section = section
|
||||
count += 1
|
||||
if cfg.getint('General', 'StartWithLastProfile'):
|
||||
if count == 1:
|
||||
if cfg.getint(tmp_pro_section[0], 'IsRelative') == 0:
|
||||
finalpath = cfg.get(tmp_pro_section[0], 'Path').split('/')[-1]
|
||||
else:
|
||||
finalpath = cfg.get(tmp_pro_section[0], 'Path')
|
||||
elif count > 1 :
|
||||
if cfg.getint(flag_pro_section, 'IsRelative') == 0:
|
||||
finalpath = cfg.get(flag_pro_section, 'Path').split('/')[-1]
|
||||
else:
|
||||
finalpath = cfg.get(flag_pro_section, 'Path')
|
||||
else:
|
||||
pass
|
||||
else:
|
||||
pass
|
||||
return finalpath
|
||||
|
||||
def get_mozilla_path(homedir):
|
||||
count = 0
|
||||
tmp_pro_section = []
|
||||
if homedir:
|
||||
app_path = '%s/.mozilla/firefox' % homedir
|
||||
else:
|
||||
app_path = os.path.expanduser('~/.mozilla/firefox')
|
||||
flag_pro_section = ''
|
||||
finalpath = ''
|
||||
|
||||
profiles_path = '%s/profiles.ini' % app_path
|
||||
if os.path.exists(profiles_path):
|
||||
cfg = ConfigParser.ConfigParser()
|
||||
cfg.read(profiles_path)
|
||||
complete_section = cfg.sections()
|
||||
for section in complete_section:
|
||||
if section.startswith('Profile'):
|
||||
tmp_pro_section.append(section)
|
||||
complete_option = cfg.options(section)
|
||||
try:
|
||||
cfg.getint(section, 'Default') == 1
|
||||
except Exception, e:
|
||||
pass
|
||||
else:
|
||||
flag_pro_section = section
|
||||
count += 1
|
||||
if cfg.getint('General', 'StartWithLastProfile'):
|
||||
if count == 1:
|
||||
if cfg.getint(tmp_pro_section[0], 'IsRelative') == 0:
|
||||
finalpath = cfg.get(tmp_pro_section[0], 'Path')
|
||||
else:
|
||||
finalpath = os.path.expanduser('%s/%s/' % (app_path, cfg.get(tmp_pro_section[0], 'Path')))
|
||||
elif count > 1 :
|
||||
if cfg.getint(flag_pro_section, 'IsRelative') == 0:
|
||||
finalpath = cfg.get(flag_pro_section, 'Path')
|
||||
else:
|
||||
finalpath = os.path.expanduser('%s/%s/' % (app_path, cfg.get(flag_pro_section, 'Path')))
|
||||
else:
|
||||
raise Exception('profile.ini has error!')
|
||||
else:
|
||||
pass
|
||||
return finalpath
|
||||
|
||||
if __name__ == '__main__':
|
||||
print analytical_profiles_file('/home/aya')
|
|
@ -0,0 +1,102 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os.path
|
||||
import sqlite3
|
||||
|
||||
from common import get_mozilla_path
|
||||
|
||||
|
||||
class CookiesClean():
|
||||
def __init__(self, homedir):
|
||||
self.filename = 'cookies.sqlite'
|
||||
self.path = get_mozilla_path(homedir)
|
||||
|
||||
def scan_the_records(self):
|
||||
save = []
|
||||
if os.path.exists(self.path):
|
||||
scan_browser_conn = sqlite3.connect(self.path + self.filename)
|
||||
scan_browser_cur = scan_browser_conn.cursor()
|
||||
sql_select = 'SELECT baseDomain, count(*) FROM moz_cookies GROUP BY baseDomain'
|
||||
scan_browser_cur.execute(sql_select)
|
||||
for eachvisit in scan_browser_cur.fetchall():
|
||||
tmp = list(eachvisit)
|
||||
tmp[-1] = str(tmp[-1])
|
||||
tmp_str = '<2_2>'.join(tmp)
|
||||
save.append(tmp_str)
|
||||
scan_browser_cur.close()
|
||||
scan_browser_conn.close()
|
||||
return save
|
||||
|
||||
def scan_cookies_records(self, filepath, tablename, keyname):
|
||||
result = []
|
||||
if os.path.exists(filepath):
|
||||
scan_browser_conn = sqlite3.connect(filepath)
|
||||
scan_browser_cur = scan_browser_conn.cursor()
|
||||
sql_select = 'SELECT %s, count(*) FROM %s GROUP BY %s' % (keyname, tablename, keyname)
|
||||
scan_browser_cur.execute(sql_select)
|
||||
result = scan_browser_cur.fetchall()
|
||||
scan_browser_cur.close()
|
||||
scan_browser_conn.close()
|
||||
#result = ["%s<2_2>%s" % (eachone[0], str(eachone[-1])) for eachone in allvisit]
|
||||
return result
|
||||
|
||||
def clean_cookies_record(self, filepath, tablename, keyname, domain):
|
||||
if os.path.exists(filepath):
|
||||
clean_browser_conn = sqlite3.connect(filepath)
|
||||
clean_browser_cur = clean_browser_conn.cursor()
|
||||
#sql_exist = "SELECT * FROM %s WHERE %s='%s'" % (tablename, keyname, domain)
|
||||
#clean_browser_cur.execute(sql_exist)
|
||||
#if clean_browser_cur.fetchone():
|
||||
sql_delete = "DELETE FROM %s WHERE %s='%s'" % (tablename, keyname, domain)
|
||||
clean_browser_cur.execute(sql_delete)
|
||||
clean_browser_conn.commit()
|
||||
clean_browser_cur.close()
|
||||
clean_browser_conn.close()
|
||||
|
||||
def clean_all_records(self, filename, tablename, keyname):
|
||||
if os.path.exists(filename):
|
||||
clean_browser_conn = sqlite3.connect(filename)
|
||||
clean_browser_cur = clean_browser_conn.cursor()
|
||||
sql_delete = "DELETE FROM %s" % tablename
|
||||
clean_browser_cur.execute(sql_delete)
|
||||
clean_browser_conn.commit()
|
||||
clean_browser_cur.close()
|
||||
clean_browser_conn.close()
|
||||
|
||||
|
||||
def clean_the_records(self, domain):
|
||||
if os.path.exists(self.path):
|
||||
clean_browser_conn = sqlite3.connect(self.path + self.filename)
|
||||
clean_browser_cur = clean_browser_conn.cursor()
|
||||
sql_exist = "SELECT * FROM moz_cookies WHERE baseDomain='%s'" % domain
|
||||
clean_browser_cur.execute(sql_exist)
|
||||
if clean_browser_cur.fetchone():
|
||||
sql_delete = "DELETE FROM moz_cookies WHERE baseDomain='%s'" % domain
|
||||
clean_browser_cur.execute(sql_delete)
|
||||
clean_browser_conn.commit()
|
||||
clean_browser_cur.close()
|
||||
clean_browser_conn.close()
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
if __name__ == "__main__":
|
||||
objc = CookiesClean()
|
||||
objc.scan_the_records()
|
||||
#objc.clean_the_records(['1188.com'])
|
||||
del objc
|
|
@ -0,0 +1,54 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
import commands
|
||||
import sqlite3
|
||||
|
||||
|
||||
class DashHistory():
|
||||
def __init__(self, homedir):
|
||||
self.full_path = ''
|
||||
if homedir:
|
||||
path = '%s/.local/share/zeitgeist/' % homedir
|
||||
else:
|
||||
path = os.path.expanduser('~/.local/share/zeitgeist/')
|
||||
self.full_path = path + 'activity.sqlite'
|
||||
if not os.path.exists(self.full_path):
|
||||
raise Exception("Dashhistory: path did not exist")
|
||||
|
||||
def scan_the_records(self):
|
||||
self.browser_conn = sqlite3.connect(self.full_path)
|
||||
self.browser_cur = self.browser_conn.cursor()
|
||||
|
||||
sql_select = "SELECT COUNT(*) FROM event_view"
|
||||
self.browser_cur.execute(sql_select)
|
||||
number = self.browser_cur.fetchone()[0]
|
||||
|
||||
self.browser_cur.close()
|
||||
self.browser_conn.close()
|
||||
return number
|
||||
|
||||
def clean_the_records(self):
|
||||
tmp_path = self.full_path
|
||||
user = tmp_path.split('/')[2]
|
||||
os.remove(tmp_path)
|
||||
cmd = "su - %s -c 'zeitgeist-daemon --replace & >& /dev/null'" % user
|
||||
(status, output) = commands.getstatusoutput(cmd)
|
||||
return
|
||||
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
import os.path
|
||||
|
||||
import common
|
||||
|
||||
class DiskAnalyse():
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def hundred_large_files(self, size, path):
|
||||
mypath = path
|
||||
final_list = []
|
||||
if os.path.exists(mypath):
|
||||
for rootpath, dirnames, filenames in os.walk(mypath):
|
||||
for filename in filenames:
|
||||
flag = True
|
||||
filepath = os.path.join(rootpath, filename)
|
||||
if os.path.islink(filepath):
|
||||
continue
|
||||
filelist = [os.path.getsize(filepath), filepath]
|
||||
if not final_list and filelist[0] >= size:
|
||||
final_list.append(filelist)
|
||||
flag = False
|
||||
else:
|
||||
for index, values in enumerate(final_list):
|
||||
if filelist > values:
|
||||
final_list.insert(index, filelist)
|
||||
flag = False
|
||||
break
|
||||
if flag and filelist[0] >= size :
|
||||
final_list.append(filelist)
|
||||
else:
|
||||
pass
|
||||
return final_list
|
||||
|
||||
def adjust_the_list(self, size, path):
|
||||
final_str = []
|
||||
tmp_list = self.hundred_large_files(size, path)
|
||||
if tmp_list:
|
||||
for tmp in tmp_list:
|
||||
tmp[0] = common.confirm_filesize_unit(tmp[0])
|
||||
final_str.append('<2_2>'.join(tmp))
|
||||
return final_str
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
obj = DiskAnalyse()
|
||||
obj.hundred_large_files()
|
||||
obj.type_of_file()
|
|
@ -0,0 +1,143 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os.path
|
||||
import sqlite3
|
||||
from common import process_pid
|
||||
from common import get_mozilla_path
|
||||
|
||||
|
||||
class HistoryClean():
|
||||
def __init__(self, homedir):
|
||||
self.filename = 'places.sqlite'
|
||||
self.path = get_mozilla_path(homedir)
|
||||
|
||||
def scan_the_records(self):
|
||||
save = []
|
||||
if os.path.exists(self.path):
|
||||
scan_browser_conn = sqlite3.connect(self.path + self.filename)
|
||||
scan_browser_cur = scan_browser_conn.cursor()
|
||||
sql_select = "SELECT moz_historyvisits.place_id, moz_places.url, moz_places.title, count(*) FROM moz_historyvisits, moz_places WHERE moz_historyvisits.place_id=moz_places.id GROUP BY moz_historyvisits.place_id"
|
||||
scan_browser_cur.execute(sql_select)
|
||||
for eachvisit in scan_browser_cur.fetchall():
|
||||
|
||||
tmp = list(eachvisit)
|
||||
tmp[0], tmp[-1] = str(tmp[0]), str(tmp[-1])
|
||||
if not isinstance(tmp[2], unicode):
|
||||
tmp[2] = str(tmp[2])
|
||||
tmp_str = '<2_2>'.join(tmp)
|
||||
save.append(tmp_str)
|
||||
scan_browser_cur.close()
|
||||
scan_browser_conn.close()
|
||||
return save
|
||||
|
||||
def scan_firefox_history_records(self, filepath):
|
||||
result = []
|
||||
if os.path.exists(filepath):
|
||||
scan_browser_conn = sqlite3.connect(filepath)
|
||||
scan_browser_cur = scan_browser_conn.cursor()
|
||||
sql_select = "SELECT moz_historyvisits.place_id, moz_places.url, count(*) FROM moz_historyvisits, moz_places WHERE moz_historyvisits.place_id=moz_places.id GROUP BY moz_historyvisits.place_id"
|
||||
scan_browser_cur.execute(sql_select)
|
||||
result = scan_browser_cur.fetchall()
|
||||
#result = ["%s<2_2>%s<2_2>%s" % (str(each[0]), each[1], str(each[2])) for each in allvisit]
|
||||
scan_browser_cur.close()
|
||||
scan_browser_conn.close()
|
||||
return result
|
||||
|
||||
def scan_chromium_history_records(self, filepath):
|
||||
result = []
|
||||
if os.path.exists(filepath):
|
||||
scan_chromium_conn = sqlite3.connect(filepath)
|
||||
scan_chromium_cur = scan_chromium_conn.cursor()
|
||||
sql_select = "SELECT visits.url, urls.url, count(*) FROM visits, urls WHERE visits.url=urls.id GROUP BY visits.url"
|
||||
scan_chromium_cur.execute(sql_select)
|
||||
result = scan_chromium_cur.fetchall()
|
||||
#result = ["%s<2_2>%s<2_2>%s" % (str(each[0]), each[1], str(each[2])) for each in allvisit]
|
||||
scan_chromium_cur.close()
|
||||
scan_chromium_conn.close()
|
||||
|
||||
return result
|
||||
|
||||
def clean_firefox_all_records(self, filepath):
|
||||
if os.path.exists(filepath):
|
||||
clean_browser_conn = sqlite3.connect(filepath)
|
||||
clean_browser_cur = clean_browser_conn.cursor()
|
||||
sql_deletehistory = 'DELETE FROM moz_historyvisits'
|
||||
clean_browser_cur.execute(sql_deletehistory)
|
||||
clean_browser_conn.commit()
|
||||
|
||||
sql_selectplace = 'SELECT place_id FROM moz_annos UNION SELECT fk FROM moz_bookmarks UNION SELECT place_id FROM moz_inputhistory'
|
||||
clean_browser_cur.execute(sql_selectplace)
|
||||
delete_place_id = clean_browser_cur.fetchall()
|
||||
delete_place_id_str = ','.join([ str(one[0]) for one in delete_place_id if one[0]])
|
||||
sql_deleteplace = 'DELETE FROM moz_places WHERE id NOT IN (%s)' % delete_place_id_str
|
||||
clean_browser_cur.execute(sql_deleteplace)
|
||||
clean_browser_conn.commit()
|
||||
|
||||
sql_selectfavicons = 'SELECT favicon_id FROM moz_places'
|
||||
clean_browser_cur.execute(sql_selectfavicons)
|
||||
delete_favicon_id = clean_browser_cur.fetchall()
|
||||
delete_favicon_id_str = ','.join([ str(one[0]) for one in delete_favicon_id if one[0]])
|
||||
sql_deletefavicons = 'DELETE FROM moz_favicons WHERE id NOT in (%s)' % delete_favicon_id_str
|
||||
clean_browser_cur.execute(sql_deletefavicons)
|
||||
clean_browser_conn.commit()
|
||||
|
||||
clean_browser_cur.close()
|
||||
clean_browser_conn.close()
|
||||
|
||||
def clean_chromium_all_records(self, filepath):
|
||||
if os.path.exists(filepath):
|
||||
clean_chromium_conn = sqlite3.connect(filepath)
|
||||
clean_chromium_cur = clean_chromium_conn.cursor()
|
||||
tables = ['visits', 'urls', 'keyword_search_terms', 'segment_usage', 'segments']
|
||||
for tn in tables:
|
||||
sql_delete = 'DELETE FROM %s' % tn
|
||||
clean_chromium_cur.execute(sql_delete)
|
||||
clean_chromium_conn.commit()
|
||||
|
||||
clean_chromium_cur.close()
|
||||
clean_chromium_conn.close()
|
||||
|
||||
def clean_the_records(self, history):
|
||||
int_history = int(history)
|
||||
sql_exist = 'SELECT * FROM moz_historyvisits WHERE place_id=%s' % int_history
|
||||
self.browser_cur.execute(sql_exist)
|
||||
if self.browser_cur.fetchone():
|
||||
sql_delete = 'DELETE FROM moz_historyvisits WHERE place_id=%s ' % int_history
|
||||
self.browser_cur.execute(sql_delete)
|
||||
#self.browser_cur.execute('DELETE FROM moz_places WHERE visit_count=0')
|
||||
self.browser_conn.commit()
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def clean_all_records(self):
|
||||
if os.path.exists(self.path):
|
||||
clean_browser_conn = sqlite3.connect(self.path + self.filename)
|
||||
clean_browser_cur = clean_browser_conn.cursor()
|
||||
sql_deleteall = 'DELETE FROM moz_historyvisits'
|
||||
clean_browser_cur.execute(sql_deleteall)
|
||||
#self.browser_cur.execute('DELETE FROM moz_places WHERE visit_count=0')
|
||||
clean_browser_conn.commit()
|
||||
clean_browser_cur.close()
|
||||
clean_browser_conn.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
objc = HistoryClean()
|
||||
objc.scan_the_records()
|
||||
#objc.clean_the_records(['36'])
|
||||
del objc
|
|
@ -0,0 +1,69 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
#import apt
|
||||
import apt_pkg
|
||||
import re
|
||||
|
||||
import common
|
||||
|
||||
class OldKernel():
|
||||
def __init__(self):
|
||||
#cache = None
|
||||
self.flag = '(\w+-)*[.\d]+-\d+[\D]*'
|
||||
|
||||
def scan_oldkernel_packages(self):
|
||||
#pkgs = self.cache.packages
|
||||
cache = common.get_cache_list()
|
||||
final_oldkernel_list = []
|
||||
current_version = '-'.join(os.uname()[2].split('-')[:2])
|
||||
if cache:
|
||||
for pkg in cache:
|
||||
if pkg.is_installed and pkg.name.startswith('linux'):
|
||||
if re.match(self.flag, pkg.name):
|
||||
#version = pkg.installedVersion[:-3]
|
||||
version = pkg.installed.version
|
||||
if apt_pkg.version_compare(version, current_version) < 0:
|
||||
#tmp_oldkernel_list = [pkg.name, common.confirm_filesize_unit(pkg.installedSize)]
|
||||
#final_oldkernel_list.append('<2_2>'.join(tmp_oldkernel_list))
|
||||
final_oldkernel_list.append(pkg)
|
||||
return final_oldkernel_list
|
||||
|
||||
def get_oldkernel_packages(self):
|
||||
#pkgs = self.cache.packages
|
||||
cache = common.get_cache_list()
|
||||
oldkernel_list = []
|
||||
current_version = '-'.join(os.uname()[2].split('-')[:2])
|
||||
if cache:
|
||||
for pkg in cache:
|
||||
if pkg.is_installed and pkg.name.startswith('linux'):
|
||||
if re.match(self.flag, pkg.name):
|
||||
#version = pkg.installedVersion[:-3]
|
||||
version = pkg.installed.version
|
||||
if apt_pkg.version_compare(version, current_version) < 0:
|
||||
#tmp_oldkernel_list = [pkg.name, common.confirm_filesize_unit(pkg.installedSize)]
|
||||
#final_oldkernel_list.append('<2_2>'.join(tmp_oldkernel_list))
|
||||
oldkernel_list.append('Name:' + pkg.name + ';' + 'Summary:' + pkg.installed.summary + ';' + 'Size:' + common.confirm_filesize_unit(pkg.installed.installed_size))
|
||||
|
||||
return oldkernel_list
|
||||
if __name__ == "__main__":
|
||||
objo = OldKernel()
|
||||
#objo.get_the_kernel()
|
||||
aaa = objo.get_old_kernel()
|
||||
print aaa
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
import sys
|
||||
import apt
|
||||
import apt_pkg
|
||||
from apt.progress.base import InstallProgress
|
||||
|
||||
import common
|
||||
|
||||
class OsSlim():
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def get_unneed_packages(self):
|
||||
cache = common.get_cache_list()
|
||||
unneed_packages_list = []
|
||||
if cache:
|
||||
for pkg in cache:
|
||||
if pkg.is_auto_removable and not pkg.name.startswith('linux'):
|
||||
unneed_packages_list.append('Name:' + pkg.name + ';' + 'Summary:' + pkg.installed.summary + ';' + 'Size:' + common.confirm_filesize_unit(pkg.installed.installed_size))
|
||||
return unneed_packages_list
|
||||
|
||||
def get_spare_packages(self):
|
||||
cache = common.get_cache_list()
|
||||
spare_packages_list = []
|
||||
if cache:
|
||||
for pkg in cache:
|
||||
if pkg.is_auto_removable and not pkg.name.startswith('linux'):
|
||||
#if pkg.is_installed and pkg.name.startswith('linux-headers'):
|
||||
tmp_packages_list = [pkg.name, pkg.installed.summary, common.confirm_filesize_unit(pkg.installed.installed_size)]
|
||||
spare_packages_list.append('<2_2>'.join(tmp_packages_list))
|
||||
return spare_packages_list
|
||||
|
||||
def scan_spare_packages(self):
|
||||
cache = common.get_cache_list()
|
||||
final_spare_list = []
|
||||
if cache:
|
||||
for pkg in cache:
|
||||
if pkg.is_auto_removable and not pkg.name.startswith('linux'):
|
||||
final_spare_list.append(pkg)
|
||||
return final_spare_list
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
obj = OsSlim()
|
||||
obj.get_spare_packages()
|
||||
#obj.clean_spare_packages()
|
|
@ -0,0 +1,100 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
import os.path
|
||||
import fnmatch
|
||||
import filecmp
|
||||
import hashlib
|
||||
|
||||
class SearchSame():
|
||||
def __init__(self):
|
||||
self.style = ['.gz', '.bz2']
|
||||
self.style_dic = {}
|
||||
self.tmp_style_dic = {}
|
||||
|
||||
def search_by_style(self, spath):
|
||||
if not os.path.exists(spath):
|
||||
raise Exception('no such path!')
|
||||
else:
|
||||
if not spath.endswith('/'):
|
||||
spath += '/'
|
||||
for name in os.listdir(spath):
|
||||
tmp = spath + name
|
||||
if os.path.islink(tmp):
|
||||
continue
|
||||
elif os.path.isdir(tmp):
|
||||
self.search_by_style(tmp)
|
||||
else:
|
||||
front, behind = os.path.splitext(tmp)
|
||||
if behind in self.style:
|
||||
addf, addb = os.path.splitext(front)
|
||||
if addb == '.tar':
|
||||
behind = addb + behind
|
||||
self.tmp_style_dic.setdefault(behind, []).append(tmp)
|
||||
|
||||
def search_by_size(self):
|
||||
self.style_dic = self.reduce_the_dic(self.tmp_style_dic)
|
||||
size_dic = {}
|
||||
for k in self.style_dic.keys():
|
||||
for abc in self.style_dic[k]:
|
||||
filesize = os.path.getsize(abc)
|
||||
size_dic.setdefault(filesize, []).append(abc)
|
||||
return self.reduce_the_dic(size_dic)
|
||||
|
||||
def search_by_cmp(self):
|
||||
final_dic = {}
|
||||
size_dic = self.search_by_size()
|
||||
for k in size_dic.keys():
|
||||
for content in size_dic[k]:
|
||||
sha1sumva = self.get_file_hash(content)
|
||||
final_dic.setdefault(sha1sumva, []).append(content)
|
||||
return self.reduce_the_dic(final_dic)
|
||||
|
||||
|
||||
def get_file_hash(self, filepath):
|
||||
with open(filepath, 'rb') as f:
|
||||
sha1obj = hashlib.sha1()
|
||||
sha1obj.update(f.read())
|
||||
hashvalue = sha1obj.hexdigest()
|
||||
return hashvalue
|
||||
|
||||
def adjust_the_dic(self):
|
||||
final_list = []
|
||||
final_dic = self.search_by_cmp()
|
||||
for key in final_dic.keys():
|
||||
tmp_str = "<2_2>".join(final_dic[key])
|
||||
final_list.append(tmp_str)
|
||||
# init
|
||||
self.style_dic = {}
|
||||
self.tmp_style_dic = {}
|
||||
return final_list
|
||||
|
||||
def reduce_the_dic(self, tmp_dic):
|
||||
for key in tmp_dic.keys():
|
||||
if len(tmp_dic[key]) < 2:
|
||||
del tmp_dic[key]
|
||||
return tmp_dic
|
||||
|
||||
if __name__ == '__main__':
|
||||
path = '/home/kylin/ubuntu-tweak'
|
||||
obj = SearchSame()
|
||||
obj.search_by_style(path)
|
||||
#obj.search_by_size()
|
||||
#obj.search_by_cmp()
|
||||
obj.adjust_the_dic()
|
||||
#obj.get_file_hash('/home/aya/test.py')
|
|
@ -0,0 +1,50 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import commands
|
||||
|
||||
import common
|
||||
|
||||
class SoftwareConfigfile():
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def scan_configfile_packages(self):
|
||||
cache = common.get_cache_list()
|
||||
final_softwareconfigfile_list = []
|
||||
|
||||
status, output = commands.getstatusoutput('dpkg -l')
|
||||
result = [(line.split()[1]).split(':')[0] for line in output.split('\n') if line.startswith('rc')]
|
||||
for one in result:
|
||||
final_softwareconfigfile_list.append(cache[one])
|
||||
return final_softwareconfigfile_list
|
||||
def get_configfile_packages(self):
|
||||
cache = common.get_cache_list()
|
||||
softwareconfigfile_list = []
|
||||
|
||||
status, output = commands.getstatusoutput('dpkg -l')
|
||||
result = [(line.split()[1]).split(':')[0] for line in output.split('\n') if line.startswith('rc')]
|
||||
for one in result:
|
||||
pkg = cache[one]
|
||||
softwareconfigfile_list.append('Name:' + pkg.name + ';' + 'Summary:' + ';' + 'Size:')
|
||||
return softwareconfigfile_list
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
obj = SoftwareConfigfile()
|
||||
a = obj.scan_configfile_packages()
|
||||
print a
|
|
@ -0,0 +1,51 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
from xml.etree import ElementTree
|
||||
|
||||
class SystemHistory():
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def scan_the_xml(self, homedir):
|
||||
if homedir:
|
||||
xml_path = '%s/.local/share/' % homedir
|
||||
else:
|
||||
xml_path = os.path.expanduser('~/.local/share/')
|
||||
|
||||
full_path = xml_path + 'recently-used.xbel'
|
||||
|
||||
hreflist = []
|
||||
if os.path.exists(full_path):
|
||||
tree = ElementTree.parse(full_path)
|
||||
nodes = tree.findall("bookmark")
|
||||
for node in nodes:
|
||||
hreflist.append(node.get('href'))
|
||||
|
||||
return hreflist
|
||||
|
||||
def clean_the_xml(self, homedir):
|
||||
xml_path = '%s/.local/share/' % homedir
|
||||
full_path = xml_path + 'recently-used.xbel'
|
||||
|
||||
if os.path.exists(full_path):
|
||||
tree = ElementTree.parse(full_path)
|
||||
root = tree.getroot()
|
||||
root .clear()
|
||||
|
||||
tree.write(full_path, encoding="UTF-8", xml_declaration=None, default_namespace=None, method="xml")
|
|
@ -0,0 +1 @@
|
|||
#!/usr/bin/python
|
|
@ -0,0 +1 @@
|
|||
UK_ACTION_YOUKER = 'com.ubuntukylin.youker.action'
|
|
@ -0,0 +1,71 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2007-2011 Tualatrix Chou <tualatrix@gmail.com>
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import dbus
|
||||
import dbus.service
|
||||
import logging
|
||||
log = logging.getLogger("DbusProxy")
|
||||
|
||||
INTERFACE = 'com.ubuntukylin.youker'
|
||||
UKPATH = '/'
|
||||
SHOWED = False
|
||||
|
||||
def show_message(*args):
|
||||
from dialogs import ErrorDialog
|
||||
title = 'Daemon start failed'
|
||||
message = ('Youker Assisant systemdaemon didn\'t start correctly.\n'
|
||||
'If you want to help developers debugging, try to run "<b>sudo /usr/lib/python2.7/dist-packages/youker-assistant-daemon/src/start_systemdbus.py</b>" in a terminal.')
|
||||
ErrorDialog(title=title, message=message).launch()
|
||||
|
||||
def nothing(*args):
|
||||
return None
|
||||
|
||||
class DbusProxy:
|
||||
try:
|
||||
__system_bus = dbus.SystemBus()
|
||||
__object = __system_bus.get_object(INTERFACE, UKPATH)
|
||||
except Exception, e:
|
||||
__object = None
|
||||
|
||||
def __getattr__(self, name):
|
||||
global SHOWED
|
||||
try:
|
||||
return self.__object.get_dbus_method(name, dbus_interface=self.INTERFACE)
|
||||
except Exception, e:
|
||||
#log.error(e)
|
||||
if not SHOWED:
|
||||
SHOWED = True
|
||||
return show_message
|
||||
else:
|
||||
return nothing
|
||||
|
||||
def get_object(self):
|
||||
return self.__object
|
||||
|
||||
class AccessDeniedException(dbus.DBusException):
|
||||
'''This exception is raised when some operation is not permitted.'''
|
||||
|
||||
_dbus_error_name = 'com.ubuntukylin.youker.AccessDeniedException'
|
||||
|
||||
def init_dbus(dbus_iface=INTERFACE, dbus_path=UKPATH):
|
||||
'''init dbus'''
|
||||
proxy = DbusProxy()
|
||||
return proxy
|
||||
|
||||
if __name__ == '__main__':
|
||||
print init_dbus()
|
|
@ -0,0 +1,74 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2007-2011 Tualatrix Chou <tualatrix@gmail.com>
|
||||
# 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import thread
|
||||
|
||||
from gi.repository import GObject, Gtk, Gdk
|
||||
|
||||
class BaseDialog(Gtk.MessageDialog):
|
||||
def __init__(self, **kwargs):
|
||||
title = kwargs.pop('title', '')
|
||||
message = kwargs.pop('message', '')
|
||||
|
||||
GObject.GObject.__init__(self, **kwargs)
|
||||
|
||||
if title:
|
||||
self.set_title(title)
|
||||
|
||||
if message:
|
||||
self.set_content(message)
|
||||
|
||||
def set_title(self, title):
|
||||
self.set_markup('<big><b>%s</b></big>' % title)
|
||||
|
||||
def set_content(self, message):
|
||||
if self.get_property('text'):
|
||||
self.format_secondary_markup(message)
|
||||
else:
|
||||
self.set_markup(message)
|
||||
|
||||
def launch(self):
|
||||
self.run()
|
||||
self.destroy()
|
||||
|
||||
def add_option_button(self, button):
|
||||
'''Add an option button to the left. It will not grab the default response.'''
|
||||
vbox = self.get_content_area()
|
||||
hbuttonbox = vbox.get_children()[-1]
|
||||
|
||||
hbox = Gtk.HBox(spacing=12)
|
||||
vbox.pack_start(hbox, False, False, 0)
|
||||
vbox.remove(hbuttonbox)
|
||||
|
||||
new_hbuttonbox = Gtk.HButtonBox()
|
||||
new_hbuttonbox.set_layout(Gtk.ButtonBoxStyle.START)
|
||||
new_hbuttonbox.pack_start(button, True, True, 0)
|
||||
|
||||
hbox.pack_start(new_hbuttonbox, True, True, 0)
|
||||
hbox.pack_start(hbuttonbox, True, True, 0)
|
||||
|
||||
hbuttonbox.get_children()[-1].grab_focus()
|
||||
|
||||
vbox.show_all()
|
||||
|
||||
|
||||
class ErrorDialog(BaseDialog):
|
||||
def __init__(self, title='', message='', parent=None,
|
||||
type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK):
|
||||
BaseDialog.__init__(self, title=title, message=message,
|
||||
parent=parent, message_type=type, buttons=buttons)
|
|
@ -0,0 +1 @@
|
|||
#!/usr/bin/python
|
|
@ -0,0 +1,153 @@
|
|||
#! /usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin Ltd
|
||||
#
|
||||
# Author: Kobe Lee <xiangli@ubuntukylin.com>
|
||||
# Maintainer: Ubuntu Kylin
|
||||
#
|
||||
# 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os, sys
|
||||
import urllib2
|
||||
import platform
|
||||
import re
|
||||
import subprocess
|
||||
import commands
|
||||
|
||||
BOOL_TYPE = 1
|
||||
INT_TYPE = 2
|
||||
DOUBLE_TYPE = 3
|
||||
STRING_TYPE = 4
|
||||
|
||||
str_agent = []
|
||||
LEN_AGENT = 10
|
||||
|
||||
str_agent.append('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; Media Center PC 6.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C)')
|
||||
|
||||
str_agent.append('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; msn OptimizedIE8;ZHCN)')
|
||||
|
||||
str_agent.append('Mozilla/5.0 (X11; Linux x86_64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre')
|
||||
|
||||
str_agent.append('Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b8pre) Gecko/20101213 Firefox/4.0b8pre')
|
||||
|
||||
str_agent.append('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; Alexa Toolbar)')
|
||||
|
||||
str_agent.append('Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.53 Safari/534.30')
|
||||
|
||||
str_agent.append('Mozilla/5.0 (X11; U;Linux i686; zh-CN;rv:1.2.3.4) Gecko/')
|
||||
|
||||
str_agent.append('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; Alexa Toolbar; SE 2.X MetaSr 1.0)')
|
||||
|
||||
str_agent.append('Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.4 (KHTML, like Gecko) Maxthon/3.0.6.27 Safari/532.4')
|
||||
|
||||
str_agent.append('Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/34.0.1847.116 Chrome/34.0.1847.116 Safari/537.36')
|
||||
|
||||
ubuntukylin_distrowatch = 'http://distrowatch.com/table.php?distribution=ubuntukylin'
|
||||
distrowatch = 'http://distrowatch.com/'
|
||||
|
||||
def get_distro_info():
|
||||
ufpath = '/etc/ubuntukylin-release'
|
||||
if(os.path.exists(ufpath) and os.path.isfile(ufpath)):
|
||||
uf = open(ufpath)
|
||||
lines = uf.readlines()
|
||||
rtn = []
|
||||
for line in lines:
|
||||
kv = line.split('=')
|
||||
if (kv[0] == 'DISTRIB_ID'):
|
||||
v = kv[1]
|
||||
rtn.append(v[:-1])
|
||||
if (kv[0] == 'DISTRIB_RELEASE'):
|
||||
v = kv[1]
|
||||
rtn.append(v[:-1])
|
||||
uf.close()
|
||||
return rtn
|
||||
else:
|
||||
dist = platform.dist()
|
||||
distname = dist[0]
|
||||
distversion = dist[1]
|
||||
return [distname, distversion]
|
||||
|
||||
#def get_machine_id():
|
||||
# fpath = '/var/lib/dbus/machine-id'
|
||||
# if(os.path.exists(fpath) and os.path.isfile(fpath)):
|
||||
# f = open(fpath, 'r')
|
||||
# id = f.read()
|
||||
# f.close()
|
||||
# id = id.replace('\n','')
|
||||
# if(id == ''):
|
||||
# return 'unknown'
|
||||
# else:
|
||||
# return id
|
||||
# else:
|
||||
# return 'unknown'
|
||||
|
||||
def get_ip_again():
|
||||
ret = ''
|
||||
url = "http://members.3322.org/dyndns/getip"
|
||||
try:
|
||||
fp = urllib2.urlopen(url, timeout=5)
|
||||
souce = fp.read()
|
||||
if not isinstance(souce, str):
|
||||
souce = str(souce)
|
||||
fp.close()
|
||||
ret = souce.replace('\n', '')
|
||||
except:
|
||||
print >> sys.stderr, 'get_ip failed!'
|
||||
return ret
|
||||
|
||||
def get_ip():
|
||||
ret = ''
|
||||
url = "http://iframe.ip138.com/ic.asp"
|
||||
try:
|
||||
fp = urllib2.urlopen(url, timeout=5)
|
||||
souce = fp.read().decode("GB2312")
|
||||
fp.close()
|
||||
ret = re.findall("<center>(.*)</center>", souce)[0].encode("UTF-8")
|
||||
except:
|
||||
ret = get_ip_again()
|
||||
return ret
|
||||
|
||||
|
||||
def get_run_command(pkgname):
|
||||
fd = os.popen('find /usr/share/applications/ -name "%s.desktop" | xargs grep "Exec"' %pkgname)
|
||||
exc = fd.read()
|
||||
fd.close()
|
||||
command = ['']
|
||||
# 截取运行指令部分
|
||||
if exc:
|
||||
command = re.findall('Exec=(.*)',exc)
|
||||
# 有些软件Exec后面会有%U %f等,进行过滤
|
||||
if re.findall(' ',command[0]):
|
||||
command = re.findall('(.*) ',command[0])
|
||||
#split the command to prevent the error: "OSError: [Errno 2] 没有那个文件或目录"
|
||||
fullcmd = command[0]
|
||||
if fullcmd:
|
||||
fullcmd = command[0].split()
|
||||
return fullcmd
|
||||
|
||||
def run_app(pkgname):
|
||||
cmd = get_run_command(pkgname)
|
||||
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
|
||||
|
||||
def get_output(cmd):
|
||||
'''status =0 : success'''
|
||||
status, output = commands.getstatusoutput(cmd)
|
||||
if status: raise
|
||||
return output
|
||||
|
||||
if __name__ == '__main__':
|
||||
ip = get_ip()
|
||||
print ip
|
|
@ -0,0 +1,74 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin Ltd
|
||||
# Author: Kobe Lee
|
||||
#
|
||||
# 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
"""This module provides the RatingsAndReviewsAPI class for talking to the
|
||||
ratings and reviews API, plus a few helper classes.
|
||||
"""
|
||||
|
||||
import os, sys
|
||||
reload(sys)
|
||||
sys.setdefaultencoding('utf8')
|
||||
from urllib import quote_plus
|
||||
from piston_mini_client import (
|
||||
PistonAPI,
|
||||
PistonResponseObject,
|
||||
PistonSerializable,
|
||||
returns,
|
||||
returns_json,
|
||||
returns_list_of,
|
||||
)
|
||||
from piston_mini_client.validators import validate_pattern, validate
|
||||
#from piston_mini_client import APIError
|
||||
import httplib2
|
||||
|
||||
# These are factored out as constants for if you need to work against a
|
||||
# server that doesn't support both schemes (like http-only dev servers)
|
||||
PUBLIC_API_SCHEME = 'http'
|
||||
AUTHENTICATED_API_SCHEME = 'https'
|
||||
|
||||
|
||||
class PingbackmainRequest(PistonSerializable):
|
||||
_atts = ('distro', 'version_os', 'version_youker_assistant', 'city')
|
||||
|
||||
|
||||
class PingBackPistonAPI(PistonAPI):
|
||||
"""A client for talking to the reviews and ratings API.
|
||||
|
||||
If you pass no arguments into the constructor it will try to connect to
|
||||
localhost:8000 so you probably want to at least pass in the
|
||||
``service_root`` constructor argument.
|
||||
"""
|
||||
default_content_type = 'application/x-www-form-urlencoded'
|
||||
|
||||
@returns_json
|
||||
def submit_pingback_main(self, distro, version_os, version_youker_assistant, city):
|
||||
postdata = PingbackmainRequest()
|
||||
postdata.distro = distro
|
||||
postdata.version_os = version_os
|
||||
postdata.version_youker_assistant = version_youker_assistant
|
||||
postdata.city = city
|
||||
return self._post('pingbackmain/', data=postdata, scheme=PUBLIC_API_SCHEME, content_type='application/json')
|
||||
|
||||
class ServerPingBackAPI(PistonAPI):
|
||||
default_content_type = 'application/x-www-form-urlencoded'
|
||||
|
||||
@returns_json
|
||||
def access_server_pingback(self):
|
||||
return self._get('pingnetwork/', scheme=PUBLIC_API_SCHEME)
|
|
@ -0,0 +1,66 @@
|
|||
#! /usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
### BEGIN LICENSE
|
||||
#
|
||||
# Author: Kobe Lee <xiangli@ubuntukylin.com>
|
||||
#
|
||||
# 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import shutil
|
||||
|
||||
# unzip -o test.zip -d /tmp/
|
||||
|
||||
HOME_PATH = os.path.expandvars('$HOME')
|
||||
|
||||
def generate_tmp_path(name):
|
||||
assert(isinstance(name, str))
|
||||
# dest_path = HOME_PATH + "/.config/ubuntukylin/youker-assistant/"
|
||||
dest_path = HOME_PATH + "/.cache/youker-assistant/"
|
||||
folder_path = dest_path + name
|
||||
if os.path.exists(folder_path):
|
||||
shutil.rmtree(folder_path)
|
||||
return dest_path
|
||||
|
||||
def unzip_resource(package_file):
|
||||
unziped_dir = generate_tmp_path("uk-img")
|
||||
if unziped_dir[len(unziped_dir)-1] != "/":
|
||||
unziped_dir = unziped_dir + "/"
|
||||
subprocess.call(["unzip", package_file, "-d", unziped_dir])
|
||||
dest_dir = unziped_dir + "uk-img/"
|
||||
if not os.path.exists(dest_dir):
|
||||
print("unzip '%s' to '%s' failed" % (package_file , unziped_dir))
|
||||
return False
|
||||
else:
|
||||
print "unzip ok...."
|
||||
return True
|
||||
# unziped_dir = unziped_dir + WS360_CHROME_PKGNAME
|
||||
# version = get_package_ver_from_manifest(unziped_dir)
|
||||
# if version == "0.0":
|
||||
# return False
|
||||
# extension_filedir = "/home/trusty/360-deb/"
|
||||
# shutil.copytree(unziped_dir, extension_filedir)
|
||||
# shutil.rmtree(unziped_dir)
|
||||
# return True
|
||||
|
||||
#unzip_resource("/home/trusty/uk-img.zip")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os, sys, shutil, tempfile
|
||||
import commands
|
||||
|
||||
# ensure that single instance of applet is running for each user
|
||||
class SingleInstance(object):
|
||||
|
||||
#Initialize, specifying a path to store pids
|
||||
def __init__(self,pidPath):
|
||||
|
||||
self.pidPath = pidPath
|
||||
if os.path.exists(pidPath):
|
||||
# Make sure it is not a "stale" pidFile
|
||||
pid = open(pidPath, 'r').read().strip()
|
||||
# Check list of running pids, if not running it is stale so overwrite
|
||||
pidRunning = commands.getoutput('ls -1 /proc | grep ^%s$' % pid)
|
||||
self.lasterror = True if pidRunning else False
|
||||
else:
|
||||
self.lasterror = False
|
||||
|
||||
if not self.lasterror:
|
||||
# Create a temp file, copy it to pidPath and remove temporary file
|
||||
(fp, temp_path) = tempfile.mkstemp()
|
||||
try:
|
||||
os.fdopen(fp, "w+b").write(str(os.getpid()))
|
||||
shutil.copy(temp_path, pidPath)
|
||||
os.unlink(temp_path)
|
||||
except Exception as e:
|
||||
print str(e)
|
||||
|
||||
def is_already_running(self):
|
||||
return self.lasterror
|
||||
|
||||
def __del__(self):
|
||||
if not self.lasterror:
|
||||
os.unlink(self.pidPath)
|
|
@ -0,0 +1 @@
|
|||
#!/usr/bin/python
|
|
@ -0,0 +1,252 @@
|
|||
#! /usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin Ltd
|
||||
#
|
||||
# Author: Kobe Lee <xiangli@ubuntukylin.com>
|
||||
# Maintainer: Ubuntu Kylin
|
||||
#
|
||||
# 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os
|
||||
import gtk
|
||||
import gobject
|
||||
import math
|
||||
import locale
|
||||
#samples:https://developer.gnome.org/pygtk/stable/class-gdkwindow.html
|
||||
|
||||
class TimeController(gobject.GObject):
|
||||
__gsignals__ = {
|
||||
'update': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_FLOAT,)),
|
||||
'completed': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
|
||||
}
|
||||
|
||||
def __init__(self, timeout):
|
||||
gobject.GObject.__init__(self)
|
||||
self.timeout = timeout
|
||||
self.container = []
|
||||
|
||||
def start(self):
|
||||
tmp = (self.timeout / 1000.0) * 30.0
|
||||
while len(self.container) <= tmp:
|
||||
curve = lambda x: math.sin(math.pi / 2 * x)
|
||||
self.container.append(curve(len(self.container) * (1.0 / tmp)))
|
||||
self.container.reverse()
|
||||
gobject.timeout_add(int(self.timeout / tmp), self.update)
|
||||
|
||||
def update(self):
|
||||
self.emit('update', self.container.pop())
|
||||
if len(self.container) == 0:
|
||||
self.emit('completed')
|
||||
return False
|
||||
return True
|
||||
|
||||
class WizardEventBox(gtk.EventBox):
|
||||
__gsignals__ = { 'close': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),}
|
||||
def __init__(self, slider_icons=None, pointer_icons=None, button_icons=None):
|
||||
gtk.EventBox.__init__(self)
|
||||
self.set_visible_window(False)
|
||||
self.add_events(gtk.gdk.BUTTON_PRESS_MASK |gtk.gdk.POINTER_MOTION_MASK)
|
||||
# 显示图片事件
|
||||
self.connect("expose-event", self.on_expose_event)
|
||||
# 鼠标点击滑动点的事件
|
||||
self.connect("motion-notify-event", self.on_motion_notify)
|
||||
# 鼠标事件
|
||||
self.connect("button-press-event", self.on_button_press)
|
||||
# 幻灯片图片
|
||||
self.slider_pics = map(gtk.gdk.pixbuf_new_from_file, slider_icons)
|
||||
# 幻灯片总数
|
||||
self.icon_num = len(slider_icons)
|
||||
# 滑动圆点图片设置
|
||||
self.pointer_pic, self.pointer_pic_active = map(gtk.gdk.pixbuf_new_from_file, pointer_icons)
|
||||
# 开始按钮图片设置
|
||||
self.btn_pic, self.btn_pic_press = map(gtk.gdk.pixbuf_new_from_file, button_icons)
|
||||
button_size = 55
|
||||
self.pointer_dict = {}
|
||||
self.index = 0
|
||||
self.dsc_index = None
|
||||
slider_pixbuf = self.slider_pics[0]
|
||||
self.slider_width = slider_pixbuf.get_width()
|
||||
self.slider_height = slider_pixbuf.get_height()
|
||||
self.set_size_request(self.slider_width, self.slider_height)
|
||||
self.pointer_width = self.pointer_pic.get_width()
|
||||
self.pointer_height = self.pointer_pic.get_height()
|
||||
pointer_width = self.pointer_width * self.icon_num + 10 * (self.icon_num - 1)
|
||||
self.pointer_sx = (self.slider_width - pointer_width) / 2
|
||||
self.pointer_y = self.slider_height -40
|
||||
# 开始按钮区域
|
||||
self.btn_rect = gtk.gdk.Rectangle((self.slider_width - self.btn_pic.get_width()) / 2, self.slider_height - self.btn_pic.get_height() - button_size, self.btn_pic.get_width(), self.btn_pic.get_height())
|
||||
self.alpha = 1.0
|
||||
self.active_x = 0
|
||||
self.dsc_x = None
|
||||
self.slider_y = 0
|
||||
self.showing = False
|
||||
self.show_index = None
|
||||
gobject.timeout_add(2000, lambda : self.start_slider(1000))
|
||||
|
||||
def draw_pixbuf(self, cr, pixbuf, x=0, y=0, alpha=1.0):
|
||||
if pixbuf != None:
|
||||
cr.set_source_pixbuf(pixbuf, x, y)
|
||||
cr.paint_with_alpha(alpha)
|
||||
|
||||
def on_expose_event(self, widget, event):
|
||||
# samples:http://zetcode.com/gui/pygtk/drawing/
|
||||
cr = widget.window.cairo_create()
|
||||
rect = widget.allocation
|
||||
cr.save()
|
||||
self.draw_pixbuf(cr, self.slider_pics[self.index], rect.x + self.active_x,
|
||||
rect.x + self.slider_y, self.alpha)
|
||||
if self.dsc_index != None and self.dsc_x != None:
|
||||
self.draw_pixbuf(cr, self.slider_pics[self.dsc_index], rect.x + self.dsc_x,
|
||||
rect.y + self.slider_y, self.dsc_alpha)
|
||||
cr.restore()
|
||||
dot_start_x = rect.x + self.pointer_sx
|
||||
for i in range(self.icon_num):
|
||||
if self.dsc_index == None:
|
||||
if self.index == i:
|
||||
dot_pixbuf = self.pointer_pic_active
|
||||
else:
|
||||
dot_pixbuf = self.pointer_pic
|
||||
else:
|
||||
if self.dsc_index == i:
|
||||
dot_pixbuf = self.pointer_pic_active
|
||||
else:
|
||||
dot_pixbuf = self.pointer_pic
|
||||
pointer_rect = gtk.gdk.Rectangle(
|
||||
dot_start_x, rect.y + self.pointer_y,
|
||||
self.pointer_width, self.pointer_height)
|
||||
self.pointer_dict[i] = pointer_rect
|
||||
self.draw_pixbuf(cr, dot_pixbuf, dot_start_x, rect.y + self.pointer_y)
|
||||
offset = self.pointer_width + 10
|
||||
dot_start_x += offset
|
||||
if self.dsc_index == self.icon_num - 1:
|
||||
if self.button_hover_flag:
|
||||
pixbuf = self.btn_pic_press
|
||||
else:
|
||||
pixbuf = self.btn_pic
|
||||
self.draw_pixbuf(cr, pixbuf, rect.x + self.btn_rect.x, rect.y + self.btn_rect.y)
|
||||
return True
|
||||
|
||||
def on_motion_notify(self, widget, event):
|
||||
self.show_index = None
|
||||
for index, rect in self.pointer_dict.items():
|
||||
if rect.x <= event.x <= rect.x + rect.width and rect.y <= event.y <= rect.y + rect.height:
|
||||
self.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.HAND2))
|
||||
self.show_index = index
|
||||
break
|
||||
else:
|
||||
self.show_index = None
|
||||
self.window.set_cursor(None)
|
||||
x, y, w, h = self.btn_rect
|
||||
if (event.x >= x and event.x <= x + w and event.y >= y and event.y <= y + h):
|
||||
self.button_hover_flag = True
|
||||
else:
|
||||
self.button_hover_flag = False
|
||||
self.queue_draw()
|
||||
|
||||
def on_button_press(self, widget, event):
|
||||
# 当前不是空时,重新播放
|
||||
if self.show_index != None:
|
||||
self.start_slider(1000, self.show_index)
|
||||
# 点击“开始”按钮,关闭启动界面
|
||||
x, y, w, h = self.btn_rect
|
||||
if (event.x >= x and event.x <= x + w and event.y >= y and event.y <= y + h):
|
||||
self.emit("close")
|
||||
|
||||
def start_slider(self, animation_time, dsc_index=None, direction="left"):
|
||||
if dsc_index is None:
|
||||
if self.index >= self.icon_num - 1:
|
||||
return False
|
||||
dsc_index = 0
|
||||
else:
|
||||
dsc_index = self.index + 1
|
||||
else:
|
||||
if dsc_index < self.index:
|
||||
direction = "right"
|
||||
|
||||
if not self.showing:
|
||||
self.showing = True
|
||||
self.dsc_index = dsc_index
|
||||
self.timecontroller = TimeController(animation_time)
|
||||
self.timecontroller.connect("update", lambda source, status: self.update_slider(source, status, direction))
|
||||
self.timecontroller.connect("completed", lambda source: self.complete_slider(source, dsc_index))
|
||||
self.timecontroller.start()
|
||||
return True
|
||||
|
||||
def update_slider(self, source, status, direction):
|
||||
self.alpha = 1.0 - status
|
||||
self.dsc_alpha = status
|
||||
if direction == "right":
|
||||
self.active_x = self.slider_width * status
|
||||
self.dsc_x = 0
|
||||
else:
|
||||
self.active_x = 0 - (self.slider_width * status)
|
||||
self.dsc_x = 0
|
||||
self.queue_draw()
|
||||
|
||||
def complete_slider(self, source, index):
|
||||
self.index = index
|
||||
self.alpha = 1.0
|
||||
self.dsc_alpha = 0.0
|
||||
self.showing = False
|
||||
self.active_x = 0
|
||||
self.dsc_x = None
|
||||
self.queue_draw()
|
||||
|
||||
class Wizard(gtk.Window):
|
||||
def __init__(self):
|
||||
gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
|
||||
self.set_decorated(False)#去掉默认标题栏
|
||||
self.set_position(gtk.WIN_POS_CENTER)
|
||||
self.set_resizable(False)
|
||||
self.window_align = gtk.Alignment()
|
||||
self.window_box = gtk.VBox()
|
||||
# 图片与边框的距离
|
||||
self.window_align.set(0.0, 0.0, 1.0, 1.0)
|
||||
self.window_align.set_padding(2, 2, 2, 2)
|
||||
self.add(self.window_align)
|
||||
self.window_align.add(self.window_box)
|
||||
wizard_dir = "/usr/share/youker-assistant/qml/img/zh_CN/wizard"
|
||||
wizard_root_dir = "/usr/share/youker-assistant/qml/img/icons"
|
||||
slider_icons = (os.path.join(wizard_dir, "%d.png" % i) for i in range(3))
|
||||
pointer_icons = (os.path.join(wizard_root_dir, "dot_normal.png"), os.path.join(wizard_root_dir, "dot_active.png"))
|
||||
button_icons = (os.path.join(wizard_dir, "start_normal.png"), os.path.join(wizard_dir, "start_press.png"))
|
||||
self.event_box = WizardEventBox(slider_icons, pointer_icons, button_icons)
|
||||
self.event_box.connect("close", lambda widget: self.destroy())
|
||||
self.connect("destroy", self.destroy_wizard)
|
||||
self.window_box.add(self.event_box)
|
||||
# 鼠标拖动界面
|
||||
self.move_window_event(self.event_box)
|
||||
|
||||
def destroy_wizard(self, widget):
|
||||
print 'Youker-Assistant slide show is over!'
|
||||
#widget.destory()
|
||||
|
||||
def is_left_button(self, event):
|
||||
return event.button == 1
|
||||
|
||||
def move_window(self, event, widget):#kobe
|
||||
if self.is_left_button(event):
|
||||
widget.set_can_focus(True)
|
||||
widget.grab_focus()
|
||||
self.begin_move_drag(event.button, int(event.x_root), int(event.y_root), event.time)
|
||||
return False
|
||||
|
||||
def move_window_event(self, widget):
|
||||
widget.connect("button-press-event", lambda w, e: self.move_window(e, w))
|
||||
|
||||
def show_slider(self):
|
||||
self.show_all()
|
||||
gtk.main()
|
|
@ -0,0 +1 @@
|
|||
#!/usr/bin/python
|
|
@ -0,0 +1,27 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import apt
|
||||
|
||||
class AptDaemon():
|
||||
def __init__(self):
|
||||
self.ca = apt.Cache()
|
||||
self.ca.open()
|
||||
|
||||
if __name__ == "__main__":
|
||||
pass
|
|
@ -0,0 +1,54 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
### BEGIN LICENSE
|
||||
|
||||
# Copyright (C) 2014 National University of Defense Technology(NUDT) & Kylin Ltd
|
||||
|
||||
# Author:
|
||||
# Robert <luolei@ubuntukylin.com>
|
||||
|
||||
# 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 <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os
|
||||
import errno
|
||||
from xdg import BaseDirectory as xdg
|
||||
|
||||
def safe_makedirs(dir_path):
|
||||
""" This function can be used in place of a straight os.makedirs to
|
||||
handle the possibility of a race condition when more than one
|
||||
process may potentially be creating the same directory, it will
|
||||
not fail if two processes try to create the same dir at the same
|
||||
time
|
||||
"""
|
||||
# avoid throwing an OSError, see for example LP: #743003
|
||||
if not os.path.exists(dir_path):
|
||||
try:
|
||||
os.makedirs(dir_path)
|
||||
except OSError as e:
|
||||
if e.errno == errno.EEXIST:
|
||||
# it seems that another process has already created this
|
||||
# directory in the meantime, that's ok
|
||||
pass
|
||||
else:
|
||||
# the error is due to something else, so we want to raise it
|
||||
raise
|
||||
|
||||
# ported from ubuntu-software-center to support Ubuntu-kylin-SSO
|
||||
UBUNTU_KYLIN_SSO_SERVICE = 'https://login.ubuntukylin.com/api/1.0'
|
||||
SOFTWARE_CENTER_NAME_KEYRING = "Youker ID"
|
||||
SOFTWARE_CENTER_SSO_DESCRIPTION = '注册或登录优客账号。'
|
||||
datadir = './sso/utils/'
|
||||
PISTON_GENERIC_HELPER = "piston_generic_helper.py"
|
||||
YOUKER_ASSISTANT_CACHE_DIR = os.path.join(xdg.xdg_cache_home, "youker-assistant")
|
||||
safe_makedirs(YOUKER_ASSISTANT_CACHE_DIR)
|
|
@ -0,0 +1,99 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (C) 2010 Canonical
|
||||
#
|
||||
# Authors:
|
||||
# Michael Vogt
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the GNU General Public License as published by the Free Software
|
||||
# Foundation; version 3.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
# details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along with
|
||||
# this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
from gi.repository import GObject
|
||||
|
||||
import logging
|
||||
# import os
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class LoginBackend(GObject.GObject):
|
||||
|
||||
NEW_ACCOUNT_URL = None
|
||||
FORGOT_PASSWORD_URL = None
|
||||
|
||||
__gsignals__ = {
|
||||
"login-successful": (GObject.SIGNAL_RUN_LAST,
|
||||
GObject.TYPE_NONE,
|
||||
(GObject.TYPE_PYOBJECT,),
|
||||
),
|
||||
"login-failed": (GObject.SIGNAL_RUN_LAST,
|
||||
GObject.TYPE_NONE,
|
||||
(),
|
||||
),
|
||||
"login-canceled": (GObject.SIGNAL_RUN_LAST,
|
||||
GObject.TYPE_NONE,
|
||||
(),
|
||||
),
|
||||
"need-username-password": (GObject.SIGNAL_RUN_LAST,
|
||||
GObject.TYPE_NONE,
|
||||
(),
|
||||
),
|
||||
"logout-successful": (GObject.SIGNAL_RUN_LAST,
|
||||
GObject.TYPE_NONE,
|
||||
(),
|
||||
),
|
||||
}
|
||||
|
||||
def login(self):
|
||||
raise NotImplemented
|
||||
|
||||
def login_or_register(self):
|
||||
raise NotImplemented
|
||||
|
||||
def find_credentials(self):
|
||||
raise NotImplemented
|
||||
|
||||
def cancel_login(self):
|
||||
self.emit("login-canceled")
|
||||
|
||||
def logout(self):
|
||||
raise NotImplemented
|
||||
|
||||
|
||||
def get_login_backend(window_id, appname, help_text):
|
||||
"""
|
||||
factory that returns an SSO loader singleton
|
||||
"""
|
||||
# if "SOFTWARE_CENTER_FAKE_REVIEW_API" in os.environ:
|
||||
# from backend.login_impl.login_fake import (
|
||||
# LoginBackendDbusSSOFake)
|
||||
# sso_class = LoginBackendDbusSSOFake(window_id, appname, help_text)
|
||||
# LOG.warn('Using fake login SSO functionality. Only meant for '
|
||||
# 'testing purposes')
|
||||
# else:
|
||||
from sso.login_impl.login_sso import (
|
||||
LoginBackendDbusSSO)
|
||||
sso_class = LoginBackendDbusSSO(window_id, appname, help_text)
|
||||
return sso_class
|
||||
|
||||
|
||||
#if __name__ == "__main__":
|
||||
# logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
# from models.enums import SOFTWARE_CENTER_NAME_KEYRING
|
||||
# login = get_login_backend(0, SOFTWARE_CENTER_NAME_KEYRING, "login-text")
|
||||
# login.login()
|
||||
|
||||
# from gi.repository import Gtk
|
||||
# Gtk.main()
|
|
@ -0,0 +1,145 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (C) 2010 Canonical
|
||||
#
|
||||
# Authors:
|
||||
# Michael Vogt
|
||||
# Robert <luolei@ubuntukylin.com>
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the GNU General Public License as published by the Free Software
|
||||
# Foundation; version 3.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
# details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along with
|
||||
# this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
import dbus
|
||||
import logging
|
||||
|
||||
from dbus.mainloop.glib import DBusGMainLoop
|
||||
DBusGMainLoop(set_as_default=True)
|
||||
|
||||
from ubuntu_kylin_sso import (
|
||||
DBUS_BUS_NAME,
|
||||
DBUS_CREDENTIALS_IFACE,
|
||||
DBUS_CREDENTIALS_PATH,
|
||||
)
|
||||
|
||||
from sso.login import LoginBackend
|
||||
|
||||
from sso.enums import SOFTWARE_CENTER_NAME_KEYRING
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
def utf8(s):
|
||||
"""
|
||||
Takes a string or unicode object and returns a utf-8 encoded
|
||||
string, errors are ignored
|
||||
"""
|
||||
if s is None:
|
||||
return None
|
||||
if isinstance(s, unicode):
|
||||
return s.encode("utf-8", "ignore")
|
||||
return unicode(s, "utf8", "ignore").encode("utf8")
|
||||
|
||||
class LoginBackendDbusSSO(LoginBackend):
|
||||
|
||||
def __init__(self, window_id, appname, help_text):
|
||||
super(LoginBackendDbusSSO, self).__init__()
|
||||
if not appname:
|
||||
self.appname = SOFTWARE_CENTER_NAME_KEYRING
|
||||
else:
|
||||
self.appname = appname
|
||||
self.help_text = help_text
|
||||
self.bus = dbus.SessionBus()
|
||||
obj = self.bus.get_object(bus_name=DBUS_BUS_NAME,
|
||||
object_path=DBUS_CREDENTIALS_PATH,
|
||||
follow_name_owner_changes=True)
|
||||
self.proxy = dbus.Interface(object=obj,
|
||||
dbus_interface=DBUS_CREDENTIALS_IFACE)
|
||||
self.proxy.connect_to_signal("CredentialsFound",
|
||||
self._on_credentials_found)
|
||||
self.proxy.connect_to_signal("CredentialsNotFound",
|
||||
self._on_credentials_not_found)
|
||||
self.proxy.connect_to_signal("CredentialsError",
|
||||
self._on_credentials_error)
|
||||
self.proxy.connect_to_signal("AuthorizationDenied",
|
||||
self._on_authorization_denied)
|
||||
self.proxy.connect_to_signal("CredentialsCleared",
|
||||
self._on_credential_cleared)
|
||||
self._window_id = window_id
|
||||
self._credentials = None
|
||||
|
||||
def _get_params(self):
|
||||
p = {}
|
||||
if self.help_text:
|
||||
p['help_text'] = utf8(self.help_text)
|
||||
if self._window_id:
|
||||
p['window_id'] = self._window_id
|
||||
return p
|
||||
|
||||
def find_credentials(self):
|
||||
LOG.debug("find_credentials()")
|
||||
self._credentials = None
|
||||
self.proxy.find_credentials(self.appname, self._get_params())
|
||||
|
||||
def login(self):
|
||||
LOG.debug("login()")
|
||||
self._credentials = None
|
||||
self.proxy.login(self.appname, self._get_params())
|
||||
|
||||
def login_or_register(self):
|
||||
LOG.debug("login_or_register()")
|
||||
self._credentials = None
|
||||
# print "login_sso::login_or_register:", self.appname, self._get_params()
|
||||
self.proxy.register(self.appname, self._get_params())
|
||||
|
||||
def logout(self):
|
||||
LOG.debug("login_or_register()")
|
||||
self._credentials = None
|
||||
self.proxy.clear_credentials(self.appname, {})
|
||||
|
||||
def _on_credentials_not_found(self, app_name):
|
||||
LOG.debug("_on_credentials_not_found for '%s'" % app_name)
|
||||
if app_name != self.appname:
|
||||
return
|
||||
self.emit("login-failed")
|
||||
|
||||
def _on_credentials_found(self, app_name, credentials):
|
||||
LOG.debug("_on_credentials_found for '%s'" % app_name)
|
||||
if app_name != self.appname:
|
||||
return
|
||||
# only emit signal here once, otherwise it may happen that a
|
||||
# different process that triggers the on the dbus triggers
|
||||
# another signal emission here!
|
||||
if self._credentials != credentials:
|
||||
self.emit("login-successful", credentials)
|
||||
self._credentials = credentials
|
||||
|
||||
def _on_credentials_error(self, app_name, error, detailed_error=""):
|
||||
LOG.error("_on_credentials_error for %s: %s (%s)" % (
|
||||
app_name, error, detailed_error))
|
||||
if app_name != self.appname:
|
||||
return
|
||||
# FIXME: do something useful with the error
|
||||
self.emit("login-failed")
|
||||
|
||||
def _on_authorization_denied(self, app_name):
|
||||
LOG.info("_on_authorization_denied: %s" % app_name)
|
||||
if app_name != self.appname:
|
||||
return
|
||||
self.cancel_login()
|
||||
self.emit("login-canceled")
|
||||
|
||||
def _on_credential_cleared(self, app_name):
|
||||
LOG.info("_on_credential_cleared: %s" % app_name)
|
||||
if app_name != self.appname:
|
||||
return
|
||||
self.emit("logout-successful")
|
|
@ -0,0 +1,23 @@
|
|||
from piston_mini_client import PistonAPI, returns_json
|
||||
from piston_mini_client.validators import oauth_protected
|
||||
|
||||
# These are factored out as constants for if you need to work against a
|
||||
# server that doesn't support both schemes (like http-only dev servers)
|
||||
PUBLIC_API_SCHEME = 'http'
|
||||
AUTHENTICATED_API_SCHEME = 'https'
|
||||
|
||||
|
||||
# this is only here because:
|
||||
# a) ubuntu-sso-client does not support verifying if the credentials
|
||||
# are still valid
|
||||
# b) the restful client interface is not really needed because we just
|
||||
# need this one single call
|
||||
class UbuntuSsoAPI(PistonAPI):
|
||||
default_service_root = 'http://localhost:8000/api/2.0'
|
||||
|
||||
@oauth_protected
|
||||
@returns_json
|
||||
def whoami(self, id=None):
|
||||
# return self._get('accounts?ws.op=me',
|
||||
# scheme=AUTHENTICATED_API_SCHEME)
|
||||
return self._get('accounts?ws.op=me')
|
|
@ -0,0 +1,275 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (C) 2010 Canonical
|
||||
#
|
||||
# Authors:
|
||||
# Michael Vogt
|
||||
# Robert <luolei@ubuntukylin.com>
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify it under
|
||||
# the terms of the GNU General Public License as published by the Free Software
|
||||
# Foundation; version 3.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
||||
# details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License along with
|
||||
# this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
|
||||
from gi.repository import GObject, GLib
|
||||
from gettext import gettext as _
|
||||
|
||||
import logging
|
||||
# import os
|
||||
|
||||
import piston_mini_client.auth
|
||||
import piston_mini_client.failhandlers
|
||||
|
||||
# mostly for testing
|
||||
#from fake_review_settings import FakeReviewSettings, network_delay
|
||||
#from spawn_helper import SpawnHelper
|
||||
|
||||
from login import get_login_backend
|
||||
|
||||
from piston.ubuntusso_pristine import (
|
||||
UbuntuSsoAPI as PristineUbuntuSsoAPI,
|
||||
)
|
||||
# patch default_service_root to the one we use
|
||||
from enums import UBUNTU_KYLIN_SSO_SERVICE
|
||||
# *Don't* append /api/1.0, as it's already included in UBUNTU_SSO_SERVICE
|
||||
PristineUbuntuSsoAPI.default_service_root = UBUNTU_KYLIN_SSO_SERVICE
|
||||
|
||||
from enums import (
|
||||
SOFTWARE_CENTER_NAME_KEYRING,
|
||||
SOFTWARE_CENTER_SSO_DESCRIPTION,
|
||||
)
|
||||
import dbus
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class UbuntuSSO(GObject.GObject):
|
||||
""" Ubuntu SSO interface using the oauth token from the keyring
|
||||
|
||||
The methods that work synchronously are suffixed with _sync()
|
||||
"""
|
||||
__gsignals__ = {
|
||||
"whoami": (GObject.SIGNAL_RUN_LAST,
|
||||
GObject.TYPE_NONE,
|
||||
(GObject.TYPE_PYOBJECT,),
|
||||
),
|
||||
"logout": (GObject.SIGNAL_RUN_LAST,
|
||||
GObject.TYPE_NONE,
|
||||
(),
|
||||
),
|
||||
"fail": (GObject.SIGNAL_RUN_LAST,
|
||||
GObject.TYPE_NONE,
|
||||
(),
|
||||
),
|
||||
"error": (GObject.SIGNAL_RUN_LAST,
|
||||
GObject.TYPE_NONE,
|
||||
(GObject.TYPE_PYOBJECT,),
|
||||
),
|
||||
}
|
||||
|
||||
def __init__(self, xid=0):
|
||||
GObject.GObject.__init__(self)
|
||||
self.oauth = None
|
||||
self.xid = xid
|
||||
self.show_register = True
|
||||
self.sso = get_login_backend(
|
||||
self.xid,
|
||||
SOFTWARE_CENTER_NAME_KEYRING,
|
||||
_(SOFTWARE_CENTER_SSO_DESCRIPTION))
|
||||
self.sso.connect("login-successful", self._dbus_maybe_login_successful)
|
||||
self.sso.connect("login-failed", self._fail)
|
||||
self.sso.connect("login-canceled", self._fail)
|
||||
self.sso.connect("logout-successful", self._logout_successful)
|
||||
|
||||
def set_show_register(self, show):
|
||||
self.show_register = not not show
|
||||
|
||||
def whoami(self, token):
|
||||
auth = piston_mini_client.auth.OAuthAuthorizer(
|
||||
token["token"], token["token_secret"],
|
||||
token["consumer_key"], token["consumer_secret"])
|
||||
api = PristineUbuntuSsoAPI(auth=auth)
|
||||
try:
|
||||
res = api.whoami()
|
||||
except piston_mini_client.failhandlers.APIError as e:
|
||||
print "api.whoami failed with APIError: '%s'" % e
|
||||
LOG.exception("api.whoami failed with APIError: '%s'" % e)
|
||||
if len(res) == 0:
|
||||
self.emit("error")
|
||||
self.oauth = None
|
||||
else:
|
||||
self.emit("whoami", res)
|
||||
|
||||
def _dbus_maybe_login_successful(self, sso_backend, oauth_result):
|
||||
# LOG.debug("_login_successful")
|
||||
# print("ubuntusso::_login_successful oauth_result: %s" % oauth_result)
|
||||
self.oauth = oauth_result
|
||||
self.whoami(self.oauth)
|
||||
# self.loop.quit()
|
||||
|
||||
# def verify_token(self, token):
|
||||
# """ Verify that the token is valid
|
||||
#
|
||||
# Note that this may raise httplib2 exceptions if the server
|
||||
# is not reachable
|
||||
# """
|
||||
# # LOG.debug("verify_token")
|
||||
# auth = piston_mini_client.auth.OAuthAuthorizer(
|
||||
# token["token"], token["token_secret"],
|
||||
# token["consumer_key"], token["consumer_secret"])
|
||||
# api = PristineUbuntuSsoAPI(auth=auth)
|
||||
# try:
|
||||
# res = api.whoami()
|
||||
# except piston_mini_client.failhandlers.APIError as e:
|
||||
# print "api.whoami failed with APIError: '%s'" % e
|
||||
# LOG.exception("api.whoami failed with APIError: '%s'" % e)
|
||||
# return False
|
||||
# return len(res) > 0
|
||||
|
||||
def clear_token(self):
|
||||
# clear_token_from_ubuntu_sso_sync(SOFTWARE_CENTER_NAME_KEYRING)
|
||||
# sso = self. _get_login_backend_and_connect()
|
||||
self.sso.logout()
|
||||
# GLib.timeout_add_seconds(2, self.loop.quit())
|
||||
# self.loop.run()
|
||||
# return True
|
||||
|
||||
# def _get_login_backend_and_connect(self):
|
||||
# sso = get_login_backend(
|
||||
# self.xid,
|
||||
# SOFTWARE_CENTER_NAME_KEYRING,
|
||||
# _(SOFTWARE_CENTER_SSO_DESCRIPTION))
|
||||
# sso.connect("login-successful", self._dbus_maybe_login_successful)
|
||||
# sso.connect("login-failed", self._fail)
|
||||
# sso.connect("login-canceled", self._fail)
|
||||
# sso.connect("logout-successful", self._logout_successful)
|
||||
# return sso
|
||||
|
||||
def _fail(self, sso_backend):
|
||||
self.emit("fail")
|
||||
|
||||
def _logout_successful(self, sso_backend):
|
||||
self.oauth = None
|
||||
self.emit("logout")
|
||||
|
||||
def find_oauth_token(self):
|
||||
self.oauth = None
|
||||
# sso = self. _get_login_backend_and_connect()
|
||||
self.sso.find_credentials()
|
||||
# self.loop.run()
|
||||
# return self.oauth
|
||||
|
||||
def get_oauth_token(self):
|
||||
self.oauth = None
|
||||
# sso = self. _get_login_backend_and_connect()
|
||||
if self.show_register:
|
||||
self.sso.login_or_register()
|
||||
else:
|
||||
self.sso.login()
|
||||
# self.loop.run()
|
||||
# return self.oauth
|
||||
|
||||
# def get_oauth_token_and_verify(self, no_relogin=False):
|
||||
# token = self.oauth
|
||||
# # check if the token is valid and reset it if not
|
||||
# if token:
|
||||
# # verify token will return false if there is a API error,
|
||||
# # but there may be httplib2 errors if there is no network,
|
||||
# # so ignore them
|
||||
# try:
|
||||
# if not self.verify_token(token):
|
||||
# attempt_relogin = not no_relogin
|
||||
# if attempt_relogin:
|
||||
# self.clear_token()
|
||||
# # re-trigger login once
|
||||
# token = self.get_oauth_token()
|
||||
# else:
|
||||
# return None
|
||||
# except Exception as e:
|
||||
# print "token could not be verified (network problem?): %s" % e
|
||||
# LOG.warn(
|
||||
# "token could not be verified (network problem?): %s" % e)
|
||||
# return token
|
||||
#
|
||||
# def find_oauth_token_and_verify(self):
|
||||
# token = self.find_oauth_token()
|
||||
# # check if the token is valid and reset it if not
|
||||
# if token:
|
||||
# # verify token will return false if there is a API error,
|
||||
# # but there may be httplib2 errors if there is no network,
|
||||
# # so ignore them
|
||||
# try:
|
||||
# self.verify_token(token)
|
||||
# except Exception as e:
|
||||
# print "token could not be verified (network problem?): %s" % e
|
||||
# LOG.warn(
|
||||
# "token could not be verified (network problem?): %s" % e)
|
||||
# return token
|
||||
|
||||
|
||||
def get_ubuntu_sso_backend(): #get_ubuntu_sso_backend(xid):
|
||||
"""
|
||||
factory that returns an ubuntu sso loader singleton
|
||||
"""
|
||||
# if "SOFTWARE_CENTER_FAKE_REVIEW_API" in os.environ:
|
||||
# ubuntu_sso_class = UbuntuSSOAPIFake()
|
||||
# LOG.warn('Using fake Ubuntu SSO API. Only meant for testing purposes')
|
||||
# else:
|
||||
ubuntu_sso_class = UbuntuSSO() #UbuntuSSO(xid)
|
||||
return ubuntu_sso_class
|
||||
|
||||
|
||||
# # test code
|
||||
# def _login_success(lp, token):
|
||||
# print "success", lp, token
|
||||
#
|
||||
#
|
||||
# def _login_failed(lp):
|
||||
# print "fail", lp
|
||||
#
|
||||
#
|
||||
# def _login_need_user_and_password(sso):
|
||||
# import sys
|
||||
# sys.stdout.write("user: ")
|
||||
# sys.stdout.flush()
|
||||
# user = sys.stdin.readline().strip()
|
||||
# sys.stdout.write("pass: ")
|
||||
# sys.stdout.flush()
|
||||
# password = sys.stdin.readline().strip()
|
||||
# sso.login(user, password)
|
||||
#
|
||||
#
|
||||
# # interactive test code
|
||||
# if __name__ == "__main__":
|
||||
# def _whoami(sso, result):
|
||||
# print "res: ", result
|
||||
# Gtk.main_quit()
|
||||
#
|
||||
# def _error(sso, result):
|
||||
# print "err: ", result
|
||||
# Gtk.main_quit()
|
||||
#
|
||||
# def _dbus_maybe_login_successful(ssologin, oauth_result):
|
||||
# print "got token, verify it now"
|
||||
# sso = UbuntuSSO()
|
||||
# sso.connect("whoami", _whoami)
|
||||
# sso.connect("error", _error)
|
||||
# sso.whoami()
|
||||
#
|
||||
# from gi.repository import Gtk
|
||||
# # logging.basicConfig(level=logging.DEBUG)
|
||||
# # softwarecenter.paths.datadir = "./data"
|
||||
#
|
||||
# backend = get_login_backend("", "appname", "help_text")
|
||||
# backend.connect("login-successful", _dbus_maybe_login_successful)
|
||||
# backend.login_or_register()
|
||||
# Gtk.main()
|
|
@ -0,0 +1,40 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2007-2011 Tualatrix Chou <tualatrix@gmail.com>
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os, sys
|
||||
import dbus
|
||||
import signal
|
||||
import dbus.mainloop.glib
|
||||
from gi.repository import GObject
|
||||
from single import SingleInstance
|
||||
#import gobject
|
||||
|
||||
if __name__ == '__main__':
|
||||
myapp = SingleInstance("/tmp/youker-assistant-sessiondbus-%d.pid" % os.getuid())
|
||||
if myapp.is_already_running():
|
||||
print "Another instance of this sessiondbus is already running"
|
||||
sys.exit("Another instance of this sessiondbus is already running")
|
||||
from sessiondbus.daemon import SessionDaemon
|
||||
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
|
||||
GObject.threads_init()
|
||||
mainloop = GObject.MainLoop()
|
||||
#gobject.threads_init()
|
||||
#mainloop = gobject.MainLoop()
|
||||
signal.signal(signal.SIGINT, lambda : mainloop.quit())
|
||||
SessionDaemon(mainloop)
|
||||
mainloop.run()
|
|
@ -0,0 +1,44 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import os, sys
|
||||
import signal
|
||||
import dbus
|
||||
import dbus.mainloop.glib
|
||||
from gi.repository import GObject
|
||||
from single import SingleInstance
|
||||
#import gobject
|
||||
|
||||
if __name__ == '__main__':
|
||||
myapp = SingleInstance("/tmp/youker-assistant-systemdbus-%d.pid" % os.getuid())
|
||||
if myapp.is_already_running():
|
||||
print "Another instance of this systemdbus is already running"
|
||||
sys.exit("Another instance of this systemdbus is already running")
|
||||
os.environ["TERM"] = "xterm"
|
||||
os.environ["PATH"] = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin"
|
||||
os.environ["DEBIAN_FRONTEND"] = "noninteractive"
|
||||
if os.path.exists("/var/lib/apt/lists/lock"):
|
||||
os.remove("/var/lib/apt/lists/lock")
|
||||
from systemdbus.daemon import Daemon
|
||||
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
|
||||
GObject.threads_init()
|
||||
mainloop = GObject.MainLoop()
|
||||
#gobject.threads_init()
|
||||
#mainloop = gobject.MainLoop()
|
||||
signal.signal(signal.SIGINT, lambda : mainloop.quit())
|
||||
Daemon(dbus.SystemBus(), mainloop)
|
||||
mainloop.run()
|
|
@ -0,0 +1,259 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import sys
|
||||
import os
|
||||
from gi.repository import GLib
|
||||
import platform
|
||||
import math
|
||||
import apt
|
||||
|
||||
NO_UPDATE_WARNING_DAYS = 7
|
||||
FILEPATH = "/etc/lsb-release"
|
||||
RELEASEPATH = "/etc/ubuntukylin-release"
|
||||
|
||||
KILOBYTE_FACTOR = 1000.0
|
||||
MEGABYTE_FACTOR = (1000.0 * 1000.0)
|
||||
GIGABYTE_FACTOR = (1000.0 * 1000.0 * 1000.0)
|
||||
TERABYTE_FACTOR = (1000.0 * 1000.0 * 1000.0 * 1000.0)
|
||||
|
||||
def get_human_read_capacity_size(size):
|
||||
size_str = ""
|
||||
displayed_size = 0.0
|
||||
unit = "KB"
|
||||
|
||||
if size < MEGABYTE_FACTOR:
|
||||
displayed_size = float(size/KILOBYTE_FACTOR)
|
||||
unit = "KB"
|
||||
elif size < GIGABYTE_FACTOR:
|
||||
displayed_size = float(size/MEGABYTE_FACTOR)
|
||||
unit = "MB"
|
||||
elif size < TERABYTE_FACTOR:
|
||||
displayed_size = float(size/GIGABYTE_FACTOR)
|
||||
unit = "GB"
|
||||
else:
|
||||
displayed_size = float(size/TERABYTE_FACTOR)
|
||||
unit = "TB"
|
||||
#print "displayed_size=", round(displayed_size)
|
||||
#round 不是简单的四舍五入,而是ROUND_HALF_EVEN的策略
|
||||
#ceil 取大于或者等于x的最小整数
|
||||
#floor 取小于或者等于x的最大整数
|
||||
#print round(2.5)#3.0
|
||||
#print math.ceil(2.5)#3.0
|
||||
#print math.floor(2.5)#2.0
|
||||
#print round(2.3)#2.0
|
||||
#print math.ceil(2.3)#3.0
|
||||
#print math.floor(2.3)#2.0
|
||||
str_list = [str(int(round(displayed_size))), unit]
|
||||
size_str = " ".join(str_list)
|
||||
return size_str
|
||||
|
||||
|
||||
class Sysinfo:
|
||||
CACHE_FLAG = ''
|
||||
CACHE_PACKAGES = ''
|
||||
CACHE_SIZE = ''
|
||||
CPU = ''
|
||||
RAM = ''
|
||||
HOSTNAME = ''
|
||||
PLATFORM = ''
|
||||
DISTRO = ''
|
||||
DESKTOP_FULLNAME = ''
|
||||
UPDATE_TIME = ''
|
||||
CURRENT_USER = ''
|
||||
HOME_DIRECTORY = ''
|
||||
SHELL = ''
|
||||
LANGUAGE = ''
|
||||
|
||||
def __init__(self):
|
||||
self.CACHE_FLAG = 'a'
|
||||
self.CACHE_PACKAGES = 'b'
|
||||
self.CACHE_SIZE = 'c'
|
||||
self.CPU = 'd'
|
||||
self.RAM = 'e'
|
||||
self.HOSTNAME = 'f'
|
||||
self.PLATFORM = 'g'
|
||||
self.DISTRO = 'h'
|
||||
self.DESKTOP_FULLNAME = 'i'
|
||||
self.UPDATE_TIME = 'j'
|
||||
self.CURRENT_USER = 'k'
|
||||
self.HOME_DIRECTORY = 'l'
|
||||
self.SHELL = 'm'
|
||||
self.LANGUAGE = 'n'
|
||||
|
||||
def get_sys_msg(self):
|
||||
CLIPS_DICT = {}
|
||||
CLIPS_DICT['currrent_user'], CLIPS_DICT['home_path'], CLIPS_DICT['terminal'], CLIPS_DICT['language'] = self.get_userinfo()
|
||||
CLIPS_DICT['distribution'] = self.get_distro()
|
||||
CLIPS_DICT['desktopenvironment'] = self.get_desktop()
|
||||
CLIPS_DICT['hostname'], CLIPS_DICT['machine'] = self.get_systeminfo()
|
||||
CLIPS_DICT['cpu'], CLIPS_DICT['ram'] = self.get_hardwareinfo()
|
||||
return CLIPS_DICT
|
||||
|
||||
def get_userinfo(self):
|
||||
dict = {}
|
||||
dict['username'] = GLib.get_user_name()
|
||||
dict['homedir'] = GLib.get_home_dir()
|
||||
dict['terminal'] = GLib.getenv('SHELL')
|
||||
dict['lang'] = GLib.getenv('LANG')
|
||||
return dict['username'], dict['homedir'],dict['terminal'],dict['lang']
|
||||
|
||||
def get_distro(self):
|
||||
'''It should be: DISTRIB_DESCRIPTION="UbuntuKylin 13.10'''
|
||||
#FILEPATH RELEASEPATH
|
||||
distro = ""
|
||||
if os.path.exists(RELEASEPATH):
|
||||
with open(RELEASEPATH, "r") as fsys:
|
||||
for line in fsys:
|
||||
if line.startswith("DISTRIB_DESCRIPTION"):
|
||||
tmp = line
|
||||
break
|
||||
# kobe: remove '"' and '\n'
|
||||
front = tmp.split('=')[1].replace('"', '').replace('\n', '') #(LP: #1240862)
|
||||
distro = front + '-' + platform.dist()[2]
|
||||
elif os.path.exists("/etc/os-release"):
|
||||
with open("/etc/os-release", "r") as fsys:
|
||||
for line in fsys:
|
||||
if line.startswith("PRETTY_NAME"):
|
||||
tmp = line
|
||||
break
|
||||
distro = tmp.split('=')[1].replace('"', '').replace('\n', '')
|
||||
else:
|
||||
a = platform.dist()[0]
|
||||
b = platform.dist()[1]
|
||||
c = platform.dist()[2]
|
||||
distro = '-'.join((a,b,c))
|
||||
# if not os.path.exists(RELEASEPATH):
|
||||
# with open(FILEPATH, "r") as fsys:
|
||||
# for line in fsys:
|
||||
# if line.startswith("DISTRIB_DESCRIPTION"):
|
||||
# tmp = line
|
||||
# break
|
||||
# # kobe: remove '"' and '\n'
|
||||
# front = tmp.split('=')[1].replace('"', '').replace('\n', '') #(LP: #1240862)
|
||||
# if front.startswith("UbuntuKylin") or front.startswith("Ubuntu Kylin"):
|
||||
# distro = front + '-' + platform.dist()[2]
|
||||
# else:
|
||||
# a = platform.dist()[0]
|
||||
# b = platform.dist()[1]
|
||||
# c = platform.dist()[2]
|
||||
# distro = '-'.join((a,b,c))
|
||||
# else:
|
||||
# with open(RELEASEPATH, "r") as fp:
|
||||
# for line in fp:
|
||||
# if line.startswith("DISTRIB_ID"):
|
||||
# tmp1 = line
|
||||
# elif line.startswith("DISTRIB_RELEASE"):
|
||||
# tmp2 = line
|
||||
# elif line.startswith("DISTRIB_CODENAME"):
|
||||
# tmp3 = line
|
||||
# # kobe: remove '"' and '\n'
|
||||
# id = tmp1.split('=')[1].replace('"', '').replace('\n', '')
|
||||
# release = tmp2.split('=')[1].replace('"', '').replace('\n', '')
|
||||
# codename = tmp3.split('=')[1].replace('"', '').replace('\n', '')
|
||||
# distro = '-'.join((id, release, codename))
|
||||
return distro
|
||||
|
||||
def get_desktop(self):
|
||||
apt_cache = apt.Cache()
|
||||
try:
|
||||
package = apt_cache["kylin-menu"]
|
||||
except:
|
||||
package = None
|
||||
if package is not None and package.is_installed:
|
||||
return "UKUI"
|
||||
desktop_dict = {'ubuntu': 'Unity',
|
||||
'ubuntu-2d': 'Unity 2D',
|
||||
'gnome': 'GNOME Shell',
|
||||
'gnome-classic': 'GNOME Classic',
|
||||
'gnome-shell': 'GNOME Shell',
|
||||
'gnome-fallback': 'GNOME Fallback',
|
||||
'pantheon': 'elementary OS (Luna)',
|
||||
'Lubutu': 'LXDE',
|
||||
}
|
||||
try:
|
||||
desktop_name = os.getenv('XDG_CURRENT_DESKTOP')
|
||||
if desktop_name is None:
|
||||
desktop_name = os.getenv('XDG_SESSION_DESKTOP')
|
||||
if desktop_name is None:
|
||||
desktop_name = "N/A"
|
||||
return desktop_name
|
||||
except Exception as e:
|
||||
print e
|
||||
desktop = os.getenv('DESKTOP_SESSION')
|
||||
if desktop in desktop_dict:
|
||||
return desktop_dict[desktop]
|
||||
else:
|
||||
if desktop:
|
||||
return 'Unknown (%s)' % desktop
|
||||
else:
|
||||
return 'Unknown'
|
||||
|
||||
|
||||
def get_systeminfo(self):
|
||||
return platform.node() , platform.processor()
|
||||
|
||||
def get_hardwareinfo(self):
|
||||
model_name = 'N/A'
|
||||
# MemTotal2 = ''
|
||||
MemSize = None
|
||||
# CPU
|
||||
with open('/proc/cpuinfo') as f:
|
||||
for line in f:
|
||||
if line.strip():
|
||||
if line.rstrip('\n').startswith('model name'):
|
||||
model_name = line.rstrip('\n').split(':')[1]
|
||||
break
|
||||
elif line.rstrip('\n').startswith('Hardware'):
|
||||
model_name = line.rstrip('\n').split(':')[1].strip()
|
||||
break
|
||||
# Memory
|
||||
# with open('/proc/meminfo') as f:
|
||||
# for line in f:
|
||||
# if line.strip():
|
||||
# if line.rstrip('\n').startswith('MemTotal'):
|
||||
# MemTotal = line.rstrip('\n').split(':')[1].strip()
|
||||
# MemTotal1 = MemTotal.split(' ')[0]
|
||||
# #MemTotal2 = GLib.format_size_for_display(int(MemTotal1) * 1024)
|
||||
# MemTotal2 = str(round(float(MemTotal1) / (1000 ** 2), 1)) + "G"
|
||||
# break
|
||||
|
||||
with open('/proc/meminfo') as f:
|
||||
for line in f:
|
||||
if line.strip():
|
||||
if line.rstrip('\n').startswith('MemTotal'):
|
||||
MemTotal = line.rstrip('\n').split(':')[1].strip()
|
||||
MemTmp = MemTotal.split(' ')[0]
|
||||
#print "MemTmp=",MemTmp
|
||||
#MemTmp = 1000204886#8156252#7889972
|
||||
MemSize = get_human_read_capacity_size(int(MemTmp)*1000)
|
||||
break
|
||||
if MemSize is None:
|
||||
MemSize = "N/A"
|
||||
return model_name,str(MemSize)
|
||||
# return model_name,MemTotal2
|
||||
|
||||
def get_codename(self):
|
||||
codename = platform.dist()[2]
|
||||
return codename
|
||||
|
||||
if __name__ == '__main__':
|
||||
c = Sysinfo()
|
||||
print(c.get_sys_msg())
|
||||
import getpass
|
||||
print(getpass.getuser())
|
|
@ -0,0 +1 @@
|
|||
#!/usr/bin/python
|
|
@ -0,0 +1,328 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import apt
|
||||
import apt.progress.base as apb
|
||||
from apt.debfile import DebPackage
|
||||
from apt.cache import FetchFailedException
|
||||
|
||||
import locale
|
||||
|
||||
# application actions
|
||||
class AppActions:
|
||||
INSTALLDEPS = "install_deps"
|
||||
INSTALLDEBFILE = "install_debfile"
|
||||
INSTALL = "install"
|
||||
REMOVE = "remove"
|
||||
UPGRADE = "upgrade"
|
||||
CANCEL = "cancel"
|
||||
APPLY = "apply_changes"
|
||||
PURCHASE = "purchase"
|
||||
UPDATE = "update"
|
||||
UPDATE_FIRST = "update_first"
|
||||
ADD_SOURCE = "add_source"
|
||||
REMOVE_SOURCE = "remove_source"
|
||||
GET_SOURCES = "get_sources"
|
||||
|
||||
|
||||
class FetchProcess(apb.AcquireProgress):
|
||||
|
||||
def __init__(self, dbus_service, appname, action):
|
||||
apb.AcquireProgress.__init__(self)
|
||||
self.dbus_service = dbus_service
|
||||
self.appname = appname
|
||||
self.action = action
|
||||
|
||||
def done(self, item):
|
||||
# kwarg = {"download_appname":self.appname,
|
||||
# "download_percent":str(self.percent),
|
||||
# "action":str(self.action),
|
||||
# }
|
||||
kwarg = []
|
||||
kwarg.append(self.appname)
|
||||
kwarg.append(str(self.percent))
|
||||
kwarg.append(str(self.action))
|
||||
|
||||
self.dbus_service.youker_fetch_signal("down_done", kwarg)
|
||||
|
||||
def fail(self, item):
|
||||
# kwarg = {"download_appname":self.appname,
|
||||
# "download_percent":str(self.percent),
|
||||
# "action":str(self.action),
|
||||
# }
|
||||
kwarg = []
|
||||
kwarg.append(self.appname)
|
||||
kwarg.append(str(self.percent))
|
||||
kwarg.append(str(self.action))
|
||||
self.dbus_service.youker_fetch_signal("down_fail", kwarg)
|
||||
|
||||
def fetch(self, item):
|
||||
# kwarg = {"download_appname":self.appname,
|
||||
# "download_percent":str(self.percent),
|
||||
# "action":str(self.action),
|
||||
# }
|
||||
kwarg = []
|
||||
kwarg.append(self.appname)
|
||||
kwarg.append(str(self.percent))
|
||||
kwarg.append(str(self.action))
|
||||
self.dbus_service.youker_fetch_signal("down_fetch", kwarg)
|
||||
|
||||
def ims_hit(self, item):
|
||||
print 'ims_hit'
|
||||
pass
|
||||
|
||||
def media_change(self, media, drive):
|
||||
print 'media_change'
|
||||
pass
|
||||
|
||||
def pulse(self, owner):
|
||||
|
||||
if self.action == AppActions.UPDATE or self.action == AppActions.UPDATE_FIRST:
|
||||
if self.total_items!= 0:
|
||||
percent = float(self.current_items * 100.0 / self.total_items)
|
||||
if percent > self.percent:
|
||||
self.percent = percent
|
||||
else:
|
||||
if self.total_bytes != 0:
|
||||
self.percent = float(self.current_bytes * 100.0 / self.total_bytes)
|
||||
|
||||
# kwarg = {"download_appname":self.appname,
|
||||
# "download_percent":str(self.percent),
|
||||
# "download_bytes":str(self.current_bytes),
|
||||
# "total_bytes":str(self.total_bytes),
|
||||
# "download_items":str(self.current_items),
|
||||
# "total_items":str(self.total_items),
|
||||
# "action":str(self.action),
|
||||
# }
|
||||
kwarg = []
|
||||
kwarg.append(self.appname)
|
||||
kwarg.append(str(self.percent))
|
||||
kwarg.append(str(self.action))
|
||||
kwarg.append(self.current_bytes)
|
||||
kwarg.append(str(self.total_bytes))
|
||||
kwarg.append(str(self.current_items))
|
||||
kwarg.append(str(self.total_items))
|
||||
self.dbus_service.youker_fetch_signal("down_pulse", kwarg)
|
||||
|
||||
# cancel the operation
|
||||
if self.dbus_service.check_cancel_worker_item(self.appname) is True:
|
||||
print "download_cancel"
|
||||
self.dbus_service.youker_fetch_signal("down_cancel", kwarg)
|
||||
return False
|
||||
|
||||
def start(self):
|
||||
# Reset all our values.
|
||||
self.current_bytes = 0.0
|
||||
self.current_cps = 0.0
|
||||
self.current_items = 0
|
||||
self.elapsed_time = 0
|
||||
self.fetched_bytes = 0.0
|
||||
self.last_bytes = 0.0
|
||||
self.total_bytes = 0.0
|
||||
self.total_items = 0
|
||||
self.percent = 0
|
||||
|
||||
# kwarg = {"download_appname":self.appname,
|
||||
# "download_percent":str(self.percent),
|
||||
# "action":str(self.action),
|
||||
# }
|
||||
kwarg = []
|
||||
kwarg.append(self.appname)
|
||||
kwarg.append(str(self.percent))
|
||||
kwarg.append(str(self.action))
|
||||
self.dbus_service.youker_fetch_signal("down_start", kwarg)
|
||||
|
||||
def stop(self):
|
||||
# kwarg = {"download_appname":self.appname,
|
||||
# "download_percent":str(200),
|
||||
# "action":str(self.action),
|
||||
# }
|
||||
kwarg = []
|
||||
kwarg.append(self.appname)
|
||||
kwarg.append(str(200))
|
||||
kwarg.append(str(self.action))
|
||||
self.dbus_service.youker_fetch_signal("down_stop", kwarg)
|
||||
|
||||
|
||||
class AptProcess(apb.InstallProgress):
|
||||
'''Apt progress'''
|
||||
def __init__(self, dbus_service, appname, action):
|
||||
apb.InstallProgress.__init__(self)
|
||||
self.dbus_service = dbus_service
|
||||
self.appname = appname
|
||||
self.percent = 0
|
||||
self.action = action
|
||||
|
||||
def conffile(self, current, new):
|
||||
pass
|
||||
|
||||
def error(self, pkg, errormsg):
|
||||
# kwarg = {"apt_appname":str(pkg),
|
||||
# "apt_percent":str(self.percent),
|
||||
# "action":str(self.action),
|
||||
# }
|
||||
kwarg = []
|
||||
kwarg.append(str(pkg))
|
||||
kwarg.append(str(self.percent))
|
||||
kwarg.append(str(self.action))
|
||||
self.dbus_service.youker_apt_signal("apt_error", kwarg)
|
||||
|
||||
def start_update(self):
|
||||
# kwarg = {"apt_appname":self.appname,
|
||||
# "apt_percent":str(self.percent),
|
||||
# "action":str(self.action),
|
||||
# }
|
||||
kwarg = []
|
||||
kwarg.append(self.appname)
|
||||
kwarg.append(str(self.percent))
|
||||
kwarg.append(str(self.action))
|
||||
self.dbus_service.youker_apt_signal("apt_start", kwarg)
|
||||
|
||||
def finish_update(self):
|
||||
# kwarg = {"apt_appname":self.appname,
|
||||
# "apt_percent":str(200),
|
||||
# "action":str(self.action),
|
||||
# }
|
||||
kwarg = []
|
||||
kwarg.append(self.appname)
|
||||
kwarg.append(str(200))
|
||||
kwarg.append(str(self.action))
|
||||
self.dbus_service.youker_apt_signal("apt_finish", kwarg)
|
||||
|
||||
def status_change(self, pkg, percent, status):
|
||||
# kwarg = {"apt_appname":str(pkg),
|
||||
# "apt_percent":str(percent),
|
||||
# "action":str(self.action),
|
||||
# "status":str(status),
|
||||
# }
|
||||
kwarg = []
|
||||
kwarg.append(str(pkg))
|
||||
kwarg.append(str(percent))
|
||||
kwarg.append(str(self.action))
|
||||
kwarg.append(str(status))
|
||||
self.dbus_service.youker_apt_signal("apt_pulse", kwarg)
|
||||
|
||||
class AptHandler():
|
||||
|
||||
def __init__(self, dbus_service):
|
||||
self.dbus_service = dbus_service
|
||||
locale.setlocale(locale.LC_ALL, "zh_CN.UTF-8")
|
||||
self.cache = apt.Cache()
|
||||
self.cache.open()
|
||||
|
||||
# get package by pkgName
|
||||
def get_pkg_by_name(self, pkgName):
|
||||
try:
|
||||
return self.cache[pkgName]
|
||||
except KeyError:
|
||||
raise WorkitemError(1, "Package %s is not available" % pkgName)
|
||||
# except Exception, e:
|
||||
# print e
|
||||
# return "ERROR"
|
||||
|
||||
# install deps
|
||||
def install_deps(self, path, kwargs=None):
|
||||
debfile = DebPackage(path)
|
||||
pkgName = debfile._sections["Package"]
|
||||
debfile.check()
|
||||
deps = debfile.missing_deps
|
||||
|
||||
if(len(deps) > 0):
|
||||
self.cache.open()
|
||||
for pkgn in deps:
|
||||
pkg = self.get_pkg_by_name(pkgn)
|
||||
pkg.mark_install()
|
||||
|
||||
try:
|
||||
self.cache.commit(FetchProcess(self.dbus_service, pkgName, AppActions.INSTALLDEPS), AptProcess(self.dbus_service, pkgName, AppActions.INSTALLDEPS))
|
||||
except Exception, e:
|
||||
print e
|
||||
print "install err"
|
||||
|
||||
# install package
|
||||
def install(self, pkgName, kwargs=None):
|
||||
print "real install->", pkgName
|
||||
self.cache.open()
|
||||
pkg = self.get_pkg_by_name(pkgName)
|
||||
print pkg.installed.version#1.2.0-0ubuntu1
|
||||
print len(pkg.versions)#2
|
||||
print pkg.versions[0].version#1.3.1-0ubuntu1
|
||||
print pkg.versions[1].version#1.2.0-0ubuntu1
|
||||
# if pkg.is_installed:
|
||||
# raise WorkitemError(7, "Package %s is installed" % pkgName)
|
||||
pkg.mark_install()
|
||||
|
||||
try:
|
||||
self.cache.commit(FetchProcess(self.dbus_service, pkgName, AppActions.INSTALL), AptProcess(self.dbus_service, pkgName, AppActions.INSTALL))
|
||||
except apt.cache.FetchFailedException as error:
|
||||
raise WorkitemError(2, str(error))
|
||||
except apt.cache.LockFailedException:
|
||||
raise WorkitemError(3, "package manager is running.")
|
||||
except Exception as e:
|
||||
raise WorkitemError(0, "unknown error")
|
||||
# except Exception, e:
|
||||
# print e
|
||||
# print "install err"
|
||||
|
||||
# update packages
|
||||
def upgrade(self, pkgNames, kwargs=None):
|
||||
self.cache.open()
|
||||
|
||||
for pkgName in pkgNames:
|
||||
pkg = self.get_pkg_by_name(pkgName)
|
||||
pkg.mark_upgrade()
|
||||
|
||||
try:
|
||||
self.cache.commit(FetchProcess(self.dbus_service, "#upgrade", AppActions.UPGRADE), AptProcess(self.dbus_service, "#upgrade", AppActions.UPGRADE))
|
||||
except apt.cache.FetchFailedException as error:
|
||||
raise WorkitemError(2, str(error))
|
||||
except apt.cache.LockFailedException:
|
||||
raise WorkitemError(3, "package manager is running.")
|
||||
except Exception as e:
|
||||
raise WorkitemError(0, "unknown error")
|
||||
# except Exception, e:
|
||||
# print e
|
||||
# print "update err"
|
||||
|
||||
def upone(self, pkgName, kwargs=None):
|
||||
self.cache.open()
|
||||
pkg = self.get_pkg_by_name(pkgName)
|
||||
pkg.mark_install()
|
||||
|
||||
try:
|
||||
self.cache.commit(FetchProcess(self.dbus_service, pkgName, AppActions.INSTALL), AptProcess(self.dbus_service, pkgName, AppActions.INSTALL))
|
||||
except apt.cache.FetchFailedException as error:
|
||||
raise WorkitemError(2, str(error))
|
||||
except apt.cache.LockFailedException:
|
||||
raise WorkitemError(3, "package manager is running.")
|
||||
except Exception as e:
|
||||
raise WorkitemError(0, "unknown error")
|
||||
|
||||
# apt-get update
|
||||
def update(self, kwargs=None):
|
||||
quiet = False
|
||||
if kwargs is not None:
|
||||
quiet = int(kwargs["quiet"])
|
||||
|
||||
try:
|
||||
if quiet == True:
|
||||
print "quiet=True"
|
||||
self.cache.update()
|
||||
else:
|
||||
print "quiet=False"
|
||||
self.cache.update(fetch_progress=FetchProcess(self.dbus_service, "#update", AppActions.UPDATE))
|
||||
except Exception, e:
|
||||
print e
|
||||
print "update except"
|
||||
|
||||
|
||||
class WorkitemError(Exception):
|
||||
|
||||
def __init__(self, errornum, details = ""):
|
||||
self.errornum = errornum
|
||||
self.details = details
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ad = AptHandler(None)
|
||||
ad.upgrade(['khelpcenter4'])
|
|
@ -0,0 +1,810 @@
|
|||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
### BEGIN LICENSE
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin 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 <http://www.gnu.org/licenses/>.
|
||||
### END LICENSE
|
||||
|
||||
import sys
|
||||
import os
|
||||
import signal
|
||||
import glob
|
||||
import fcntl
|
||||
import shutil
|
||||
import logging
|
||||
import tempfile
|
||||
import subprocess
|
||||
import re
|
||||
import dbus
|
||||
import dbus.service
|
||||
import dbus.mainloop.glib
|
||||
from gi.repository import GObject
|
||||
#import apt
|
||||
#import aptsources.sourceslist
|
||||
#import apt_pkg
|
||||
import threading
|
||||
import thread
|
||||
from server import PolicyKitService
|
||||
from policykit import UK_ACTION_YOUKER
|
||||
import time
|
||||
import cleaner
|
||||
from detailinfo.cpuinfo import DetailInfo
|
||||
from beautify.sound import Sound
|
||||
from beautify.others import Others
|
||||
#from appcollections.monitorball.monitor_ball import MonitorBall
|
||||
#from softwarecenter.apt_daemon import AptDaemon
|
||||
from beautify.theme import Theme
|
||||
log = logging.getLogger('Daemon')
|
||||
|
||||
|
||||
INTERFACE = 'com.ubuntukylin.youker'
|
||||
UKPATH = '/'
|
||||
|
||||
#------------------------------------apt start----------------------------
|
||||
from apt_handler import AppActions, AptHandler, WorkitemError
|
||||
#class WorkItem:
|
||||
# def __init__(self, pkgname, action, kwargs):
|
||||
# self.pkgname = pkgname
|
||||
# self.action = action
|
||||
# self.kwargs = kwargs
|
||||
|
||||
#class WorkThread(threading.Thread):
|
||||
# def __init__(self, dbusDaemon):
|
||||
# threading.Thread.__init__(self)
|
||||
# self.dbusDaemon = dbusDaemon
|
||||
# print "$$$$$$$$$$$$$$ ", type(self.dbusDaemon)
|
||||
|
||||
# def run(self):
|
||||
# while(True):
|
||||
# if len(self.dbusDaemon.worklist) == 0:
|
||||
# time.sleep(0.2)
|
||||
# continue
|
||||
|
||||
# self.dbusDaemon.mutex.acquire()
|
||||
# item = self.dbusDaemon.worklist.pop(0) #get first item and remove it from list
|
||||
# self.dbusDaemon.mutex.release()
|
||||
|
||||
# try:
|
||||
# func = getattr(self.dbusDaemon.aptHandler, item.action)
|
||||
# if func is None:
|
||||
# print "Error action: ", item
|
||||
|
||||
# res = func(item.pkgname,item.kwargs)
|
||||
# if res is False:
|
||||
# print "Action exec failed..."
|
||||
# except WorkitemError as e:
|
||||
# kwarg = {"apt_appname": item.pkgname,
|
||||
# "apt_percent": str(-e.errornum),
|
||||
# "action": str(item.action),
|
||||
# }
|
||||
# self.dbusDaemon.youker_apt_signal("apt_error", kwarg)
|
||||
|
||||
# time.sleep(0.3)
|
||||
#------------------------------------apt end----------------------------
|
||||
|
||||
class Daemon(PolicyKitService):
|
||||
def __init__ (self, bus, mainloop):
|
||||
self.infoconf = DetailInfo()
|
||||
self.otherconf = Others()
|
||||
self.soundconf = Sound()
|
||||
# self.ballconf = MonitorBall()
|
||||
self.themeconf = Theme()
|
||||
# self.daemonsame = cleaner.SearchTheSame()
|
||||
# self.daemonlarge = cleaner.ManageTheLarge()
|
||||
# self.daemonunneed = cleaner.CleanTheUnneed()
|
||||
# self.daemonclean = cleaner.FunctionOfClean()
|
||||
self.daemononekey = cleaner.OneKeyClean()
|
||||
# self.daemoncache = cleaner.CleanTheCache()
|
||||
# self.daemonApt = AptDaemon()
|
||||
#self.daemonApt = AptDaemon(self)
|
||||
|
||||
#--------------apt start----------------
|
||||
self.aptHandler = AptHandler(self)
|
||||
# self.worklist = []
|
||||
# self.mutex = threading.RLock()
|
||||
# self.worker_thread = WorkThread(self)
|
||||
# self.worker_thread.setDaemon(True)
|
||||
# self.worker_thread.start()
|
||||
#--------------apt end----------------
|
||||
|
||||
bus_name = dbus.service.BusName(INTERFACE, bus=bus)
|
||||
PolicyKitService.__init__(self, bus_name, UKPATH)
|
||||
self.mainloop = mainloop
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='')
|
||||
def exit(self):
|
||||
self.mainloop.quit()
|
||||
|
||||
#--------------apt start----------------
|
||||
# def add_worker_item(self, item):
|
||||
# print "####add_worker_item:", item
|
||||
# self.mutex.acquire()
|
||||
# self.worklist.append(item)
|
||||
# self.mutex.release()
|
||||
|
||||
# package download status signal
|
||||
'''parm mean
|
||||
type:
|
||||
start:start download
|
||||
stop:all work is finish
|
||||
done:all items download finished
|
||||
fail:download failed
|
||||
fetch:one item download finished
|
||||
pulse:download status, this msg given a string like dict
|
||||
msg:
|
||||
a message of type, sometimes is None
|
||||
'''
|
||||
@dbus.service.signal(INTERFACE, signature='sas')
|
||||
def youker_fetch_signal(self, type, msg):
|
||||
pass
|
||||
|
||||
# package install/update/remove signal
|
||||
'''parm mean
|
||||
type:
|
||||
start:start work
|
||||
stop:work finish
|
||||
error:got a error
|
||||
pulse:work status, this msg given a string like dict
|
||||
msg:
|
||||
a message of type, sometimes is None
|
||||
'''
|
||||
@dbus.service.signal(INTERFACE, signature='sas')
|
||||
def youker_apt_signal(self, type, msg):
|
||||
pass
|
||||
|
||||
def start_install_uk(self, pkgName):
|
||||
self.aptHandler.install(pkgName)
|
||||
|
||||
# install package sa:youker_fetch_signal() and youker_apt_signal()
|
||||
#sudo apt-get install youker-assistant=1.3.1-0ubuntu1
|
||||
@dbus.service.method(INTERFACE, in_signature='s', out_signature='b', sender_keyword='sender')
|
||||
def install(self, pkgName, sender=None):
|
||||
print "####install: ",pkgName
|
||||
# item = WorkItem(pkgName, AppActions.INSTALL, None)
|
||||
# self.add_worker_item(item)
|
||||
# self.aptHandler.install(pkgName)
|
||||
thread.start_new_thread(self.start_install_uk, (pkgName,))
|
||||
print "####install return"
|
||||
return True
|
||||
|
||||
def start_update_source_list(self):
|
||||
self.aptHandler.update()
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='b', sender_keyword='sender')
|
||||
def update(self, sender=None):
|
||||
thread.start_new_thread(self.start_update_source_list, ())
|
||||
# self.aptHandler.update()
|
||||
return True
|
||||
|
||||
# @dbus.service.method(INTERFACE, in_signature='as', out_signature='b', sender_keyword='sender')
|
||||
# def upgrade(self, pkgNames, sender=None):
|
||||
# print "####upgrade: ", pkgNames
|
||||
# item = WorkItem(pkgNames, AppActions.UPGRADE, None)
|
||||
# self.add_worker_item(item)
|
||||
# # self.aptHandler.upgrade_pkg(pkgName)
|
||||
# print "####upgrade return"
|
||||
# return True
|
||||
#--------------apt end----------------
|
||||
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='s', out_signature='')
|
||||
def set_homedir(self, homedir):
|
||||
self.soundconf.set_homedir(homedir)
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='s', out_signature='')
|
||||
def adjust_cpufreq_scaling_governer(self, value):
|
||||
cpufreq_file = "/etc/init.d/cpufrequtils"
|
||||
oldvalue = ''
|
||||
if os.path.exists(cpufreq_file):
|
||||
fp = open(cpufreq_file, "rw+")
|
||||
line = fp.readline()
|
||||
while line:
|
||||
if line.startswith("GOVERNOR="):
|
||||
if value not in line:
|
||||
oldvalue = line.split("=")[1].replace('"', '').replace('\n', '')
|
||||
break
|
||||
line = fp.readline()
|
||||
fp.close()
|
||||
if oldvalue not in ['', None] and value not in ['', None]:
|
||||
cmd = "sed -i 's/%s/%s/g' %s" % (oldvalue, value, cpufreq_file)
|
||||
os.system(cmd)
|
||||
os.system('service cpufrequtils restart')
|
||||
else:
|
||||
fpath = os.path.expanduser("/sys/devices/system/cpu/")
|
||||
for line in os.listdir(fpath):
|
||||
line = line.strip('\n')
|
||||
#pattern = re.compile(r'cpu.*[0-9]$')
|
||||
pattern = re.compile(r'cpu.*\d\Z')
|
||||
m = pattern.match(line)
|
||||
if m:
|
||||
filepath = "/sys/devices/system/cpu/%s/cpufreq/scaling_governor" % line
|
||||
if os.path.exists(filepath):
|
||||
cmd = 'echo %s > %s' % (value, filepath)
|
||||
os.system(cmd)
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='as')
|
||||
def get_cpufreq_scaling_governer_list(self):
|
||||
cmd = "cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors"
|
||||
fp = os.popen(cmd)
|
||||
msg = fp.read().strip('\n')
|
||||
fp.close()
|
||||
cpulist = []
|
||||
if msg not in ['', None]:
|
||||
cpulist = msg.split(' ')
|
||||
return cpulist
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='s')
|
||||
def get_current_cpufreq_scaling_governer(self):
|
||||
cmd = "cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"
|
||||
fp = os.popen(cmd)
|
||||
msg = fp.read().strip('\n')
|
||||
fp.close()
|
||||
return msg
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='s', out_signature='b')
|
||||
def copy_file(self, filename):
|
||||
des_path = '/var/lib/youker-assistant-daemon/custom'
|
||||
filename = filename.encode('utf-8')
|
||||
if not os.path.exists(des_path):
|
||||
os.makedirs(des_path)
|
||||
try:
|
||||
shutil.copy(filename, des_path)
|
||||
return True
|
||||
except os.error:
|
||||
pass
|
||||
return False
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='s', out_signature='b')
|
||||
def delete_file(self, filename):
|
||||
filename = filename.encode('utf-8')
|
||||
# output = open("/tmp/default.txt", 'w+')
|
||||
# output.write(filename)
|
||||
# output.close()
|
||||
# fp = open("/tmp/default.txt", "w")
|
||||
# print >> fp, "--------------"
|
||||
# print >> fp, filename
|
||||
# print >> fp, "------22222222--------"
|
||||
# fp.close()
|
||||
# if os.path.exists(filename):
|
||||
if os.path.isfile(filename):
|
||||
try:
|
||||
os.remove(filename)
|
||||
return True
|
||||
except os.error:
|
||||
pass
|
||||
return False
|
||||
|
||||
# set cursor theme
|
||||
@dbus.service.method(INTERFACE, in_signature='s', out_signature='b')
|
||||
def set_cursor_theme_with_root(self, theme):
|
||||
return self.themeconf.set_cursor_theme_with_root(theme)
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='s', out_signature='b', sender_keyword='sender')
|
||||
def kill_root_process(self, pid, sender=None):
|
||||
status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
if not status:
|
||||
return False
|
||||
cmd = 'kill -9 %s' % pid
|
||||
subprocess.Popen(cmd, shell=True, close_fds=True)#加上close_fds=True,避免子进程一直存在
|
||||
return True
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='b')
|
||||
def kill_uk_process(self):
|
||||
cmd = 'killall youker-assistant'
|
||||
subprocess.Popen(cmd, shell=True, close_fds=True)#加上close_fds=True,避免子进程一直存在
|
||||
return True
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='s', out_signature='')
|
||||
def set_user_homedir(self, homedir):
|
||||
cleaner.get_user_homedir(homedir)
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='s')
|
||||
def get_system_daemon(self):
|
||||
return "SystemDaemon"
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='a{sv}')
|
||||
def get_computer_info(self):
|
||||
return self.infoconf.get_computer()
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='s')
|
||||
def get_os_name(self):
|
||||
return self.infoconf.get_os_name()
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='a{sv}')
|
||||
def get_cpu_info(self):
|
||||
return self.infoconf.get_cpu()
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='a{sv}')
|
||||
def get_board_info(self):
|
||||
return self.infoconf.get_board()
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='a{sv}')
|
||||
def get_memory_info(self):
|
||||
return self.infoconf.get_memory()
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='a{sv}')
|
||||
def get_harddisk_info(self):
|
||||
return self.infoconf.get_disk()
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='a{sv}')
|
||||
def get_networkcard_info(self):
|
||||
return self.infoconf.get_network()
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='a{sv}')
|
||||
def get_monitor_info(self):
|
||||
return self.infoconf.get_monitor()
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='a{sv}')
|
||||
def get_cdrom_info(self):
|
||||
return self.infoconf.get_dvd()
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='a{sv}')
|
||||
def get_audiocard_info(self):
|
||||
return self.infoconf.get_multimedia()
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='s')
|
||||
def get_time_value(self):
|
||||
return self.infoconf.uptimeinfo()
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='a{sv}')
|
||||
def get_sensor_info(self):
|
||||
return self.infoconf.get_sensors()
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='b')
|
||||
def judge_sensors_exists_hb(self):
|
||||
return self.infoconf.judge_sensors_exists()
|
||||
|
||||
|
||||
# -------------------------sound-------------------------
|
||||
# get sound themes
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='as')
|
||||
def get_sound_themes(self):
|
||||
return self.soundconf.get_sound_themes()
|
||||
|
||||
# get sound files in current sound theme
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='as')
|
||||
def get_sounds(self):
|
||||
return self.soundconf.get_sounds()
|
||||
|
||||
# replace a sound file
|
||||
@dbus.service.method(INTERFACE, in_signature='ss', out_signature='')
|
||||
def replace_sound_file(self, newSoundFile, targetSoundFile):
|
||||
self.soundconf.replace_sound_file(newSoundFile, targetSoundFile)
|
||||
|
||||
# restore a sound file
|
||||
@dbus.service.method(INTERFACE, in_signature='s', out_signature='')
|
||||
def restore_sound_file(self, targetSoundFile):
|
||||
self.soundconf.restore_sound_file(targetSoundFile)
|
||||
|
||||
# restore all sound file in current sound theme
|
||||
@dbus.service.method(INTERFACE, in_signature='s', out_signature='')
|
||||
def restore_all_sound_file(self, soundTheme):
|
||||
self.soundconf.restore_all_sound_file(soundTheme)
|
||||
|
||||
# -------------------------others-------------------------
|
||||
|
||||
# custom plymouth bg by plymouthName
|
||||
@dbus.service.method(INTERFACE, in_signature='s', out_signature='')
|
||||
def custom_plymouth_bg(self, plymouthName):
|
||||
self.otherconf.custom_plymouth_bg(plymouthName)
|
||||
|
||||
# add new custom plymouth
|
||||
@dbus.service.method(INTERFACE, in_signature='ss', out_signature='')
|
||||
def add_new_plymouth(self, customBG, plymouthName):
|
||||
self.otherconf.add_new_plymouth(customBG, plymouthName)
|
||||
|
||||
# get existing plymouth list
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='as')
|
||||
def get_existing_plymouth_list(self):
|
||||
return self.otherconf.get_existing_plymouth_list()
|
||||
|
||||
# check and save current plymouth when init
|
||||
@dbus.service.method(INTERFACE, in_signature='', out_signature='')
|
||||
def plymouth_init_check(self):
|
||||
self.otherconf.plymouth_init_check()
|
||||
|
||||
# get image path
|
||||
@dbus.service.method(INTERFACE, in_signature='s', out_signature='s')
|
||||
def get_image_path(self,name):
|
||||
return self.otherconf.get_image_path(name)
|
||||
|
||||
# Delete the boot animation from the list
|
||||
@dbus.service.method(INTERFACE, in_signature='s', out_signature='s')
|
||||
def delete_plymouth(self,plymouthName):
|
||||
return self.otherconf.delete_plymouth(plymouthName)
|
||||
|
||||
# -------------------------monitorball-------------------------
|
||||
# clean up memory
|
||||
# @dbus.service.method(INTERFACE, in_signature='', out_signature='')
|
||||
# def cleanup_memory(self):
|
||||
# self.ballconf.cleanup_memory()
|
||||
# -------------------------monitorball end-------------------------
|
||||
|
||||
@dbus.service.signal(INTERFACE, signature='s')
|
||||
def clean_complete_onekey(self, msg):
|
||||
pass
|
||||
|
||||
@dbus.service.signal(INTERFACE, signature='s')
|
||||
def clean_error_onekey(self, msg):
|
||||
pass
|
||||
|
||||
@dbus.service.signal(INTERFACE, signature='ss')
|
||||
def status_for_quick_clean(self, flag, status):
|
||||
pass
|
||||
|
||||
# a dbus method which means clean complete
|
||||
@dbus.service.signal(INTERFACE, signature='s')
|
||||
def clean_complete(self, msg):
|
||||
pass
|
||||
|
||||
# a dbus method which means quit clean by clicking the policykit's quit button
|
||||
@dbus.service.signal(INTERFACE, signature='b')
|
||||
def quit_clean(self, status):
|
||||
pass
|
||||
|
||||
# a dbus method which means clean single complete
|
||||
@dbus.service.signal(INTERFACE, signature='s')
|
||||
def clean_single_complete(self, msg):
|
||||
pass
|
||||
|
||||
# a dbus method which means an error occurred
|
||||
@dbus.service.signal(INTERFACE, signature='s')
|
||||
def clean_error(self, msg):
|
||||
pass
|
||||
|
||||
# a dbus method which means an single error occurred
|
||||
@dbus.service.signal(INTERFACE, signature='s')
|
||||
def clean_single_error(self, msg):
|
||||
pass
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='as', out_signature='', sender_keyword='sender')
|
||||
def onekey_clean_crufts_function(self, mode_list, sender=None):
|
||||
status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
if not status:
|
||||
self.revoke_clean_onekey('yes')
|
||||
return
|
||||
else:
|
||||
self.revoke_clean_onekey('no')
|
||||
daemononekey = cleaner.OneKeyClean()
|
||||
try:
|
||||
t = threading.Thread(target = daemononekey.clean_all_onekey_crufts, args = (self, mode_list))
|
||||
t.start()
|
||||
#daemononekey.clean_all_onekey_crufts(self, mode_list)
|
||||
except Exception, e:
|
||||
self.clean_error_msg('onekey')
|
||||
else:
|
||||
self.clean_complete_msg('onekey')
|
||||
|
||||
# @dbus.service.method(INTERFACE, in_signature='as', out_signature='', sender_keyword='sender')
|
||||
# def onekey_clean_crufts_function_by_threading(self, mode_list, sender=None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.revoke_clean_onekey('yes')
|
||||
# return
|
||||
# else:
|
||||
# self.revoke_clean_onekey('no')
|
||||
# daemononekey = cleaner.OneKeyClean()
|
||||
# try:
|
||||
# t = threading.Thread(target = daemononekey.clean_all_onekey_crufts, args = (self, mode_list))
|
||||
# #daemononekey.clean_all_onekey_crufts(self, mode_list)
|
||||
# except Exception, e:
|
||||
# self.clean_error_msg('onekey')
|
||||
# else:
|
||||
# self.clean_complete_msg('onekey')
|
||||
|
||||
# return t
|
||||
|
||||
def onekey_clean_cancel_function(self, t):
|
||||
daemononekey.cancel_onekey_clean(t, SystemExit)
|
||||
|
||||
# @dbus.service.method(INTERFACE, in_signature='s', out_signature='', sender_keyword='sender')
|
||||
# def history_clean_records_function(self, flag, sender=None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.clean_complete_msg('')
|
||||
# return
|
||||
# daemonhistory = cleaner.CleanTheHistory()
|
||||
# try:
|
||||
# running = daemonhistory.clean_all_history_crufts(flag)
|
||||
# except Exception, e:
|
||||
# self.clean_error_msg(flag)
|
||||
# else:
|
||||
# self.clean_complete_msg(flag)
|
||||
|
||||
# @dbus.service.method(INTERFACE, in_signature='', out_signature='', sender_keyword='sender')
|
||||
# def clean_system_history(self, sender=None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.clean_complete_msg('')
|
||||
# return
|
||||
# daemonsystem = cleaner.CleanSystemHistory()
|
||||
# try:
|
||||
# daemonsystem.clean_the_cruftlist()
|
||||
# except Exception, e:
|
||||
# self.clean_error_msg('system')
|
||||
# else:
|
||||
# self.clean_complete_msg('system')
|
||||
|
||||
#@dbus.service.method(INTERFACE, in_signature='', out_signature='', sender_keyword='sender')
|
||||
#def clean_dash_history(self, sender=None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.clean_complete_msg('')
|
||||
# return
|
||||
# daemondash = cleaner.CleanDashHistory()
|
||||
# try:
|
||||
# daemondash.clean_the_cruftlist()
|
||||
# except Exception, e:
|
||||
# self.clean_error_msg('dash')
|
||||
# else:
|
||||
# self.clean_complete_msg('dash')
|
||||
|
||||
# @dbus.service.method(INTERFACE, in_signature = 'as', out_signature = '', sender_keyword = 'sender')
|
||||
# def cookies_clean_record_function(self, flag, sender=None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.clean_single_complete_msg('')
|
||||
# return
|
||||
# daemoncookies = cleaner.CleanTheCookies(None)
|
||||
# try:
|
||||
# daemoncookies.clean_one_cookies_cruft(flag[0], flag[1])
|
||||
# except Exception, e:
|
||||
# self.clean_single_error_msg('cookies')
|
||||
# else:
|
||||
# self.clean_single_complete_msg('cookies')
|
||||
|
||||
# @dbus.service.method(INTERFACE, in_signature = 's', out_signature = '', sender_keyword = 'sender')
|
||||
# def cookies_clean_records_function(self, flag, sender = None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.quit_clean_work(flag)
|
||||
# return
|
||||
# daemoncookies = cleaner.CleanTheCookies(None)
|
||||
# try:
|
||||
# daemoncookies.clean_all_cookies_crufts(flag)
|
||||
# except Exception, e:
|
||||
# self.clean_error_msg(flag)
|
||||
# else:
|
||||
# self.clean_complete_msg(flag)
|
||||
|
||||
# the function of clean files
|
||||
### input-['filepath', 'file...] output-''
|
||||
# @dbus.service.method(INTERFACE, in_signature='ass', out_signature='', sender_keyword='sender')
|
||||
# def clean_file_cruft(self, cruft_list, flagstr, sender=None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.clean_complete_msg('')
|
||||
# return
|
||||
# try:
|
||||
# for cruft in cruft_list:
|
||||
# self.daemonclean.clean_the_file(cruft)
|
||||
# except Exception, e:
|
||||
# self.clean_error_msg(flagstr)
|
||||
# else:
|
||||
# self.clean_complete_msg(flagstr)
|
||||
|
||||
#def dbusstring_to_string(self, string):
|
||||
# tmp_string = str(string)
|
||||
# patt = "u'[\S]+'"
|
||||
# tmp_list = re.findall(patt, tmp_string)
|
||||
# return [ok.split("'")[1] for ok in tmp_list]
|
||||
|
||||
def clean_complete_msg(self, para):
|
||||
self.clean_complete(para)
|
||||
|
||||
# def quit_clean_work(self, para):
|
||||
# self.quit_clean(para)
|
||||
# def quit_clean_work(self, status):
|
||||
# self.quit_clean(status)
|
||||
|
||||
def clean_single_complete_msg(self, para):
|
||||
self.clean_single_complete(para)
|
||||
|
||||
def clean_error_msg(self, para):
|
||||
self.clean_error(para)
|
||||
|
||||
def clean_single_error_msg(self, para):
|
||||
self.clean_single_error(para)
|
||||
|
||||
def revoke_clean_onekey(self, para):
|
||||
self.clean_complete_onekey(para)
|
||||
|
||||
# a dbus method which means clean complete
|
||||
# @dbus.service.signal(INTERFACE, signature='s')
|
||||
# def finish_clean(self, msg):
|
||||
# pass
|
||||
|
||||
@dbus.service.signal(INTERFACE, signature='ss')
|
||||
def status_remove_packages(self, type, msg):
|
||||
pass
|
||||
|
||||
# a dbus method which means an error occurred
|
||||
# @dbus.service.signal(INTERFACE, signature='s')
|
||||
# def sudo_clean_error(self, msg):
|
||||
# pass
|
||||
|
||||
# the function of clean packages
|
||||
### input-['packagename', 'pack...] output-''
|
||||
# @dbus.service.method(INTERFACE, in_signature='ass', out_signature='', sender_keyword='sender')
|
||||
# def clean_package_cruft(self, cruftlist, flag, sender=None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.finish_clean_msg('')
|
||||
# return
|
||||
# try:
|
||||
# self.daemonclean.clean_the_package(cruftlist, self)
|
||||
# except Exception, e:
|
||||
# self.sudo_clean_error_msg(flag)
|
||||
# else:
|
||||
# self.finish_clean_msg(flag)
|
||||
|
||||
# def finish_clean_msg(self, para):
|
||||
# self.finish_clean(para)
|
||||
|
||||
# def sudo_clean_error_msg(self, para):
|
||||
# self.sudo_clean_error(para)
|
||||
|
||||
#-----START-----------NEW-YOUKER---------------------------
|
||||
#
|
||||
|
||||
# @dbus.service.method(INTERFACE, in_signature='a{sv}', out_signature='', sender_keyword='sender')
|
||||
# def remove_select_items(self, mode_dic, sender=None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.quit_clean(False)
|
||||
## self.quit_clean_work()
|
||||
# return
|
||||
# else:
|
||||
# self.quit_clean(True)
|
||||
def start_clean_all(self, mode_dic):
|
||||
filecache = mode_dic.get('file', [])
|
||||
if filecache:
|
||||
for tmpName in filecache:
|
||||
cleaner.interface_remove_file_system(self, tmpName)
|
||||
|
||||
packagecache = mode_dic.get('package', [])
|
||||
if packagecache:
|
||||
for pkgName in packagecache:
|
||||
cleaner.interface_remove_package_system(self, pkgName)
|
||||
|
||||
bashhistory = mode_dic.get('bash-history', [])
|
||||
if bashhistory:
|
||||
for tmpName in bashhistory:
|
||||
cleaner.interface_remove_file_system(self, tmpName)
|
||||
|
||||
x11history = mode_dic.get('x11-history', [])
|
||||
if x11history:
|
||||
for tmpName in x11history:
|
||||
cleaner.interface_remove_file_system(self, tmpName)
|
||||
|
||||
firefoxhistory = mode_dic.get('firefox-history', [])
|
||||
if firefoxhistory:
|
||||
cleaner.interface_remove_firefox_history_system(self)
|
||||
|
||||
chromiumhistory = mode_dic.get('chromium-history', [])
|
||||
if chromiumhistory:
|
||||
cleaner.interface_remove_chromium_history_system(self)
|
||||
|
||||
systemhistory = mode_dic.get('system-history', [])
|
||||
if systemhistory:
|
||||
cleaner.interface_remove_system_history_system(self)
|
||||
|
||||
firefoxcookies = mode_dic.get('firefox-cookie', [])
|
||||
if firefoxcookies:
|
||||
for domain in firefoxcookies:
|
||||
cleaner.interface_remove_firefox_cookies_system(self, domain)
|
||||
|
||||
chromiumcookies = mode_dic.get('chromium-cookie', [])
|
||||
if chromiumcookies:
|
||||
for domain in chromiumcookies:
|
||||
cleaner.interface_remove_chromium_cookies_system(self, domain)
|
||||
|
||||
self.subpage_status_signal('Complete:All', "finish")
|
||||
|
||||
@dbus.service.method(INTERFACE, in_signature='a{sv}', out_signature='', sender_keyword='sender')
|
||||
def remove_select_items(self, mode_dic, sender=None):
|
||||
status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
if not status:
|
||||
self.quit_clean(False)
|
||||
return
|
||||
else:
|
||||
self.quit_clean(True)
|
||||
thread.start_new_thread(self.start_clean_all, (mode_dic,))
|
||||
# @dbus.service.method(INTERFACE, in_signature='s', out_signature='', sender_keyword='sender')
|
||||
# def remove_file(self, fp):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.revoke_clean_onekey('yes')
|
||||
# return
|
||||
# else:
|
||||
# self.revoke_clean_onekey('no')
|
||||
# cleaner.interface_remove_file_system(self, fp)
|
||||
|
||||
# @dbus.service.method(INTERFACE, in_signature='s', out_signature='', sender_keyword='sender')
|
||||
# def remove_package(self, pkgname, sender=None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.revoke_clean_onekey('yes')
|
||||
# return
|
||||
# else:
|
||||
# self.revoke_clean_onekey('no')
|
||||
# cleaner.interface_remove_package_system(self, pkgname)
|
||||
|
||||
# @dbus.service.method(INTERFACE, in_signature='', out_signature='', sender_keyword='sender')
|
||||
# def remove_firefox_history(self, sender=None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.revoke_clean_onekey('yes')
|
||||
# return
|
||||
# else:
|
||||
# self.revoke_clean_onekey('no')
|
||||
# cleaner.interface_remove_firefox_history_system(self)
|
||||
|
||||
# @dbus.service.method(INTERFACE, in_signature='', out_signature='', sender_keyword='sender')
|
||||
# def remove_chromium_history(self, sender=None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.revoke_clean_onekey('yes')
|
||||
# return
|
||||
# else:
|
||||
# self.revoke_clean_onekey('no')
|
||||
# cleaner.interface_remove_chromium_history_system(self)
|
||||
|
||||
# @dbus.service.method(INTERFACE, in_signature='s', out_signature='', sender_keyword='sender')
|
||||
# def remove_firefox_cookies(self, domain, sender=None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.revoke_clean_onekey('yes')
|
||||
# return
|
||||
# else:
|
||||
# self.revoke_clean_onekey('no')
|
||||
# cleaner.interface_remove_firefox_cookies_system(self, domain)
|
||||
|
||||
# @dbus.service.method(INTERFACE, in_signature='s', out_signature='', sender_keyword='sender')
|
||||
# def remove_chromium_cookies(self, domain, sender=None):
|
||||
# status = self._check_permission(sender, UK_ACTION_YOUKER)
|
||||
# if not status:
|
||||
# self.revoke_clean_onekey('yes')
|
||||
# return
|
||||
# else:
|
||||
# self.revoke_clean_onekey('no')
|
||||
# cleaner.interface_remove_chromium_cookies_system(self, domain)
|
||||
|
||||
@dbus.service.signal(INTERFACE, signature='as')
|
||||
def subpage_data_signal(self, msg):
|
||||
pass
|
||||
|
||||
@dbus.service.signal(INTERFACE, signature='ss')
|
||||
def subpage_status_signal(self, msg, domain):
|
||||
pass
|
||||
|
||||
@dbus.service.signal(INTERFACE, signature='s')
|
||||
def subpage_error_signal(self, msg):
|
||||
pass
|
||||
#-----END------------NEW-YOUKER---------------------------
|
||||
|
||||
if __name__ == '__main__':
|
||||
os.environ["TERM"] = "xterm"
|
||||
os.environ["PATH"] = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin"
|
||||
os.environ["DEBIAN_FRONTEND"] = "noninteractive"
|
||||
if os.path.exists("/var/lib/apt/lists/lock"):
|
||||
os.remove("/var/lib/apt/lists/lock")
|
||||
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
|
||||
#gobject.threads_init()
|
||||
#mainloop = gobject.MainLoop()
|
||||
GObject.threads_init()
|
||||
mainloop = GObject.MainLoop()
|
||||
signal.signal(signal.SIGINT, lambda : mainloop.quit())
|
||||
Daemon(dbus.SystemBus(), mainloop)
|
||||
mainloop.run()
|
|
@ -0,0 +1,26 @@
|
|||
# This class is modified from gnome-lirc-properties project
|
||||
# the original file is gnome_lirc_properties/backend.py
|
||||
# GPL v2+
|
||||
# Copyright (C) 2008 Fluendo Embedded S.L.
|
||||
# Copyright (C) 2010 TualatriX <tualatrix@gmail.com>
|
||||
# Copyright (C) 2013 ~ 2014 National University of Defense Technology(NUDT) & Kylin Ltd
|
||||
|
||||
import dbus.service
|
||||
|
||||
class AccessDeniedException(dbus.DBusException):
|
||||
'''This exception is raised when some operation is not permitted.'''
|
||||
|
||||
_dbus_error_name = 'com.ubuntukylin.youker.AccessDeniedException'
|
||||
|
||||
|
||||
class PolicyKitService(dbus.service.Object):
|
||||
'''A D-BUS service that uses PolicyKit for authorization.'''
|
||||
|
||||
def _check_permission(self, sender, action):
|
||||
if not sender: raise ValueError('sender == None')
|
||||
kit = dbus.SystemBus().get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority')
|
||||
kit = dbus.Interface(kit, 'org.freedesktop.PolicyKit1.Authority')
|
||||
(granted, _, details) = kit.CheckAuthorization(
|
||||
('system-bus-name', {'name': sender}),
|
||||
action, {}, dbus.UInt32(1), '', timeout=600)
|
||||
return granted
|
|
@ -0,0 +1,85 @@
|
|||
/*
|
||||
* Copyright (C) 2013 ~ 2015 National University of Defense Technology(NUDT) & Kylin Ltd.
|
||||
*
|
||||
* Authors:
|
||||
* Kobe Lee xiangli@ubuntukylin.com/kobe24_lixiang@126.com
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "cacheactionwidget.h"
|
||||
#include "mainwindow.h"
|
||||
#include <QLabel>
|
||||
|
||||
CacheActionWidget::CacheActionWidget(QWidget *parent)
|
||||
: QWidget(parent)
|
||||
{
|
||||
this->setFixedSize(900, 150);
|
||||
this->setAutoFillBackground(true);
|
||||
this->setObjectName("transparentWidget");
|
||||
|
||||
img_label = new QLabel();
|
||||
title_label = new QLabel();
|
||||
description_label = new QLabel();
|
||||
|
||||
img_label->setScaledContents(true);//自动缩放,显示图像大小自动调整为Qlabel大小
|
||||
QPixmap label_pixmap("://res/cache.png");
|
||||
img_label->setPixmap(label_pixmap);
|
||||
img_label->setFixedSize(label_pixmap.size());
|
||||
|
||||
title_label->setObjectName("whiteLabel");
|
||||
description_label->setWordWrap(true);//QLabel自动换行
|
||||
description_label->setObjectName("tipLabel");
|
||||
|
||||
QVBoxLayout *layout1 = new QVBoxLayout();
|
||||
layout1->addStretch();
|
||||
layout1->addWidget(title_label);
|
||||
layout1->addWidget(description_label);
|
||||
layout1->addStretch();
|
||||
layout1->setSpacing(15);
|
||||
layout1->setMargin(0);
|
||||
layout1->setContentsMargins(0, 0, 0, 0);
|
||||
|
||||
QHBoxLayout *layout2 = new QHBoxLayout();
|
||||
layout2->addWidget(img_label, 0, Qt::AlignVCenter);
|
||||
layout2->addLayout(layout1);
|
||||
layout2->setSpacing(20);
|
||||
layout2->setMargin(0);
|
||||
layout2->setContentsMargins(20, 20, 0, 0);
|
||||
|
||||
setLayout(layout2);
|
||||
|
||||
this->setLanguage();
|
||||
}
|
||||
|
||||
CacheActionWidget::~CacheActionWidget()
|
||||
{
|
||||
if(img_label != NULL) {
|
||||
delete img_label;
|
||||
img_label = NULL;
|
||||
}
|
||||
if(title_label != NULL) {
|
||||
delete title_label;
|
||||
title_label = NULL;
|
||||
}
|
||||
if(description_label != NULL) {
|
||||
delete description_label;
|
||||
description_label = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
void CacheActionWidget::setLanguage()
|
||||
{
|
||||
title_label->setText(tr("Cleaning up the system cache"));
|
||||
description_label->setText(tr("Deep cleaning up the system cache, to save disk space"));
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
/*
|
||||
* Copyright (C) 2013 ~ 2015 National University of Defense Technology(NUDT) & Kylin Ltd.
|
||||
*
|
||||
* Authors:
|
||||
* Kobe Lee xiangli@ubuntukylin.com/kobe24_lixiang@126.com
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef CACHEACTIONWIDGET_H
|
||||
#define CACHEACTIONWIDGET_H
|
||||
|
||||
#include <QWidget>
|
||||
class MainWindow;
|
||||
class QLabel;
|
||||
|
||||
class CacheActionWidget : public QWidget
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit CacheActionWidget(QWidget *parent = 0);
|
||||
~CacheActionWidget();
|
||||
void setParentWindow(MainWindow* window) { p_mainwindow = window;}
|
||||
void setLanguage();
|
||||
|
||||
private:
|
||||
QLabel *img_label;
|
||||
QLabel *title_label;
|
||||
QLabel *description_label;
|
||||
MainWindow *p_mainwindow;
|
||||
};
|
||||
|
||||
#endif // CACHEACTIONWIDGET_H
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,133 @@
|
|||
/*
|
||||
* Copyright (C) 2013 ~ 2015 National University of Defense Technology(NUDT) & Kylin Ltd.
|
||||
*
|
||||
* Authors:
|
||||
* Kobe Lee xiangli@ubuntukylin.com/kobe24_lixiang@126.com
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef CLEANERDETAILWIDGET_H
|
||||
#define CLEANERDETAILWIDGET_H
|
||||
|
||||
#include <QWidget>
|
||||
#include "cleaneritems.h"
|
||||
#include "cleanlistwidget.h"
|
||||
|
||||
class QLabel;
|
||||
class QBoxLayout;
|
||||
class QHBoxLayout;
|
||||
class QGridLayout;
|
||||
class SessionDispatcher;
|
||||
class SystemDispatcher;
|
||||
class Toolkits;
|
||||
class MainWindow;
|
||||
class CleanSubGroup;
|
||||
|
||||
|
||||
namespace Ui {
|
||||
class CleanerDetailWidget;
|
||||
}
|
||||
|
||||
class CleanerDetailWidget : public QWidget
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit CleanerDetailWidget(QWidget *parent = 0, SessionDispatcher *seroxy = 0, SystemDispatcher *syproxy = 0, MainWindow *window = 0, Toolkits *kits = 0, QString skin = ":/background/res/skin/1.png");
|
||||
~CleanerDetailWidget();
|
||||
void setUIData();
|
||||
void setLanguage();
|
||||
void initConnect();
|
||||
void getAllSelectedItems();
|
||||
void resetCurrentSkin(QString skin);
|
||||
|
||||
public slots:
|
||||
void showCustomPage();
|
||||
void showReciveData(const QStringList &data);
|
||||
void receiveCleanSignal();
|
||||
void showReciveStatus(const QString &status);
|
||||
void CleanUIAndData();
|
||||
// void receivePolicyKitSignal(bool status);
|
||||
|
||||
signals:
|
||||
void notifyMainCheckBox(int status);
|
||||
// void showActionAnimaiton();
|
||||
void sendScanOverStatus(bool status);
|
||||
|
||||
private:
|
||||
void initTitleBar();
|
||||
|
||||
private:
|
||||
Ui::CleanerDetailWidget *ui;
|
||||
MainWindow *parentWindow;
|
||||
SessionDispatcher *sessionproxy;
|
||||
SystemDispatcher *systemproxy;
|
||||
Toolkits *toolKits;
|
||||
QMap<QString, QVariant> argsData;
|
||||
CleanListWidget *cache_apt_items ;
|
||||
CleanSubGroup *cache_apt_btn;
|
||||
CleanListWidget *cache_software_items ;
|
||||
CleanSubGroup *cache_software_btn;
|
||||
CleanListWidget *cache_thumbnails_items ;
|
||||
CleanSubGroup *cache_thumbnails_btn;
|
||||
CleanListWidget *cache_firefox_items ;
|
||||
CleanSubGroup *cache_firefox_btn;
|
||||
CleanListWidget *cache_chromium_items ;
|
||||
CleanSubGroup *cache_chromium_btn;
|
||||
|
||||
CleanListWidget *package_unneed_items ;
|
||||
CleanSubGroup *package_unneed_btn;
|
||||
CleanListWidget *package_oldkernel_items ;
|
||||
CleanSubGroup *package_oldkernel_btn;
|
||||
CleanListWidget *package_configfile_items ;
|
||||
CleanSubGroup *package_configfile_btn;
|
||||
|
||||
CleanListWidget *cookies_firefox_items ;
|
||||
CleanSubGroup *cookies_firefox_btn;
|
||||
CleanListWidget *cookies_chromium_items ;
|
||||
CleanSubGroup *cookies_chromium_btn;
|
||||
|
||||
CleanSubGroup *trace_firefox_btn;
|
||||
CleanSubGroup *trace_chromium_btn;
|
||||
CleanSubGroup *trace_system_btn;
|
||||
CleanSubGroup *trace_bash_btn;
|
||||
CleanListWidget *trace_x11_items ;
|
||||
CleanSubGroup *trace_x11_btn;
|
||||
|
||||
QStringList cache_apt_list;
|
||||
QStringList cache_software_list;
|
||||
QStringList cache_thumbnails_list;
|
||||
QStringList cache_firefox_list;
|
||||
QStringList cache_chromium_list;
|
||||
QStringList package_unneed_list;
|
||||
QStringList package_oldkernel_list;
|
||||
QStringList package_configfile_list;
|
||||
QStringList cookies_firefox_list;
|
||||
QStringList cookies_chromium_list;
|
||||
QString trace_firefox_count;
|
||||
QString trace_chromium_count;
|
||||
QString trace_system_count;
|
||||
QString trace_bash_size;
|
||||
QString trace_bash_path;
|
||||
QStringList trace_x11_list;
|
||||
|
||||
QGridLayout *grid_layout;
|
||||
// int rowIndex;
|
||||
// int columnIndex;
|
||||
int subCount;
|
||||
bool scanResult;
|
||||
QString cur_skin;
|
||||
};
|
||||
|
||||
#endif // CLEANERDETAILWIDGET_H
|