commit 0fd8394397a511a65e792b812b0134ef2adca60b Author: Xie Wei Date: Fri May 6 18:29:20 2022 +0800 Import Upstream version 1.0.3 diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..1b12365 --- /dev/null +++ b/AUTHORS @@ -0,0 +1 @@ +liuhao diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/ChangeLog b/ChangeLog new file mode 100644 index 0000000..e69de29 diff --git a/Makefile.am b/Makefile.am new file mode 100644 index 0000000..36a1a63 --- /dev/null +++ b/Makefile.am @@ -0,0 +1,2 @@ +SUBDIRS = src data po +EXTRA_DIST = autogen.sh diff --git a/NEWS b/NEWS new file mode 100644 index 0000000..e69de29 diff --git a/README b/README new file mode 100644 index 0000000..52573ed --- /dev/null +++ b/README @@ -0,0 +1,142 @@ +# ukui interface + +## API结构 +初步计划API结构如下所示: +``` +ukui interface结构 +├── 操作系统(OS) +│   ├── 操作系统信息 +│   │   ├── 版本:大版本号、小版本号、补丁集编号、build日期 +│   │   ├── 授权:授权用户、授权时间 +│   │   └── 桌面环境:UKUI、DDE、GNOME之类 +│   ├── 文件浏览历史记录 +│   │   ├── 是否记录文件打开历史 +│   │   └── 开始菜单是否记录常用软件 +│   ├── 备份还原 +│   ├── 磁盘、分区管理 +│   │   └── 分区管理器 +│   └── 其他系统管理工具 +│      ├── 系统服务:获取服务列表,禁用、启用服务,运行、停止、重启服务等 +│      └── 打开其他各种图形化系统管理工具 +├── 用户账户(Accounts) +│   ├── 用户(User) +│   │   └── 添加、修改、删除用户,包括以下信息 +│   │      ├── 用户名 +│   │      ├── 密码 +│   │      ├── 用户组(账户类型) +│   │      ├── 自动登录 +│   │      └── 语言 +│   └── 用户组(Group) +│      └── 添加、修改、删除用户组,包括以下信息 +│         ├── 组名 +│         └── 组用户 +├── 个性化(Personal) +│   ├── 个性化(Personal) +│   │   ├── 主题 +│   │   ├── 屏幕保护程序 +│   │   ├── 桌面壁纸 +│   │   └── 桌面图标大小 +│   ├── 显示(Display) +│   │   ├── 分辨率 +│   │   ├── 多屏设置 +│   │   └── 屏幕方向 +│   └── 字体设置(Fonts) +│      ├── 添加删除字体 +│      └── 设置字体大小 +├── 时间(Date) +│   ├── 日期(Date)和时间(Time) +│   │   ├── 设置日期、时间 +│   │   ├── 系统时间显示格式 +│   │   ├── 禁用/启用时间同步 +│   │   └── 时间同步服务器设置 +│   ├── 语言(Language) +│   │   └── 设置语言 +│   │   └── 设置输入法 +│   └── 区域(Region) +│      └── 设置时区 +├── 语言(Language) +│   ├── 设置语言 +│   └── 输入法(Input) +├── 安全管理(Security) +│   ├── 安全概况(SecurityInfo) +│   │   ├── 获取安全等级及状态 +│   │   ├── 更改安全等级 +│   │   └── 安全策略设置 +│   └── 防火墙(Firewall) +│      ├── 防火墙状态 +│      ├── 防火墙禁用/启用 +│      └── 防火墙规则设置 +├── 软件管理(Software) +│   └── 默认应用程序(DefaultPrograms) +│      ├── 设置默认浏览器 +│      ├── 设置默认文档编辑器 +│      └── 设置默认图片查看器 +├── 系统更新(Updates) +│   ├── 包版本 +│   ├── 系统升级 +│   ├── 包升级 +│   └── 软件源(SoftwareSources) +│      ├── 添加、修改、移除、更新系统软件源 +│      └── 添加、修改、移除、更新第三方软件源 +├── 网络管理(Network) +│   ├── 网络设置(Network) +│   │   ├── 禁用启用网络接口; +│   │   ├── 设置以太网网络接口:IP、子网掩码、网关、DNS +│   │   └── 设置WiFi接口:SSID、密码、IP、子网掩码、网关、DNS +│   ├── 网络状态(Network) +│   │   ├── 接口 +│   │   ├── MAC地址 +│   │   ├── 驱动 +│   │   ├── 链接速度 +│   │   ├── IP地址、子网掩码、广播地址、网关、DNS +│   │   ├── 上传下载速率 +│   │   ├── 总计上传下载数据包 +│   │   ├── 总计上传下载数据量 +│   │   └── 错误、丢弃、过载数据包数量 +│   └── 网络共享(NetworkSharing) +│      └── samba、NFS之类服务 +├── 硬件管理(Hardware) +│   ├── 硬件信息(HardwareInfo) +│   │   ├── CPU:厂商、体系结构、型号、主频 +│   │   ├── 内存:厂商、内存数量、单根内存大小、内存总大小 +│   │   ├── 磁盘:厂商、磁盘数量、磁盘大小 +│   │   ├── 主板:厂商、主板型号 +│   │   ├── 显卡:厂商、显卡型号 +│   │   ├── 以太网:厂商、型号、MAC地址 +│   │   ├── WiFi:厂商、型号、MAC地址 +│   │   └── 蓝牙:厂商、型号、MAC地址 +│   ├── 电源管理(Power) +│   │   ├── 电池设置:是否在菜单栏显示电池状态 +│   │   ├── 关闭显示器时间 +│   │   ├── 唤醒是否需要输入密码 +│   │   └── 睡眠时间 +│   ├── 打印机(Printers) +│   │   ├── 添加、删除打印机 +│   │   └── 打印机测试 +│   ├── 鼠标(Mouse)和触摸板(Touchpad) +│   │   ├── 左右手习惯 +│   │   ├── 双击速度 +│   │   ├── 指针图标 +│   │   ├── 指针移动速度 +│   │   ├── 滚轮滚动行数 +│   │   └── 触摸板行为(这项可能需要与硬件匹配) +│   ├── 键盘(Keyboard) +│   │   ├── 打开/关闭按住某一键时重复该键:重复延时、重复速度 +│   │   ├── 打开/关闭光标闪烁:光标闪烁速度 +│   │   └── 快捷键:获取系统预设快捷键、设置自定义快捷键、删除自定义快捷键 +│   ├── 声音管理(Sound) +│   │   ├── 输出管理:音量大小、静音、左右声道、输出源选择 +│   │   ├── 输入管理:音量大小、静音、输出源选择 +│   │   ├── 声音效果:警告音量、警告静音、选择警告声音 +│   │   ├── 应用程序:应用音量设置 +│   │   └── 菜单栏是否显示音量 +│   ├── 显示器设置(Display) +│   │   ├── 分辨率 +│   │   ├── 多屏设置 +│   │   └── 屏幕方向 +│   └── 蓝牙(Bluetooth) +│      ├── 打开关闭蓝牙 +│      ├── 蓝牙设备列表 +│      └── 菜单栏显示蓝牙状态 +└── 其他功能 +``` diff --git a/autogen.sh b/autogen.sh new file mode 100755 index 0000000..2c26593 --- /dev/null +++ b/autogen.sh @@ -0,0 +1,9 @@ +#!/bin/sh +#aclocal +#autoconf +#autoheader +#libtoolize --copy +#automake --copy --add-missing + +echo "Regenerating autotools files" +autoreconf --force --install || exit 1 diff --git a/configure.ac b/configure.ac new file mode 100644 index 0000000..7a25304 --- /dev/null +++ b/configure.ac @@ -0,0 +1,72 @@ +# -*- Autoconf -*- +# Process this file with autoconf to produce a configure script. + +AC_PREREQ([2.69]) +AC_INIT(ukui-interface,1.0,liuhao@kylinos.cn) +AM_INIT_AUTOMAKE +AC_CONFIG_SRCDIR([config.h.in]) +AC_CONFIG_HEADERS([config.h]) + +# Checks for programs. +AC_PROG_CXX +AC_PROG_AWK +AC_PROG_CC +AC_PROG_CPP +AC_PROG_INSTALL +AC_PROG_LN_S +AC_PROG_MAKE_SET +AC_PROG_RANLIB +AC_PROG_LIBTOOL + +# Checks for libraries. + +PKG_CHECK_MODULES(GLIB_2, glib-2.0 >= 1.00) +PKG_CHECK_MODULES(GIO_2, gio-2.0 >= 1.00) +PKG_CHECK_MODULES(GIO_UNIX_2, gio-unix-2.0 >= 1.00) +PKG_CHECK_MODULES(QT5CORE, Qt5Core >= 5.6.1) + +# FIXME: Replace `main' with a function in `-lgsettings': +AC_CHECK_LIB([gsettings], [main]) +# FIXME: Replace `main' with a function in `-lprint': +AC_CHECK_LIB([print], [main]) + +# Checks for header files. +AC_CHECK_HEADERS([stdlib.h string.h unistd.h]) + +# Checks for typedefs, structures, and compiler characteristics. +AC_CHECK_HEADER_STDBOOL + +# Checks for library functions. +AC_CHECK_FUNCS([strerror]) + +AC_CONFIG_FILES([Makefile + data/Makefile + po/Makefile + src/Makefile + src/accounts/Makefile + src/accounts/user/Makefile + src/common/Makefile + src/date/Makefile + src/date/dttm/Makefile + src/hardware/Makefile + src/hardware/keyboard/Makefile + src/hardware/mouse/Makefile + src/hardware/touchpad/Makefile + src/hardware/power/Makefile + src/language/Makefile + src/network/Makefile + src/network/network/Makefile + src/os/Makefile + src/os/subversion/Makefile + src/os/sysinfo/Makefile + src/other/Makefile + src/personal/Makefile + src/personal/background/Makefile + src/personal/desktop/Makefile + src/personal/font/Makefile + src/personal/marcogeneral/Makefile + src/security/Makefile + src/software/Makefile + src/software/defaultprograms/Makefile + src/updates/Makefile]) +AC_OUTPUT diff --git a/data/Makefile.am b/data/Makefile.am new file mode 100644 index 0000000..667c5d8 --- /dev/null +++ b/data/Makefile.am @@ -0,0 +1,9 @@ +dbusdir = /usr/share/dbus-1/services +dist_dbus_DATA = cn.kylinos.font.service \ + cn.kylinos.mouse.service cn.kylinos.touchpad.service \ + cn.kylinos.desktop.service \ + cn.kylinos.background.service \ + cn.kylinos.marcogeneral.service \ + cn.kylinos.xkbgeneral.service cn.kylinos.interface.service cn.kylinos.keyboard.service \ + cn.kylinos.power.service cn.kylinos.screensaver.service cn.kylinos.session.service \ + $(NULL) diff --git a/data/cn.kylinos.background.service b/data/cn.kylinos.background.service new file mode 100755 index 0000000..a150865 --- /dev/null +++ b/data/cn.kylinos.background.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=cn.kylinos.background +Exec=/usr/libexec/ukui-backgroundserver diff --git a/data/cn.kylinos.background.xml b/data/cn.kylinos.background.xml new file mode 100644 index 0000000..9fb44fd --- /dev/null +++ b/data/cn.kylinos.background.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/data/cn.kylinos.desktop.service b/data/cn.kylinos.desktop.service new file mode 100755 index 0000000..08860bf --- /dev/null +++ b/data/cn.kylinos.desktop.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=cn.kylinos.desktop +Exec=/usr/libexec/ukui-desktopserver diff --git a/data/cn.kylinos.desktop.xml b/data/cn.kylinos.desktop.xml new file mode 100644 index 0000000..e6a1f23 --- /dev/null +++ b/data/cn.kylinos.desktop.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/data/cn.kylinos.font.service b/data/cn.kylinos.font.service new file mode 100755 index 0000000..246ea8c --- /dev/null +++ b/data/cn.kylinos.font.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=cn.kylinos.font +Exec=/usr/libexec/ukui-fontserver diff --git a/data/cn.kylinos.font.xml b/data/cn.kylinos.font.xml new file mode 100644 index 0000000..1fbb0fc --- /dev/null +++ b/data/cn.kylinos.font.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/data/cn.kylinos.interface.service b/data/cn.kylinos.interface.service new file mode 100755 index 0000000..c74ddc6 --- /dev/null +++ b/data/cn.kylinos.interface.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=cn.kylinos.interface +Exec=/usr/libexec/ukui-interfaceserver diff --git a/data/cn.kylinos.interface.xml b/data/cn.kylinos.interface.xml new file mode 100644 index 0000000..cd622aa --- /dev/null +++ b/data/cn.kylinos.interface.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/cn.kylinos.keyboard.service b/data/cn.kylinos.keyboard.service new file mode 100755 index 0000000..f551895 --- /dev/null +++ b/data/cn.kylinos.keyboard.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=cn.kylinos.keyboard +Exec=/usr/libexec/ukui-keyboardserver diff --git a/data/cn.kylinos.keyboard.xml b/data/cn.kylinos.keyboard.xml new file mode 100644 index 0000000..04947dd --- /dev/null +++ b/data/cn.kylinos.keyboard.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/cn.kylinos.marcogeneral.service b/data/cn.kylinos.marcogeneral.service new file mode 100755 index 0000000..77cf44c --- /dev/null +++ b/data/cn.kylinos.marcogeneral.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=cn.kylinos.marcogeneral +Exec=/usr/libexec/ukui-marcogeneralserver diff --git a/data/cn.kylinos.marcogeneral.xml b/data/cn.kylinos.marcogeneral.xml new file mode 100644 index 0000000..45d7137 --- /dev/null +++ b/data/cn.kylinos.marcogeneral.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/data/cn.kylinos.mouse.service b/data/cn.kylinos.mouse.service new file mode 100755 index 0000000..9ec364a --- /dev/null +++ b/data/cn.kylinos.mouse.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=cn.kylinos.mouse +Exec=/usr/libexec/ukui-mouseserver diff --git a/data/cn.kylinos.mouse.xml b/data/cn.kylinos.mouse.xml new file mode 100644 index 0000000..3df62e8 --- /dev/null +++ b/data/cn.kylinos.mouse.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/cn.kylinos.power.service b/data/cn.kylinos.power.service new file mode 100755 index 0000000..10a373c --- /dev/null +++ b/data/cn.kylinos.power.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=cn.kylinos.power +Exec=/usr/libexec/ukui-powerserver diff --git a/data/cn.kylinos.power.xml b/data/cn.kylinos.power.xml new file mode 100644 index 0000000..8acb9f8 --- /dev/null +++ b/data/cn.kylinos.power.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/data/cn.kylinos.screensaver.service b/data/cn.kylinos.screensaver.service new file mode 100755 index 0000000..99cf141 --- /dev/null +++ b/data/cn.kylinos.screensaver.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=cn.kylinos.screensaver +Exec=/usr/libexec/ukui-screensaverserver diff --git a/data/cn.kylinos.screensaver.xml b/data/cn.kylinos.screensaver.xml new file mode 100644 index 0000000..9e6dbc1 --- /dev/null +++ b/data/cn.kylinos.screensaver.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/data/cn.kylinos.session.service b/data/cn.kylinos.session.service new file mode 100755 index 0000000..51bdbe0 --- /dev/null +++ b/data/cn.kylinos.session.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=cn.kylinos.session +Exec=/usr/libexec/ukui-sessionserver diff --git a/data/cn.kylinos.session.xml b/data/cn.kylinos.session.xml new file mode 100644 index 0000000..92f8a8e --- /dev/null +++ b/data/cn.kylinos.session.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/data/cn.kylinos.touchpad.service b/data/cn.kylinos.touchpad.service new file mode 100755 index 0000000..50791c2 --- /dev/null +++ b/data/cn.kylinos.touchpad.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=cn.kylinos.touchpad +Exec=/usr/libexec/ukui-touchpadserver diff --git a/data/cn.kylinos.touchpad.xml b/data/cn.kylinos.touchpad.xml new file mode 100644 index 0000000..aa20524 --- /dev/null +++ b/data/cn.kylinos.touchpad.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/data/cn.kylinos.xkbgeneral.service b/data/cn.kylinos.xkbgeneral.service new file mode 100755 index 0000000..571e6cc --- /dev/null +++ b/data/cn.kylinos.xkbgeneral.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=cn.kylinos.xkbgeneral +Exec=/usr/libexec/ukui-xkbgeneralserver diff --git a/data/cn.kylinos.xkbgeneral.xml b/data/cn.kylinos.xkbgeneral.xml new file mode 100644 index 0000000..a207529 --- /dev/null +++ b/data/cn.kylinos.xkbgeneral.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/po/LINGUAS b/po/LINGUAS new file mode 100644 index 0000000..6b88f63 --- /dev/null +++ b/po/LINGUAS @@ -0,0 +1,2 @@ +bo +zh_CN diff --git a/po/Makefile.am b/po/Makefile.am new file mode 100644 index 0000000..e69de29 diff --git a/po/Makevars b/po/Makevars new file mode 100644 index 0000000..5afab09 --- /dev/null +++ b/po/Makevars @@ -0,0 +1,41 @@ +# Makefile variables for PO directory in any package using GNU gettext. + +# Usually the message domain is the same as the package name. +DOMAIN = $(PACKAGE) + +# These two variables depend on the location of this directory. +subdir = po +top_builddir = .. + +# These options get passed to xgettext. +XGETTEXT_OPTIONS = --keyword=_ --keyword=N_ + +# This is the copyright holder that gets inserted into the header of the +# $(DOMAIN).pot file. Set this to the copyright holder of the surrounding +# package. (Note that the msgstr strings, extracted from the package's +# sources, belong to the copyright holder of the package.) Translators are +# expected to transfer the copyright for their translations to this person +# or entity, or to disclaim their copyright. The empty string stands for +# the public domain; in this case the translators are expected to disclaim +# their copyright. +COPYRIGHT_HOLDER = Kylin Teams + +# This is the email address or URL to which the translators shall report +# bugs in the untranslated strings: +# - Strings which are not entire sentences, see the maintainer guidelines +# in the GNU gettext documentation, section 'Preparing Strings'. +# - Strings which use unclear terms or require additional context to be +# understood. +# - Strings which make invalid assumptions about notation of date, time or +# money. +# - Pluralisation problems. +# - Incorrect English spelling. +# - Incorrect formatting. +# It can be your email address, or a mailing list address where translators +# can write to without being subscribed, or the URL of a web page through +# which the translators can contact you. +MSGID_BUGS_ADDRESS = $(PACKAGE_BUGREPORT) + +# This is the list of locale categories, beyond LC_MESSAGES, for which the +# message catalogs shall be used. It is usually empty. +EXTRA_LOCALE_CATEGORIES = diff --git a/po/POTFILES.in b/po/POTFILES.in new file mode 100644 index 0000000..e69de29 diff --git a/po/zh_CN.po b/po/zh_CN.po new file mode 100644 index 0000000..c3c66c7 --- /dev/null +++ b/po/zh_CN.po @@ -0,0 +1,18 @@ +# Chinese translations for ukui-interface package. +# Copyright (C) 2017 THE ukui-interface'S COPYRIGHT HOLDER +# This file is distributed under the same license as the ukui-interface package. +# droiing , 2017. +# +msgid "" +msgstr "" +"Project-Id-Version: ukui-interface 0.0.1\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2017-11-28 15:00+0800\n" +"PO-Revision-Date: 2017-11-28 11:57+0800\n" +"Last-Translator: droiing \n" +"Language-Team: Chinese (simplified)\n" +"Language: zh_CN\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + diff --git a/src/Makefile.am b/src/Makefile.am new file mode 100644 index 0000000..089176d --- /dev/null +++ b/src/Makefile.am @@ -0,0 +1,5 @@ +NULL = + +SUBDIRS = accounts common hardware language network \ + other personal security updates \ + $(NULL) diff --git a/src/accounts/Makefile.am b/src/accounts/Makefile.am new file mode 100644 index 0000000..280c1e7 --- /dev/null +++ b/src/accounts/Makefile.am @@ -0,0 +1 @@ +SUBDIRS=user diff --git a/src/accounts/user/Makefile.am b/src/accounts/user/Makefile.am new file mode 100644 index 0000000..d70a385 --- /dev/null +++ b/src/accounts/user/Makefile.am @@ -0,0 +1,25 @@ +#Generata binary file +lib_LTLIBRARIES = libukui-usersetting.la + +#gcc -wall: displays all the errors and warning information when compiling +#gcc -g: add the debugging code when compiling +COMM_CFS = -Wall -g + +#Add the dependent source file for libukui-usersetting.la +libukui_usersetting_la_SOURCES = kylin-user-interface.c \ + $(NULL) + +#The header files that need to be installed +include_HEADERS= kylin-user-interface.h \ + $(NULL) + +#Additional C compiler flags +libukui_usersetting_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_usersetting_la_LDFLAGS= -lcrypt \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + diff --git a/src/accounts/user/kylin-user-interface.c b/src/accounts/user/kylin-user-interface.c new file mode 100755 index 0000000..3042622 --- /dev/null +++ b/src/accounts/user/kylin-user-interface.c @@ -0,0 +1,316 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include"kylin-user-interface.h" + +static gchar +salt_char (GRand *rand) +{ + gchar salt[] = "ABCDEFGHIJKLMNOPQRSTUVXYZ" + "abcdefghijklmnopqrstuvxyz" + "./0123456789"; + + return salt[g_rand_int_range (rand, 0, G_N_ELEMENTS (salt))]; +} + +static gchar * +make_crypted (const char *plain) +{ + GString *salt; + gchar *result; + GRand *rand; + gint i; + + rand = g_rand_new (); + salt = g_string_sized_new (21); + + /* SHA 256 */ + g_string_append (salt, "$6$"); + for (i = 0; i < 16; i++) { + g_string_append_c (salt, salt_char (rand)); + } + g_string_append_c (salt, '$'); + + result = g_strdup ((const gchar *)crypt(plain, salt->str)); + + g_string_free (salt, TRUE); + g_rand_free (rand); + + return result; +} + +//获取用户对象路径 +static gchar *getpath(char *username) +{ + GDBusProxy *account_proxy; + GVariant *result; + + account_proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, + NULL, "org.freedesktop.Accounts", + "/org/freedesktop/Accounts", + "org.freedesktop.Accounts", NULL, NULL); + + result=g_dbus_proxy_call_sync(account_proxy, "FindUserByName", + g_variant_new("(s)", username), + G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL); + + if(result!=NULL){ + gchar *path = (char *)g_variant_get_data(result); + + if (account_proxy){ + g_object_unref(account_proxy); + } + + return path; + } + else{ + return NULL; + } +} + +//添加新用户 +void kylin_accounts_user_createuser(char *username, int accounttype, char *password, char *iconfile) +{ + GError *error = NULL; + GError *pProxyError = NULL; + GVariant *result; + GDBusProxy *account_proxy; + + account_proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM,G_DBUS_PROXY_FLAGS_NONE, + NULL, "org.freedesktop.Accounts", + "/org/freedesktop/Accounts", + "org.freedesktop.Accounts", NULL, &error); + if (error != NULL) + { + g_error("Could not connect to org.freedesktop.Accounts:%s\n",error->message); + if (account_proxy) + g_object_unref(account_proxy); + return; + } + + //设置用户名 + result=g_dbus_proxy_call_sync(account_proxy, "CreateUser", + g_variant_new("(ssi)", username, "", accounttype), + G_DBUS_CALL_FLAGS_NONE, -1, NULL, &pProxyError); + + if (result != NULL) + { + char *crypted = make_crypted(password); + + if(iconfile==NULL) + iconfile = "/usr/share/pixmaps/faces/stock_person.svg"; + + GDBusProxy *proxy; + GError * err = NULL; + + char *path = (char *)g_variant_get_data(result); + + proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, + NULL, "org.freedesktop.Accounts", + path, + "org.freedesktop.Accounts.User", NULL, &err); + + //设置用户头像 + g_dbus_proxy_call_sync(proxy, "SetIconFile", + g_variant_new("(s)", iconfile), + G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL); + + //设置用户密码 + g_dbus_proxy_call_sync(proxy, "SetPassword", + g_variant_new("(ss)", crypted, ""), + G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL); + + //设置用户类型 + g_dbus_proxy_call_sync(proxy, "SetAccountType", + g_variant_new("(i)", accounttype), + G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL); + + if (proxy){ + g_object_unref(proxy); + } + + } + + else{ + g_warning("-----------%s had already existed----------",username); + } + + if (account_proxy){ + g_object_unref(account_proxy); + } + +} + +//设置自动登录 +void kylin_accounts_user_autologin(char *username, bool login) +{ + GError * err = NULL; + gchar *path=getpath(username); + + if(path!=NULL){ + GDBusProxy *proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, + NULL, "org.freedesktop.Accounts", + path, + "org.freedesktop.Accounts.User", NULL, &err); + + g_dbus_proxy_call_sync(proxy, "SetAutomaticLogin", + g_variant_new("(b)", login), + G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL); + + if (proxy){ + g_object_unref(proxy); + } + } + else{ + g_warning("-----------%s does not existed----------",username); + } +} + +//更改用户头像 +void kylin_accounts_user_chgusericon(char *username, char *iconfile) +{ + GError * err = NULL; + gchar *path=getpath(username); + + if(path!=NULL){ + GDBusProxy *proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, + NULL, "org.freedesktop.Accounts", + path, + "org.freedesktop.Accounts.User", NULL, &err); + + g_dbus_proxy_call_sync(proxy, "SetIconFile", + g_variant_new("(s)", iconfile), + G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL); + + if (proxy){ + g_object_unref(proxy); + } + } + else{ + g_warning("-----------%s does not existed----------",username); + } + + +} + +//更改用户密码 +void kylin_accounts_user_chguserpasswd(char *username, char *password) +{ + GError * err = NULL; + gchar *path=getpath(username); + + if(path!=NULL){ + GDBusProxy *proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, + NULL, "org.freedesktop.Accounts", + path, + "org.freedesktop.Accounts.User", NULL, &err); + + char *crypted = make_crypted(password); + + g_dbus_proxy_call_sync(proxy, "SetPassword", + g_variant_new("(ss)", crypted, ""), + G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL); + + if (proxy){ + g_object_unref(proxy); + } + } + else{ + g_warning("-----------%s does not existed----------",username); + } + +} + +//更改账户类型 +void kylin_accounts_user_chgusertype(char *username, int accounttype) +{ + GError * err = NULL; + gchar *path=getpath(username); + + if(path!=NULL){ + GDBusProxy *proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, + NULL, "org.freedesktop.Accounts", + path, + "org.freedesktop.Accounts.User", NULL, &err); + + g_dbus_proxy_call_sync(proxy, "SetAccountType", + g_variant_new("(i)", accounttype), + G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL); + + if (proxy){ + g_object_unref(proxy); + } + } + else{ + g_warning("-----------%s does not existed----------",username); + } + +} + +//删除用户 +void kylin_accounts_user_deleteuser(char *username, bool removefile) +{ + GDBusProxy *account_proxy; + GDBusProxy *proxy; + GError * err = NULL; + + gchar *path = getpath(username); + + if(path!=NULL){ + proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, + NULL, "org.freedesktop.Accounts", + path, + "org.freedesktop.Accounts.User", NULL, &err); + + //获取用户账户的UID + GVariant *value = g_dbus_proxy_get_cached_property(proxy, "Uid"); + gint uid = (gint)g_variant_get_uint64(value); + + g_warning("-----------%d----------",uid); + + account_proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, + NULL, "org.freedesktop.Accounts", + "/org/freedesktop/Accounts", + "org.freedesktop.Accounts", NULL, NULL); + + //删除用户账户 + g_dbus_proxy_call_sync(account_proxy, "DeleteUser", + g_variant_new("(xb)", uid, removefile), + G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL); + + if (account_proxy){ + g_object_unref(account_proxy); + } + + if (proxy){ + g_object_unref(proxy); + } + } + else{ + g_warning("-----------%s does not existed----------",username); + } + +} diff --git a/src/accounts/user/kylin-user-interface.h b/src/accounts/user/kylin-user-interface.h new file mode 100755 index 0000000..ec45228 --- /dev/null +++ b/src/accounts/user/kylin-user-interface.h @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C"{ +#endif + +/* + * create new user. + * @username is the login name. + * @accounttype is the user type, "0" is the standard user, and "1" is the administrators. + * @password is the login password. + * @iconfile is the path of the user image. + */ +void kylin_accounts_user_createuser(char *username, + int accounttype, + char *password, + char *iconfile); + +/* + * set to login automatically. + * @login can be set to true, indicating automatic login. + */ +void kylin_accounts_user_autologin(char *username, bool login); + +/* + * change the user image. + * @iconfile is the path of the user image. + */ +void kylin_accounts_user_chgusericon(char *username, + char *iconfile); + +/* + * change the user password. + * @password is the login password. + */ +void kylin_accounts_user_chguserpasswd(char *username, + char *password); + +/* + * change the user type. + * @accounttype is the user type, "0" is the standard user, and "1" is the administrators. + */ +void kylin_accounts_user_chgusertype(char *username, + int accounttype); + +/* + * delete the user. + * @remove represents whether to delete the user directory. + */ +void kylin_accounts_user_deleteuser(char *username, + bool removefile); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/common/Makefile.am b/src/common/Makefile.am new file mode 100644 index 0000000..3a09c4a --- /dev/null +++ b/src/common/Makefile.am @@ -0,0 +1,64 @@ +#Generata binary file +lib_LTLIBRARIES = libukui-print.la libukui-gsettings.la libukui-com4c.la libukui-com4cxx.la + +#gcc -wall: displays all the errors and warning information when compiling +#gcc -g: add the debugging code when compiling +COMM_CFS = -Wall -g + +#Add the dependent source file for libukui-com4c.la +libukui_com4c_la_SOURCES = kylin-com4c.c \ + kylin-ini.c \ + $(NULL) + +#Additional C compiler flags +libukui_com4c_la_CFLAGS= $(COMM_CFS) \ + -liniparser \ + $(NULL) + +#Additional link objects +libukui_com4c_la_LDFLAGS= \ + $(NULL) + +#Add the dependent source file for libukui-com4cxx.la +libukui_com4cxx_la_SOURCES = kylin-com4cxx.cpp \ + kylin-ini.c \ + $(NULL) + +#Additional CXX compiler flags +libukui_com4cxx_la_CXXFLAGS= $(COMM_CFS) \ + -liniparser \ + $(NULL) + +#Additional C compiler flags +libukui_com4cxx_la_CFLAGS= $(COMM_CFS) \ + $(NULL) + +#Additional link objects +libukui_com4cxx_la_LDFLAGS= \ + $(NULL) + +#Add the dependent source file for libukui-print.la +libukui_print_la_SOURCES = kylin-print.c \ + $(NULL) + +#Add the dependent source file for libukui-gsettings.la +libukui_gsettings_la_SOURCES = kylin-gsettings-set.c \ + $(NULL) + +#The header files that need to be installed +include_HEADERS= \ + kylin-com4c.h \ + kylin-com4cxx.h \ + kylin-print.h \ + kylin-gsettings-set.h \ + $(NULL) + +#Additional C compiler flags +libukui_gsettings_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_gsettings_la_LDFLAGS= \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) diff --git a/src/common/kylin-com4c.c b/src/common/kylin-com4c.c new file mode 100644 index 0000000..ef744c2 --- /dev/null +++ b/src/common/kylin-com4c.c @@ -0,0 +1,220 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include + +#include "kylin-ini.h" + +#define LSB_RELEASE_FILE "/etc/lsb-release" /* lsb-release文件路径 */ +#define OS_RELEASE_FILE "/etc/os-release" /* os-release文件路径 */ +#define KYINFO_FILE "/etc/.kyinfo" /* kyinfo文件路径 */ +#define CPUINFO_FILE "/proc/cpuinfo" /* cpuinfo文件路径 */ +#define RELEASEFILE_LINE_MAX 256 /* 最大解析行行数 */ +#define RELEASEFILE_LINE_MAX_LEN 256 /* 最大解析行长度 */ +#define RELEASEFILE_KEY_MAX_LEN 128 /* 最大key长度 */ +#define RELEASEFILE_VALUE_MAX_LEN 256 /* 最大value长度 预留'\0', '='*/ +#define RELEASEFILE_SPLIT_EQUAL '=' /* key和value的分隔符 */ +#define RELEASEFILE_SPLIT_COLON ':' /* key和value的分隔符 */ +#define PROJECT_CODENAME "PROJECT_CODENAME" +#define CPUINFO_MODELNAME "model name" + +// 根据key获取value,成功返回 >0 否则 返回 <= 0 +static int file_get_keyvalue(const char *path, const char *key, char *value, int value_max_len, const char chSplit) +{ + if (path == NULL || key == NULL || value == NULL || value_max_len <= 0) { + return -1; + } + int ret = 0; + int cnt = 0; + int key_len = 0; + int line_len = 0; + int value_len = 0; + FILE *fp = NULL; + char line_buf[RELEASEFILE_LINE_MAX_LEN] = {0}; + + /* 合法性判断 */ + if (NULL == path || NULL == key || NULL == value || 0 >= value_max_len) { + return -1; + } + + key_len = strlen(key); + if (0 >= key_len || RELEASEFILE_KEY_MAX_LEN < key_len) { + return -2; + } + + if (F_OK != access(path, F_OK)) { + return -3; + } + + /* 打开文件 */ + fp = fopen(path, "r"); + if (NULL == fp) { + return -4; + } + + /* 遍历行,匹配Key */ + while(NULL != fgets(line_buf, RELEASEFILE_LINE_MAX_LEN-1, fp)) { + line_len = strlen(line_buf); + if (line_len > key_len) { + /* 找到key */ + //找到非空格的首字符 + char *pStart = line_buf; + int nSplitIndex = 0; + while(pStart != (line_buf+line_len) && isspace(*pStart)) { + ++pStart; ++nSplitIndex; + } + if (0 == strncmp(pStart, key, key_len)) { + pStart = pStart + key_len; + nSplitIndex = nSplitIndex + key_len; + //跳过空格字符 + while(pStart != (line_buf+line_len) && isspace(*pStart)) { + ++pStart; ++nSplitIndex; + } + if (pStart != (line_buf+line_len) && *pStart == chSplit) { + ret = 1; + key_len = nSplitIndex; + break; + } + } + } + memset(line_buf, 0, sizeof(line_buf)); + + /* 最大查找行限制 */ + cnt++; + if (RELEASEFILE_LINE_MAX < cnt) { + break; + } + } + + /* 关闭文件 */ + fclose(fp); + fp = NULL; + + /* 找到key,返回value */ + if (1 == ret) { + value_len = line_len - key_len - 1; + if (0 < value_len) { + if (value_len > value_max_len) { + value_len = value_max_len; + } + /* 拷贝value */ + snprintf(value, value_max_len, "%s", &line_buf[key_len + 1]); + value[value_len] = '\0'; + + /* 去掉结尾的换行符 */ + strstrip(value, 1); + } else { + value[0] = '\0'; + } + } + return ret; +} + +/** + * @fn kdk_get_xdgsessiontype + * @brief 获取区分x11与wayland的环境变量值 + * @retval char* !NULL 成功 否则失败 + */ +char* kdk_get_xdgsessiontype() +{ + return getenv("XDG_SESSION_TYPE"); +} + +int kdk_get_lsbrelease(const char *key, char *value, int value_max_len) +{ + int nRet = -1; + if (NULL == key || NULL == value || 0 >= value_max_len) + return nRet; + dictionary *iniHandle = iniparser_load(LSB_RELEASE_FILE); + if (iniHandle) { + char sessionKey[256] = {0}; + snprintf(sessionKey, 256, ":%s", key); + const char *tempValue = iniparser_getstring(iniHandle, sessionKey, ""); + snprintf(value, value_max_len, "%s", tempValue); + iniparser_freedict(iniHandle); + iniHandle = NULL; + nRet = strlen(value); + } + return nRet; +} + +int kdk_get_osrelease(const char *key, char *value, int value_max_len) +{ + int nRet = -1; + if (NULL == key || NULL == value || 0 >= value_max_len) + return nRet; + dictionary *iniHandle = iniparser_load(OS_RELEASE_FILE); + if (iniHandle) { + char sessionKey[256] = {0}; + snprintf(sessionKey, 256, ":%s", key); + const char *tempValue = iniparser_getstring(iniHandle, sessionKey, ""); + snprintf(value, value_max_len, "%s", tempValue); + iniparser_freedict(iniHandle); + iniHandle = NULL; + nRet = strlen(value); + } + return nRet; +} + +int kdk_get_prjcodename(char *value, int value_max_len) +{ + int nResult = kdk_get_lsbrelease(PROJECT_CODENAME, value, value_max_len); + if (nResult <= 0) { + nResult = kdk_get_osrelease(PROJECT_CODENAME, value, value_max_len); + } + return nResult; +} + +int kdk_get_kyinfo(const char *session, const char *key, char *value, int value_max_len) +{ + int nRet = -1; + if (NULL == session || NULL == key || NULL == value || 0 >= value_max_len) + return nRet; + dictionary *iniHandle = iniparser_load(KYINFO_FILE); + if (iniHandle) { + char sessionKey[256] = {0}; + snprintf(sessionKey, 256, "%s:%s", session, key); + const char *tempValue = iniparser_getstring(iniHandle, sessionKey, ""); + snprintf(value, value_max_len, "%s", tempValue); + iniparser_freedict(iniHandle); + iniHandle = NULL; + nRet = strlen(value); + } + return nRet; +} + +int kdk_get_cpumodelname(char *modelName, int max_len) +{ + return file_get_keyvalue(CPUINFO_FILE, CPUINFO_MODELNAME, modelName, max_len, RELEASEFILE_SPLIT_COLON); +} + +int kdk_get_spechdplatform(char *platformName, int max_len) +{ + if (platformName == NULL || max_len <= 0) + return -1; + char strDefault[128] = "default"; + int validLen = strlen(strDefault); + validLen = validLen > max_len ? max_len : validLen; + snprintf(platformName, max_len, "%s", strDefault); + return validLen; +} \ No newline at end of file diff --git a/src/common/kylin-com4c.h b/src/common/kylin-com4c.h new file mode 100644 index 0000000..f890120 --- /dev/null +++ b/src/common/kylin-com4c.h @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @fn kdk_get_lsbrelease + * @brief 根据lsbrelease信息的键获取值 + * @param[in] key lsbrelease信息的键 + * @param[out] value lsbrelease信息的值 + * @param[in] value_max_len 值缓存区的大小 + * @retval int > 0 成功 否则失败 + */ +int kdk_get_lsbrelease(const char *key, char *value, int value_max_len); + +/** + * @fn kdk_get_osrelease + * @brief 根据osrelease信息的键获取值 + * @param[in] key osrelease信息的键 + * @param[out] value osrelease信息的值 + * @param[in] value_max_len 值缓存区的大小 + * @retval int > 0 成功 否则失败 + */ +int kdk_get_osrelease(const char *key, char *value, int value_max_len); + +/** + * @fn kdk_get_kyinfo + * @brief 根据kyinfo的键获取值 + * @param[in] session kyinfo的session值 + * @param[in] key kyinfo的键 + * @param[out] value kyinfo的值 + * @param[in] value_max_len 值缓存区的大小 + * @retval int >= 0 成功 否则失败 + */ +int kdk_get_kyinfo(const char *session, const char *key, char *value, int value_max_len); + +/** + * @fn kdk_get_prjcodename + * @brief 根据PROJECT_CODENAME字段的值 + * @param[out] value PROJECT_CODENAME字段的值 + * @param[in] value_max_len 值缓存区的大小 + * @retval int > 0 成功 否则失败 + */ +int kdk_get_prjcodename(char *value, int value_max_len); + +/** + * @fn kdk_get_cpumodelname + * @brief 获取CPU型号 + * @param[out] modelName CPU型号信息 + * @param[in] max_len CPU型号缓存区的大小 + * @retval int > 0 成功 否则失败 + */ +int kdk_get_cpumodelname(char *modelName, int max_len); + +/** + * @fn kdk_get_spechdplatform + * @brief 获取特定硬件平台信息 + * @param[out] platformName 特定硬件平台信息 + * @param[in] max_len 特定硬件平台缓存区的大小 + * @retval int > 0 成功 否则失败 + */ +int kdk_get_spechdplatform(char *platformName, int max_len); + +#ifdef __cplusplus +} +#endif + +#endif // __KYLINCOMM4C_H__ \ No newline at end of file diff --git a/src/common/kylin-com4cxx.cpp b/src/common/kylin-com4cxx.cpp new file mode 100644 index 0000000..6cbe950 --- /dev/null +++ b/src/common/kylin-com4cxx.cpp @@ -0,0 +1,223 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include + +#include "kylin-ini.h" + +#define LSB_RELEASE_FILE "/etc/lsb-release" /* lsb-release文件路径 */ +#define OS_RELEASE_FILE "/etc/os-release" /* os-release文件路径 */ +#define KYINFO_FILE "/etc/.kyinfo" /* kyinfo文件路径 */ +#define CPUINFO_FILE "/proc/cpuinfo" /* cpuinfo文件路径 */ +#define RELEASEFILE_LINE_MAX 256 /* 最大解析行行数 */ +#define RELEASEFILE_LINE_MAX_LEN 256 /* 最大解析行长度 */ +#define RELEASEFILE_KEY_MAX_LEN 128 /* 最大key长度 */ +#define RELEASEFILE_VALUE_MAX_LEN 256 /* 最大value长度 预留'\0', '='*/ +#define RELEASEFILE_SPLIT_EQUAL '=' /* key和value的分隔符 */ +#define RELEASEFILE_SPLIT_COLON ':' /* key和value的分隔符 */ +#define PROJECT_CODENAME "PROJECT_CODENAME" +#define CPUINFO_MODELNAME "model name" + +// 根据key获取value,成功返回 >0 否则 返回 <= 0 +static int file_get_keyvalue(const char *path, const char *key, char *value, int value_max_len, const char chSplit) +{ + if (path == NULL || key == NULL || value == NULL || value_max_len <= 0) { + return -1; + } + int ret = 0; + int cnt = 0; + int key_len = 0; + int line_len = 0; + int value_len = 0; + FILE *fp = NULL; + char line_buf[RELEASEFILE_LINE_MAX_LEN] = {0}; + + /* 合法性判断 */ + if (NULL == path || NULL == key || NULL == value || 0 >= value_max_len) { + return -1; + } + + key_len = strlen(key); + if (0 >= key_len || RELEASEFILE_KEY_MAX_LEN < key_len) { + return -2; + } + + if (F_OK != access(path, F_OK)) { + return -3; + } + + /* 打开文件 */ + fp = fopen(path, "r"); + if (NULL == fp) { + return -4; + } + + /* 遍历行,匹配Key */ + while(NULL != fgets(line_buf, RELEASEFILE_LINE_MAX_LEN-1, fp)) { + line_len = strlen(line_buf); + if (line_len > key_len) { + /* 找到key */ + //找到非空格的首字符 + char *pStart = line_buf; + int nSplitIndex = 0; + while(pStart != (line_buf+line_len) && isspace(*pStart)) { + ++pStart; ++nSplitIndex; + } + if (0 == strncmp(pStart, key, key_len)) { + pStart = pStart + key_len; + nSplitIndex = nSplitIndex + key_len; + //跳过空格字符 + while(pStart != (line_buf+line_len) && isspace(*pStart)) { + ++pStart; ++nSplitIndex; + } + if (pStart != (line_buf+line_len) && *pStart == chSplit) { + ret = 1; + key_len = nSplitIndex; + break; + } + } + } + memset(line_buf, 0, sizeof(line_buf)); + + /* 最大查找行限制 */ + cnt++; + if (RELEASEFILE_LINE_MAX < cnt) { + break; + } + } + + /* 关闭文件 */ + fclose(fp); + fp = NULL; + + /* 找到key,返回value */ + if (1 == ret) { + value_len = line_len - key_len - 1; + if (0 < value_len) { + if (value_len > value_max_len) { + value_len = value_max_len; + } + /* 拷贝value */ + snprintf(value, value_max_len, "%s", &line_buf[key_len + 1]); + value[value_len] = '\0'; + + /* 去掉结尾的换行符 */ + strstrip(value, 1); + } else { + value[0] = '\0'; + } + } + return ret; +} + +/** + * @fn KDKGetXdgSessionType + * @brief 获取区分x11与wayland的环境变量值 + * @param None 无参 + * @retval string xdg会话类型字符串,empty 失败,否则成功 + */ +string KDKGetXdgSessionType() +{ + char *strSessionType = getenv("XDG_SESSION_TYPE"); + if (!strSessionType) { + return ""; + } + return string(strSessionType); +} + +string KDKGetLSBRelease(const string key) +{ + if (key.empty()) { + return ""; + } + dictionary *iniHandle = iniparser_load(LSB_RELEASE_FILE); + if (iniHandle) { + string sessionKey = ":"+key; + string strValue = ""; + strValue = iniparser_getstring(iniHandle, sessionKey.c_str(), ""); + iniparser_freedict(iniHandle); + iniHandle = NULL; + return strValue; + } + return ""; +} + +string KDKGetOSRelease(const string key) +{ + if (key.empty()) { + return ""; + } + dictionary *iniHandle = iniparser_load(OS_RELEASE_FILE); + if (iniHandle) { + string sessionKey = ":"+key; + string strValue = ""; + strValue = iniparser_getstring(iniHandle, sessionKey.c_str(), ""); + iniparser_freedict(iniHandle); + iniHandle = NULL; + return strValue; + } + return ""; +} + +string KDKGetPrjCodeName() +{ + string strValue = KDKGetLSBRelease(PROJECT_CODENAME); + if (strValue.empty()) { + strValue = KDKGetOSRelease(PROJECT_CODENAME); + } + return strValue; +} + +string KDKGetKYInfo(const string session, const string key) +{ + if (session.empty() || key.empty()) { + return ""; + } + dictionary *iniHandle = iniparser_load(KYINFO_FILE); + if (iniHandle) { + string sessionKey = session+":"+key; + string strValue = ""; + strValue = iniparser_getstring(iniHandle, sessionKey.c_str(), ""); + iniparser_freedict(iniHandle); + iniHandle = NULL; + return strValue; + } + return ""; +} + +string KDKGetCpuModelName() +{ + char strValue[256] = {0}; + int nRet = file_get_keyvalue(CPUINFO_FILE, CPUINFO_MODELNAME, strValue, 256, RELEASEFILE_SPLIT_COLON); + if (nRet > 0) { + return string(strValue); + } else { + return ""; + } +} + +string KDKGetSpecHDPlatform() +{ + string strDefaultValue = "default"; + return strDefaultValue; +} \ No newline at end of file diff --git a/src/common/kylin-com4cxx.h b/src/common/kylin-com4cxx.h new file mode 100644 index 0000000..c3ac8f3 --- /dev/null +++ b/src/common/kylin-com4cxx.h @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 +using namespace std; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @fn KDKGetLsbRelease + * @brief 根据lsbrelease信息的键获取值 + * @param[in] key lsbrelease信息的键 + * @param[out] value lsbrelease信息的值 + * @param[in] value_max_len 值缓存区的大小 + * @retval string lsbrelease信息的值,empty 失败,否则成功 + */ +string KDKGetLSBRelease(const string key); + +/** + * @fn KDKGetOSRelease + * @brief 根据osrelease信息的键获取值 + * @param[in] key osrelease信息的键 + * @retval string osrelease信息的值,empty 失败,否则成功 + */ +string KDKGetOSRelease(const string key); + +/** + * @fn KDKGetKYInfo + * @brief 根据kyinfo的键获取值 + * @param[in] session kyinfo的session值 + * @param[in] key kyinfo的键 + * @retval string kyinfo信息的键值,empty 失败,否则成功 + */ +string KDKGetKYInfo(const string session, const string key); + +/** + * @fn KDKGetPrjCodeName + * @brief 根据PROJECT_CODENAME字段的值 + * @param None 无参 + * @retval string PROJECT_CODENAME字段的值,empty 失败,否则成功 + */ +string KDKGetPrjCodeName(); + +/** + * @fn KDKGetCpuModelName + * @brief 获取CPU型号 + * @param None 无参 + * @retval string CPU型号信息,empty 失败,否则成功 + */ +string KDKGetCpuModelName(); + +/** + * @fn KDKGetSpecHDPlatform + * @brief 获取特定硬件平台信息 + * @param None 无参 + * @retval string 特定硬件平台信息,empty 失败,否则成功 + */ +string KDKGetSpecHDPlatform(); + +#ifdef __cplusplus +} +#endif + +#endif // __KYLINCOMM4C_H__ \ No newline at end of file diff --git a/src/common/kylin-gsettings-set.c b/src/common/kylin-gsettings-set.c new file mode 100644 index 0000000..12dfcd6 --- /dev/null +++ b/src/common/kylin-gsettings-set.c @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include "kylin-gsettings-set.h" +#include +#include + +//Creates a new GSsetting object with the schema specified by schema_id +GSettings *gsettings_get_schemaID(const gchar *schemaID) +{ + + GSettings *settings = g_settings_new(schemaID); + + return settings; +} + +//Sets int_key in settings to value +bool gsettings_set_int(GSettings *settings, const gchar *key, gint value) +{ + + bool ret=g_settings_set_int(settings, key, value); + return ret; + +} + +//Sets boolean_key in settings to value +bool gsettings_set_boolean(GSettings *settings, const gchar *key, gboolean value) +{ + bool ret=g_settings_set_boolean(settings,key,value); + return ret; + +} + +//Sets double_key in settings to value +bool gsettings_set_double(GSettings *settings, const gchar *key, gdouble value) +{ + + bool ret=g_settings_set_double(settings, key, value); + return ret; + +} + +//Sets string_key in settings to value +bool gsettings_set_string(GSettings *settings, const gchar *key, const gchar *value) +{ + bool ret=g_settings_set_string(settings, key, value); + return ret; + +} + +//Sets enum_key in settings to value +bool gsettings_set_enum(GSettings *settings, const gchar *key, gint value) +{ + + bool ret=g_settings_set_enum(settings, key, value); + return ret; + +} + +//Decreases the reference count of setting +void Dec_ref(GSettings *setting) +{ + g_object_unref(setting); +} + +//fix library-not-linked-against-libc by lintian +void fun() +{ + printf("fun\n"); +} diff --git a/src/common/kylin-gsettings-set.h b/src/common/kylin-gsettings-set.h new file mode 100644 index 0000000..c109a9d --- /dev/null +++ b/src/common/kylin-gsettings-set.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#ifdef __cplusplus +extern "C" { +#endif + +//Creates a new GSsetting object with the schema specified by schema_id +GSettings *gsettings_get_schemaID(const gchar *schemaID); + +//Sets int_key in settings to value +bool gsettings_set_int(GSettings *settings, const gchar *key, gint value); + +//Sets boolean_key in settings to value +bool gsettings_set_boolean(GSettings *settings, const gchar *key, gboolean value); + +//Sets double_key in settings to value +bool gsettings_set_double(GSettings *settings, const gchar *key, gdouble value); + +//Sets string_key in settings to value +bool gsettings_set_string(GSettings *settings, const gchar *key, const gchar *value); + +//Sets enum_key in settings to value +bool gsettings_set_enum(GSettings *settings, const gchar *key, gint value); + +//Decreases the reference count of setting +void Dec_ref(GSettings *setting); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/common/kylin-ini.c b/src/common/kylin-ini.c new file mode 100644 index 0000000..3965919 --- /dev/null +++ b/src/common/kylin-ini.c @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include + +//去除尾部空白字符 包括\t \n \r +/* +标准的空白字符包括: +' ' (0x20) space (SPC) 空格符 +'\t' (0x09) horizontal tab (TAB) 水平制表符 +'\n' (0x0a) newline (LF) 换行符 +'\v' (0x0b) vertical tab (VT) 垂直制表符 +'\f' (0x0c) feed (FF) 换页符 +'\r' (0x0d) carriage return (CR) 回车符 +//windows \r\n linux \n mac \r +*/ +char *strstripr(char *str, int containQuot) +{ + if(str == NULL || *str == '\0') { + return str; + } + int len = strlen(str); + char *p = str + len - 1; + if (containQuot) { + while(p >= str && (isspace(*p) || *p == '\"')) { + *p = '\0'; --p; + } + } else { + while(p >= str && isspace(*p)) { + *p = '\0'; --p; + } + } + return str; +} + +//去除首部空格 +char *strstripl(char *str, int containQuot) +{ + if(str == NULL || *str == '\0') { + return str; + } + int len = 0; + char *p = str; + if (containQuot) { + while(*p != '\0' && (isspace(*p) || *p == '\"')) { + ++p; ++len; + } + } else { + while(*p != '\0' && isspace(*p)) { + ++p; ++len; + } + } + memmove(str, p, strlen(str) - len + 1); + return str; +} + +//去除首尾空格 +char *strstrip(char *str, int containQuot) +{ + str = strstripr(str, containQuot); + str = strstripl(str, containQuot); + return str; +} diff --git a/src/common/kylin-ini.h b/src/common/kylin-ini.h new file mode 100644 index 0000000..7cc94fd --- /dev/null +++ b/src/common/kylin-ini.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// 去除尾部空格 +char *strstripr(char *str, int containQuot); + +// 去除头部空格 +char *strstripl(char *str, int containQuot); + +// 去除前后空格 +char *strstrip(char *str, int containQuot); + +#ifdef __cplusplus +} +#endif + +#endif //__KYLININI_H__ \ No newline at end of file diff --git a/src/common/kylin-print.c b/src/common/kylin-print.c new file mode 100644 index 0000000..87f8391 --- /dev/null +++ b/src/common/kylin-print.c @@ -0,0 +1,174 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include "kylin-print.h" +#include +#include + +int vprint_by_level(int print_level, FILE * __restrict stream, + char * __restrict format, va_list args) +{ + int ret = 0; + int level_int = 0; + + level_int = PRINT_LEVEL_DEFAULT; + + + if (print_level <= level_int) + { + + switch (print_level) + { + case PRINT_LEVEL_EMERG: + case PRINT_LEVEL_ALERT: + case PRINT_LEVEL_CRIT: + case PRINT_LEVEL_ERROR: + fprintf(stderr, "%s", PRINT_COLOR_RED); + break; + case PRINT_LEVEL_WARN: + fprintf(stdout, "%s", PRINT_COLOR_PURPLE); + break; + case PRINT_LEVEL_NOTICE: + fprintf(stdout, "%s", PRINT_COLOR_BLUE); + break; + case PRINT_LEVEL_INFO: + fprintf(stdout, "%s", PRINT_COLOR_CYAN); + break; + case PRINT_LEVEL_DEBUG: + fprintf(stdout, "%s", PRINT_COLOR_YELLOW); + break; + default: + fprintf(stdout, "%s", PRINT_COLOR_WHITE); + } + + + switch (print_level) + { + case PRINT_LEVEL_EMERG: + fprintf(stderr, "[EMERG] "); + break; + case PRINT_LEVEL_ALERT: + fprintf(stderr, "[ALERT] "); + break; + case PRINT_LEVEL_CRIT: + fprintf(stderr, "[CRIT] "); + break; + case PRINT_LEVEL_ERROR: + fprintf(stderr, "[ERROR] "); + break; + case PRINT_LEVEL_WARN: + fprintf(stdout, "[WARN] "); + break; + case PRINT_LEVEL_NOTICE: + fprintf(stdout, "[NOTE] "); + break; + case PRINT_LEVEL_INFO: + fprintf(stdout, "[INFO] "); + break; + case PRINT_LEVEL_DEBUG: + fprintf(stdout, "[DEBUG] "); + break; + default: + fprintf(stdout, "[UKNOW] "); + } + + ret = vfprintf(stream, format, args); + + if (print_level <= PRINT_LEVEL_ERROR && print_level >= 0) + fprintf(stderr, "%s", PRINT_COLOR_END); + else + fprintf(stdout, "%s", PRINT_COLOR_END); + + } + + return ret; +} + +int print_by_level(int print_level, FILE * stream, char * format, ...) +{ + int ret = 0; + va_list args; + + va_start(args, format); + ret = vprint_by_level(print_level, stream, format, args); + va_end(args); + + return ret; +} + +int print_debug(char * format, ...) +{ + int ret = 0; + va_list args; + + va_start(args, format); + ret = vprint_by_level(PRINT_LEVEL_DEBUG, stdout, format, args); + va_end(args); + + return ret; +} + +int print_info(char * format, ...) +{ + int ret = 0; + va_list args; + + va_start(args, format); + ret = vprint_by_level(PRINT_LEVEL_INFO, stdout, format, args); + va_end(args); + + return ret; +} + +int print_notice(char * format, ...) +{ + int ret = 0; + va_list args; + + va_start(args, format); + ret = vprint_by_level(PRINT_LEVEL_NOTICE, stdout, format, args); + va_end(args); + + return ret; +} + +int print_warning(char * format, ...) +{ + int ret = 0; + va_list args; + + va_start(args, format); + ret = vprint_by_level(PRINT_LEVEL_WARN, stdout, format, args); + va_end(args); + + return ret; +} + +int print_error(char * format, ...) +{ + int ret = 0; + va_list args; + + va_start(args, format); + ret = vprint_by_level(PRINT_LEVEL_ERROR, stderr, format, args); + va_end(args); + + return ret; +} diff --git a/src/common/kylin-print.h b/src/common/kylin-print.h new file mode 100644 index 0000000..b36e868 --- /dev/null +++ b/src/common/kylin-print.h @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#define PRINT_LEVEL_EMERG 0 +#define PRINT_LEVEL_ALERT 1 +#define PRINT_LEVEL_CRIT 2 +#define PRINT_LEVEL_ERROR 3 // 错误信息 +#define PRINT_LEVEL_WARN 4 // 警告信息 +#define PRINT_LEVEL_NOTICE 5 // 提示信息 +#define PRINT_LEVEL_INFO 6 // 运行时信息 +#define PRINT_LEVEL_DEBUG 7 // 调试信息 + +//#define PRINT_LEVEL_DEFAULT PRINT_LEVEL_NOTICE // 默认输出信息等级 +#define PRINT_LEVEL_DEFAULT PRINT_LEVEL_DEBUG +//#define PRINT_LEVEL_ENV "PRINT_LEVEL" // 控制信息等级的环境变量 +#define PRINT_LEVEL_COLOR "PRINT_COLOR" // 控制信息颜色的环境变量 + +#define PRINT_COLOR_BLACK "\033[01;30m" +#define PRINT_COLOR_RED "\033[01;31m" +#define PRINT_COLOR_GREEN "\033[01;32m" +#define PRINT_COLOR_YELLOW "\033[01;33m" +#define PRINT_COLOR_BLUE "\033[01;34m" +#define PRINT_COLOR_PURPLE "\033[01;35m" +#define PRINT_COLOR_CYAN "\033[01;36m" +#define PRINT_COLOR_WHITE "\033[01;36m" +#define PRINT_COLOR_END "\033[0m" + +int vprint_by_level(int print_level, FILE * __restrict stream, + char * __restrict format, va_list args); +int print_by_level(int print_level, FILE * stream, char * format, ...); +int print_debug(char * format, ...); +int print_info(char * format, ...); +int print_notice(char * format, ...); +int print_warning(char * format, ...); +int print_error(char * format, ...); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/date/Makefile.am b/src/date/Makefile.am new file mode 100644 index 0000000..31492eb --- /dev/null +++ b/src/date/Makefile.am @@ -0,0 +1 @@ +SUBDIRS=dttm diff --git a/src/date/dttm/Makefile.am b/src/date/dttm/Makefile.am new file mode 100644 index 0000000..ca80448 --- /dev/null +++ b/src/date/dttm/Makefile.am @@ -0,0 +1,25 @@ +#Generata binary file +lib_LTLIBRARIES = libukui-datesetting.la + +#gcc -wall: displays all the errors and warning information when compiling +#gcc -g: add the debugging code when compiling +COMM_CFS = -Wall -g + +#Add the dependent source file for libukui-datesetting.la +libukui_datesetting_la_SOURCES = kylin-date-interface.c \ + $(NULL) + +#The header files that need to be installed +include_HEADERS= kylin-date-interface.h \ + $(NULL) + +#Additional C compiler flags +libukui_datesetting_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_datesetting_la_LDFLAGS= \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + diff --git a/src/date/dttm/kylin-date-interface.c b/src/date/dttm/kylin-date-interface.c new file mode 100644 index 0000000..ec1b008 --- /dev/null +++ b/src/date/dttm/kylin-date-interface.c @@ -0,0 +1,198 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include "kylin-date-interface.h" +#include + +#define USE_24_FORMAT "use-24h-format" +#define schemaID "org.mate.panel.indicator.calendar" +#define TZ_DATA_FILE "/usr/share/zoneinfo/zone_utc" + +typedef struct _TimeDate TimeDate; +typedef struct _TzDB TzDB; +//typedef struct _TzLocation TzLocation; +typedef struct _TzUTC TzUTC; +TimeDate timedata; + +struct _TzUTC{ + GPtrArray *tz_rtc; + gchar *tz_utc; +}; + +struct _TzDB { + GPtrArray *locations; +}; + + +struct _TimeDate { + TzDB *tzdb; +}; + +//Initialize the time zone database. +TzDB *init_timedb (){ + gchar *tz_data_file; + TzDB *tz_db; + FILE *tzfile; + + char buf[4096]; + + tz_data_file = TZ_DATA_FILE; + + if (!tz_data_file){ + g_warning("Could not get timedb source\n"); + return NULL; + } + tzfile = fopen(tz_data_file, "r"); + if (!tzfile) { + g_warning("Could not open tzfile *%s*\n",tz_data_file); + // g_free(tz_data_file); + return NULL; + } + + tz_db = g_new0(TzDB, 1); + tz_db->locations = g_ptr_array_new(); + + while(fgets(buf, sizeof(buf), tzfile)){ + gchar **tmpstrarr; + TzUTC *loc; + loc = g_new0(TzUTC, 1); + loc->tz_rtc = g_ptr_array_new(); + + g_strchomp(buf); + tmpstrarr = g_strsplit(buf, "\t",2); + gchar ***tmp_rtc = g_strsplit(tmpstrarr[0], " ", 6); + + for(int i =0; i!=6; ++i){ + if(tmp_rtc[i] != NULL){ + g_ptr_array_add (loc->tz_rtc, (gpointer)g_strdup(tmp_rtc[i])); + } + else + break; + } + + loc->tz_utc = g_strdup(tmpstrarr[1]); + + g_ptr_array_add (tz_db->locations, loc); + + g_strfreev(tmp_rtc); + g_strfreev(tmpstrarr); + } + + fclose(tzfile); + return tz_db; +} + +//Modify the time zone +void kylin_date_dt_settz(char * location){ + gchar *rtc; + TzUTC *tmp; + GPtrArray *translate; + timedata.tzdb= init_timedb(); + translate = timedata.tzdb->locations; + + if(!strcmp(getenv("LANG"), "en_US.UTF-8")) + rtc = location; + else{ + for(int i=0; i != timedata.tzdb->locations->len; ++i){ + tmp = g_ptr_array_index(timedata.tzdb->locations, i); + + if(tmp->tz_utc && strcmp(tmp->tz_utc, location) == 0){ + rtc = g_ptr_array_index(tmp->tz_rtc,0); + break; + } + } + } + + GError *error=NULL; + GDBusProxy *proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE,NULL, + "org.freedesktop.timedate1", + "/org/freedesktop/timedate1", + "org.freedesktop.timedate1", + NULL,&error); + if (error !=NULL) { + g_warning("Error :%s\n",error->message); + } + + g_dbus_proxy_call_sync(proxy, "SetTimezone", g_variant_new("(sb)", rtc, TRUE), + G_DBUS_CALL_FLAGS_NONE, -1,NULL, NULL); + + // g_free(location); + return; +} + +//Change the system date and time. +void kylin_date_dt_chgdt(unsigned year,unsigned month,unsigned day, unsigned hour, unsigned minute, unsigned second){ + GDateTime *now; + gint64 newtime; + + if(hour>23) + hour = hour -12; + + now = g_date_time_new_local(year,month,day,hour,minute,(gdouble)second); + newtime = g_date_time_to_unix(now); + + GError *error=NULL; + GDBusProxy *proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE,NULL, "org.freedesktop.timedate1", + "/org/freedesktop/timedate1", + "org.freedesktop.timedate1", + NULL,&error); + if (error !=NULL) { + g_warning("Error :%s\n",error->message); + } + + g_dbus_proxy_call_sync(proxy, "SetTime", g_variant_new("(xbb)", (newtime * G_TIME_SPAN_SECOND), FALSE,TRUE), + G_DBUS_CALL_FLAGS_NONE,-1,NULL,NULL); +} + +//Whether to enable network time synchronization. +void kylin_date_dt_setnetsync(int timesetting) +{ + GError *error=NULL; + GDBusProxy *proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE,NULL, + "org.freedesktop.timedate1", + "/org/freedesktop/timedate1", + "org.freedesktop.timedate1", + NULL,&error); + if (error !=NULL) { + g_warning("Error :%s\n",error->message); + } + + if (timesetting == 0){ + g_dbus_proxy_call_sync(proxy, "SetNTP", g_variant_new("(bb)", FALSE, TRUE), + G_DBUS_CALL_FLAGS_NONE, -1,NULL, NULL); + }else { + g_dbus_proxy_call_sync(proxy, "SetNTP", g_variant_new("(bb)", TRUE, TRUE), + G_DBUS_CALL_FLAGS_NONE, -1,NULL, NULL); + } +} + +//Whether to enable time format. +void kylin_date_dt_sethrfmt(bool value) +{ + GSettings *setting=g_settings_new(schemaID); + g_settings_set_boolean(setting,USE_24_FORMAT,value); + g_object_unref(setting); + g_settings_sync(); +} diff --git a/src/date/dttm/kylin-date-interface.h b/src/date/dttm/kylin-date-interface.h new file mode 100644 index 0000000..d798320 --- /dev/null +++ b/src/date/dttm/kylin-date-interface.h @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C"{ +#endif + +/* + * Modify the time zone. + * @location is the time zone.Referring to the file "/usr/share/zoneinfo/zone_utc". + * e.g. gchar *location="(UTC+08:00) 北京,重庆,香港特别行政区,乌鲁木齐"; + */ +void kylin_date_dt_settz(char *location); + +/* + * Change the system date and time. + * @Parameter represents the date and time you want to set. + */ +void kylin_date_dt_chgdt(unsigned year, + unsigned month, + unsigned day, + unsigned hour, + unsigned minute, + unsigned second); + +/* + * Whether to enable network time synchronization. + * @timesetting can be equal to 1 or 0. + */ +void kylin_date_dt_setnetsync(int timesetting); + +/* + * Whether to enable time format. + */ +void kylin_date_dt_sethrfmt(bool value); + +#ifdef __cplusplus +} +#endif + +#endif + + diff --git a/src/hardware/Makefile.am b/src/hardware/Makefile.am new file mode 100755 index 0000000..62c9212 --- /dev/null +++ b/src/hardware/Makefile.am @@ -0,0 +1 @@ +SUBDIRS=mouse keyboard power touchpad diff --git a/src/hardware/keyboard/Makefile.am b/src/hardware/keyboard/Makefile.am new file mode 100644 index 0000000..2d56e83 --- /dev/null +++ b/src/hardware/keyboard/Makefile.am @@ -0,0 +1,115 @@ +COMM_PRINT= -L$(top_srcdir)/src/common -lukui-print +COMM_GSETTINGS= -L$(top_srcdir)/src/common -lukui-gsettings + +#generate the .c and .h file which used by client and server side by XML file +#$(top_srcdir) represents the top-level directory of the project +GENE_XML = $(top_srcdir)/data/cn.kylinos.xkbgeneral.xml +INTE_XML = $(top_srcdir)/data/cn.kylinos.interface.xml +KEY_XML = $(top_srcdir)/data/cn.kylinos.keyboard.xml + +GENERATED_GENE = xkbgeneral-generated +GENERATED_INTE = interface-generated +GENERATED_KEY = keyboard-generated + +xkbgeneral-generated.h xkbgeneral-generated.c: $(GENE_XML) + gdbus-codegen --interface-prefix cn.kylinos --generate-c-code $(GENERATED_GENE) $(GENE_XML) + +interface-generated.h interface-generated.c: $(INTE_XML) + gdbus-codegen --interface-prefix cn.kylinos. --generate-c-code $(GENERATED_INTE) $(INTE_XML) + +keyboard-generated.h keyboard-generated.c: $(KEY_XML) + gdbus-codegen --interface-prefix cn.kylinos. --generate-c-code $(GENERATED_KEY) $(KEY_XML) + + +#Generata binary file +lib_LTLIBRARIES = libukui-interfaceclient.la libukui-keyboardclient.la + +#gcc -wall: displays all the errors and warning information when compiling +#gcc -g: add the debugging code when compiling +COMM_CFS = -Wall -g + +#The header files that need to be installed +include_HEADERS= kylin-interface-interface.h \ + kylin-keyboard-interface.h \ + $(NULL) + +#Add the dependent source file for libinterfaceclient.la +#interface-generated.c must be front of kylin-interface-interface.c +libukui_interfaceclient_la_SOURCES = interface-generated.c kylin-interface-interface.c \ + $(NULL) + +#Additional C compiler flags +libukui_interfaceclient_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_interfaceclient_la_LDFLAGS= $(COMM_PRINT) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Add the dependent source file for libkeyboardclient.la +#keyboard-generated.c must be front of kylin-keyboard-interface.c +libukui_keyboardclient_la_SOURCES = keyboard-generated.c kylin-keyboard-interface.c \ + $(NULL) + +#Additional C compiler flags +libukui_keyboardclient_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_keyboardclient_la_LDFLAGS= $(COMM_PRINT) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Generata binary file +bin_PROGRAMS =ukui-xkbgeneralserver ukui-interfaceserver ukui-keyboardserver + +#Add the dependent source file for xkbgeneralserver +ukui_xkbgeneralserver_SOURCES = \ + xkbgeneral-generated.h xkbgeneral-generated.c \ + kylin-xkbgeneral-server.c \ + $(NULL) + +#Additional C compiler flags +ukui_xkbgeneralserver_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +ukui_xkbgeneralserver_LDFLAGS= $(COMM_PRINT) $(COMM_GSETTINGS) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Add the dependent source file for interfaceserver +ukui_interfaceserver_SOURCES = \ + interface-generated.h interface-generated.c \ + kylin-interface-server.c \ + $(NULL) + +#Additional C compiler flags +ukui_interfaceserver_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +ukui_interfaceserver_LDFLAGS= $(COMM_PRINT) $(COMM_GSETTINGS) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Add the dependent source file for keyboardserver +ukui_keyboardserver_SOURCES = \ + keyboard-generated.h keyboard-generated.c \ + kylin-keyboard-server.c \ + $(NULL) + +#Additional C compiler flags +ukui_keyboardserver_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +ukui_keyboardserver_LDFLAGS= $(COMM_PRINT) $(COMM_GSETTINGS) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) diff --git a/src/hardware/keyboard/interface-dbus.h b/src/hardware/keyboard/interface-dbus.h new file mode 100644 index 0000000..0ad3d1d --- /dev/null +++ b/src/hardware/keyboard/interface-dbus.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 /* Bus define */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define INTERFACE_BUS G_BUS_TYPE_SESSION +#define INTERFACE_BUS_NAME "cn.kylinos.interface" +#define INTERFACE_OBJECT_PATH "/cn/kylinos/interface" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/hardware/keyboard/interface-generated.c b/src/hardware/keyboard/interface-generated.c new file mode 100644 index 0000000..0ad29d5 --- /dev/null +++ b/src/hardware/keyboard/interface-generated.c @@ -0,0 +1,2061 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#ifdef G_OS_UNIX +# include +#endif + +typedef struct +{ + GDBusArgInfo parent_struct; + gboolean use_gvariant; +} _ExtendedGDBusArgInfo; + +typedef struct +{ + GDBusMethodInfo parent_struct; + const gchar *signal_name; + gboolean pass_fdlist; +} _ExtendedGDBusMethodInfo; + +typedef struct +{ + GDBusSignalInfo parent_struct; + const gchar *signal_name; +} _ExtendedGDBusSignalInfo; + +typedef struct +{ + GDBusPropertyInfo parent_struct; + const gchar *hyphen_name; + guint use_gvariant : 1; + guint emits_changed_signal : 1; +} _ExtendedGDBusPropertyInfo; + +typedef struct +{ + GDBusInterfaceInfo parent_struct; + const gchar *hyphen_name; +} _ExtendedGDBusInterfaceInfo; + +typedef struct +{ + const _ExtendedGDBusPropertyInfo *info; + guint prop_id; + GValue orig_value; /* the value before the change */ +} ChangedProperty; + +static void +_changed_property_free (ChangedProperty *data) +{ + g_value_unset (&data->orig_value); + g_free (data); +} + +static gboolean +_g_strv_equal0 (gchar **a, gchar **b) +{ + gboolean ret = FALSE; + guint n; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + if (g_strv_length (a) != g_strv_length (b)) + goto out; + for (n = 0; a[n] != NULL; n++) + if (g_strcmp0 (a[n], b[n]) != 0) + goto out; + ret = TRUE; +out: + return ret; +} + +static gboolean +_g_variant_equal0 (GVariant *a, GVariant *b) +{ + gboolean ret = FALSE; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + ret = g_variant_equal (a, b); +out: + return ret; +} + +G_GNUC_UNUSED static gboolean +_g_value_equal (const GValue *a, const GValue *b) +{ + gboolean ret = FALSE; + g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); + switch (G_VALUE_TYPE (a)) + { + case G_TYPE_BOOLEAN: + ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); + break; + case G_TYPE_UCHAR: + ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); + break; + case G_TYPE_INT: + ret = (g_value_get_int (a) == g_value_get_int (b)); + break; + case G_TYPE_UINT: + ret = (g_value_get_uint (a) == g_value_get_uint (b)); + break; + case G_TYPE_INT64: + ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); + break; + case G_TYPE_UINT64: + ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); + break; + case G_TYPE_DOUBLE: + { + /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ + gdouble da = g_value_get_double (a); + gdouble db = g_value_get_double (b); + ret = memcmp (&da, &db, sizeof (gdouble)) == 0; + } + break; + case G_TYPE_STRING: + ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); + break; + case G_TYPE_VARIANT: + ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); + break; + default: + if (G_VALUE_TYPE (a) == G_TYPE_STRV) + ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); + else + g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); + break; + } + return ret; +} + +/* ------------------------------------------------------------------------ + * Code for interface cn.kylinos.interface + * ------------------------------------------------------------------------ + */ + +/** + * SECTION:Interface + * @title: Interface + * @short_description: Generated C code for the cn.kylinos.interface D-Bus interface + * + * This section contains code for working with the cn.kylinos.interface D-Bus interface in C. + */ + +/* ---- Introspection data for cn.kylinos.interface ---- */ + +static const _ExtendedGDBusArgInfo _interface_method_info_transfer_bool_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(sb)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _interface_method_info_transfer_bool_value_IN_ARG_pointers[] = +{ + &_interface_method_info_transfer_bool_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _interface_method_info_transfer_bool_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _interface_method_info_transfer_bool_value_OUT_ARG_pointers[] = +{ + &_interface_method_info_transfer_bool_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _interface_method_info_transfer_bool_value = +{ + { + -1, + (gchar *) "TransferBoolValue", + (GDBusArgInfo **) &_interface_method_info_transfer_bool_value_IN_ARG_pointers, + (GDBusArgInfo **) &_interface_method_info_transfer_bool_value_OUT_ARG_pointers, + NULL + }, + "handle-transfer-bool-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _interface_method_info_get_bool_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "s", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _interface_method_info_get_bool_value_IN_ARG_pointers[] = +{ + &_interface_method_info_get_bool_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _interface_method_info_get_bool_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _interface_method_info_get_bool_value_OUT_ARG_pointers[] = +{ + &_interface_method_info_get_bool_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _interface_method_info_get_bool_value = +{ + { + -1, + (gchar *) "GetBoolValue", + (GDBusArgInfo **) &_interface_method_info_get_bool_value_IN_ARG_pointers, + (GDBusArgInfo **) &_interface_method_info_get_bool_value_OUT_ARG_pointers, + NULL + }, + "handle-get-bool-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _interface_method_info_transfer_int_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(si)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _interface_method_info_transfer_int_value_IN_ARG_pointers[] = +{ + &_interface_method_info_transfer_int_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _interface_method_info_transfer_int_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _interface_method_info_transfer_int_value_OUT_ARG_pointers[] = +{ + &_interface_method_info_transfer_int_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _interface_method_info_transfer_int_value = +{ + { + -1, + (gchar *) "TransferIntValue", + (GDBusArgInfo **) &_interface_method_info_transfer_int_value_IN_ARG_pointers, + (GDBusArgInfo **) &_interface_method_info_transfer_int_value_OUT_ARG_pointers, + NULL + }, + "handle-transfer-int-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _interface_method_info_get_int_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "s", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _interface_method_info_get_int_value_IN_ARG_pointers[] = +{ + &_interface_method_info_get_int_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _interface_method_info_get_int_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "i", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _interface_method_info_get_int_value_OUT_ARG_pointers[] = +{ + &_interface_method_info_get_int_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _interface_method_info_get_int_value = +{ + { + -1, + (gchar *) "GetIntValue", + (GDBusArgInfo **) &_interface_method_info_get_int_value_IN_ARG_pointers, + (GDBusArgInfo **) &_interface_method_info_get_int_value_OUT_ARG_pointers, + NULL + }, + "handle-get-int-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _interface_method_info_transfer_string_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(ss)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _interface_method_info_transfer_string_value_IN_ARG_pointers[] = +{ + &_interface_method_info_transfer_string_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _interface_method_info_transfer_string_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _interface_method_info_transfer_string_value_OUT_ARG_pointers[] = +{ + &_interface_method_info_transfer_string_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _interface_method_info_transfer_string_value = +{ + { + -1, + (gchar *) "TransferStringValue", + (GDBusArgInfo **) &_interface_method_info_transfer_string_value_IN_ARG_pointers, + (GDBusArgInfo **) &_interface_method_info_transfer_string_value_OUT_ARG_pointers, + NULL + }, + "handle-transfer-string-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _interface_method_info_get_string_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "s", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _interface_method_info_get_string_value_IN_ARG_pointers[] = +{ + &_interface_method_info_get_string_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _interface_method_info_get_string_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "s", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _interface_method_info_get_string_value_OUT_ARG_pointers[] = +{ + &_interface_method_info_get_string_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _interface_method_info_get_string_value = +{ + { + -1, + (gchar *) "GetStringValue", + (GDBusArgInfo **) &_interface_method_info_get_string_value_IN_ARG_pointers, + (GDBusArgInfo **) &_interface_method_info_get_string_value_OUT_ARG_pointers, + NULL + }, + "handle-get-string-value", + FALSE +}; + +static const GDBusMethodInfo * const _interface_method_info_pointers[] = +{ + &_interface_method_info_transfer_bool_value.parent_struct, + &_interface_method_info_get_bool_value.parent_struct, + &_interface_method_info_transfer_int_value.parent_struct, + &_interface_method_info_get_int_value.parent_struct, + &_interface_method_info_transfer_string_value.parent_struct, + &_interface_method_info_get_string_value.parent_struct, + NULL +}; + +static const _ExtendedGDBusInterfaceInfo _interface_interface_info = +{ + { + -1, + (gchar *) "cn.kylinos.interface", + (GDBusMethodInfo **) &_interface_method_info_pointers, + NULL, + NULL, + NULL + }, + "interface", +}; + + +/** + * interface_interface_info: + * + * Gets a machine-readable description of the cn.kylinos.interface D-Bus interface. + * + * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. + */ +GDBusInterfaceInfo * +interface_interface_info (void) +{ + return (GDBusInterfaceInfo *) &_interface_interface_info.parent_struct; +} + +/** + * interface_override_properties: + * @klass: The class structure for a #GObject derived class. + * @property_id_begin: The property id to assign to the first overridden property. + * + * Overrides all #GObject properties in the #Interface interface for a concrete class. + * The properties are overridden in the order they are defined. + * + * Returns: The last property id. + */ +guint +interface_override_properties (GObjectClass *klass, guint property_id_begin) +{ + return property_id_begin - 1; +} + + + +/** + * Interface: + * + * Abstract interface type for the D-Bus interface cn.kylinos.interface. + */ + +/** + * InterfaceIface: + * @parent_iface: The parent interface. + * @handle_get_bool_value: Handler for the #Interface::handle-get-bool-value signal. + * @handle_get_int_value: Handler for the #Interface::handle-get-int-value signal. + * @handle_get_string_value: Handler for the #Interface::handle-get-string-value signal. + * @handle_transfer_bool_value: Handler for the #Interface::handle-transfer-bool-value signal. + * @handle_transfer_int_value: Handler for the #Interface::handle-transfer-int-value signal. + * @handle_transfer_string_value: Handler for the #Interface::handle-transfer-string-value signal. + * + * Virtual table for the D-Bus interface cn.kylinos.interface. + */ + +typedef InterfaceIface InterfaceInterface; +G_DEFINE_INTERFACE (Interface, interface, G_TYPE_OBJECT) + +static void +interface_default_init (InterfaceIface *iface) +{ + /* GObject signals for incoming D-Bus method calls: */ + /** + * Interface::handle-transfer-bool-value: + * @object: A #Interface. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferBoolValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call interface_complete_transfer_bool_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-bool-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (InterfaceIface, handle_transfer_bool_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Interface::handle-get-bool-value: + * @object: A #Interface. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the GetBoolValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call interface_complete_get_bool_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-get-bool-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (InterfaceIface, handle_get_bool_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_STRING); + + /** + * Interface::handle-transfer-int-value: + * @object: A #Interface. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferIntValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call interface_complete_transfer_int_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-int-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (InterfaceIface, handle_transfer_int_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Interface::handle-get-int-value: + * @object: A #Interface. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the GetIntValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call interface_complete_get_int_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-get-int-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (InterfaceIface, handle_get_int_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_STRING); + + /** + * Interface::handle-transfer-string-value: + * @object: A #Interface. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferStringValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call interface_complete_transfer_string_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-string-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (InterfaceIface, handle_transfer_string_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Interface::handle-get-string-value: + * @object: A #Interface. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the GetStringValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call interface_complete_get_string_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-get-string-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (InterfaceIface, handle_get_string_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_STRING); + +} + +/** + * interface_call_transfer_bool_value: + * @proxy: A #InterfaceProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferBoolValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call interface_call_transfer_bool_value_finish() to get the result of the operation. + * + * See interface_call_transfer_bool_value_sync() for the synchronous, blocking version of this method. + */ +void +interface_call_transfer_bool_value ( + Interface *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * interface_call_transfer_bool_value_finish: + * @proxy: A #InterfaceProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to interface_call_transfer_bool_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with interface_call_transfer_bool_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +interface_call_transfer_bool_value_finish ( + Interface *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * interface_call_transfer_bool_value_sync: + * @proxy: A #InterfaceProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferBoolValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See interface_call_transfer_bool_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +interface_call_transfer_bool_value_sync ( + Interface *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * interface_call_get_bool_value: + * @proxy: A #InterfaceProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the GetBoolValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call interface_call_get_bool_value_finish() to get the result of the operation. + * + * See interface_call_get_bool_value_sync() for the synchronous, blocking version of this method. + */ +void +interface_call_get_bool_value ( + Interface *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "GetBoolValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * interface_call_get_bool_value_finish: + * @proxy: A #InterfaceProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to interface_call_get_bool_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with interface_call_get_bool_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +interface_call_get_bool_value_finish ( + Interface *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * interface_call_get_bool_value_sync: + * @proxy: A #InterfaceProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the GetBoolValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See interface_call_get_bool_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +interface_call_get_bool_value_sync ( + Interface *proxy, + const gchar *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "GetBoolValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * interface_call_transfer_int_value: + * @proxy: A #InterfaceProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferIntValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call interface_call_transfer_int_value_finish() to get the result of the operation. + * + * See interface_call_transfer_int_value_sync() for the synchronous, blocking version of this method. + */ +void +interface_call_transfer_int_value ( + Interface *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * interface_call_transfer_int_value_finish: + * @proxy: A #InterfaceProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to interface_call_transfer_int_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with interface_call_transfer_int_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +interface_call_transfer_int_value_finish ( + Interface *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * interface_call_transfer_int_value_sync: + * @proxy: A #InterfaceProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferIntValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See interface_call_transfer_int_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +interface_call_transfer_int_value_sync ( + Interface *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * interface_call_get_int_value: + * @proxy: A #InterfaceProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the GetIntValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call interface_call_get_int_value_finish() to get the result of the operation. + * + * See interface_call_get_int_value_sync() for the synchronous, blocking version of this method. + */ +void +interface_call_get_int_value ( + Interface *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "GetIntValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * interface_call_get_int_value_finish: + * @proxy: A #InterfaceProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to interface_call_get_int_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with interface_call_get_int_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +interface_call_get_int_value_finish ( + Interface *proxy, + gint *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(i)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * interface_call_get_int_value_sync: + * @proxy: A #InterfaceProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the GetIntValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See interface_call_get_int_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +interface_call_get_int_value_sync ( + Interface *proxy, + const gchar *arg_InArg, + gint *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "GetIntValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(i)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * interface_call_transfer_string_value: + * @proxy: A #InterfaceProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferStringValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call interface_call_transfer_string_value_finish() to get the result of the operation. + * + * See interface_call_transfer_string_value_sync() for the synchronous, blocking version of this method. + */ +void +interface_call_transfer_string_value ( + Interface *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferStringValue", + g_variant_new ("(@(ss))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * interface_call_transfer_string_value_finish: + * @proxy: A #InterfaceProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to interface_call_transfer_string_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with interface_call_transfer_string_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +interface_call_transfer_string_value_finish ( + Interface *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * interface_call_transfer_string_value_sync: + * @proxy: A #InterfaceProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferStringValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See interface_call_transfer_string_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +interface_call_transfer_string_value_sync ( + Interface *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferStringValue", + g_variant_new ("(@(ss))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * interface_call_get_string_value: + * @proxy: A #InterfaceProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the GetStringValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call interface_call_get_string_value_finish() to get the result of the operation. + * + * See interface_call_get_string_value_sync() for the synchronous, blocking version of this method. + */ +void +interface_call_get_string_value ( + Interface *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "GetStringValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * interface_call_get_string_value_finish: + * @proxy: A #InterfaceProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to interface_call_get_string_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with interface_call_get_string_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +interface_call_get_string_value_finish ( + Interface *proxy, + gchar **out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(s)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * interface_call_get_string_value_sync: + * @proxy: A #InterfaceProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the GetStringValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See interface_call_get_string_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +interface_call_get_string_value_sync ( + Interface *proxy, + const gchar *arg_InArg, + gchar **out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "GetStringValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(s)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * interface_complete_transfer_bool_value: + * @object: A #Interface. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the TransferBoolValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +interface_complete_transfer_bool_value ( + Interface *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/** + * interface_complete_get_bool_value: + * @object: A #Interface. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the GetBoolValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +interface_complete_get_bool_value ( + Interface *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/** + * interface_complete_transfer_int_value: + * @object: A #Interface. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the TransferIntValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +interface_complete_transfer_int_value ( + Interface *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/** + * interface_complete_get_int_value: + * @object: A #Interface. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the GetIntValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +interface_complete_get_int_value ( + Interface *object, + GDBusMethodInvocation *invocation, + gint OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(i)", + OutArg)); +} + +/** + * interface_complete_transfer_string_value: + * @object: A #Interface. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the TransferStringValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +interface_complete_transfer_string_value ( + Interface *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/** + * interface_complete_get_string_value: + * @object: A #Interface. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the GetStringValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +interface_complete_get_string_value ( + Interface *object, + GDBusMethodInvocation *invocation, + const gchar *OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(s)", + OutArg)); +} + +/* ------------------------------------------------------------------------ */ + +/** + * InterfaceProxy: + * + * The #InterfaceProxy structure contains only private data and should only be accessed using the provided API. + */ + +/** + * InterfaceProxyClass: + * @parent_class: The parent class. + * + * Class structure for #InterfaceProxy. + */ + +struct _InterfaceProxyPrivate +{ + GData *qdata; +}; + +static void interface_proxy_iface_init (InterfaceIface *iface); + +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (InterfaceProxy, interface_proxy, G_TYPE_DBUS_PROXY, + G_ADD_PRIVATE (InterfaceProxy) + G_IMPLEMENT_INTERFACE (TYPE_INTERFACE, interface_proxy_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (InterfaceProxy, interface_proxy, G_TYPE_DBUS_PROXY, + G_IMPLEMENT_INTERFACE (TYPE_INTERFACE, interface_proxy_iface_init)) + +#endif +static void +interface_proxy_finalize (GObject *object) +{ + InterfaceProxy *proxy = INTERFACE_PROXY (object); + g_datalist_clear (&proxy->priv->qdata); + G_OBJECT_CLASS (interface_proxy_parent_class)->finalize (object); +} + +static void +interface_proxy_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +interface_proxy_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +interface_proxy_g_signal (GDBusProxy *proxy, + const gchar *sender_name G_GNUC_UNUSED, + const gchar *signal_name, + GVariant *parameters) +{ + _ExtendedGDBusSignalInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + gsize n; + guint signal_id; + info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_interface_interface_info.parent_struct, signal_name); + if (info == NULL) + return; + num_params = g_variant_n_children (parameters); + paramv = g_new0 (GValue, num_params + 1); + g_value_init (¶mv[0], TYPE_INTERFACE); + g_value_set_object (¶mv[0], proxy); + g_variant_iter_init (&iter, parameters); + n = 1; + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_INTERFACE); + g_signal_emitv (paramv, signal_id, 0, NULL); + for (n = 0; n < num_params + 1; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static void +interface_proxy_g_properties_changed (GDBusProxy *_proxy, + GVariant *changed_properties, + const gchar *const *invalidated_properties) +{ + InterfaceProxy *proxy = INTERFACE_PROXY (_proxy); + guint n; + const gchar *key; + GVariantIter *iter; + _ExtendedGDBusPropertyInfo *info; + g_variant_get (changed_properties, "a{sv}", &iter); + while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_interface_interface_info.parent_struct, key); + g_datalist_remove_data (&proxy->priv->qdata, key); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } + g_variant_iter_free (iter); + for (n = 0; invalidated_properties[n] != NULL; n++) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_interface_interface_info.parent_struct, invalidated_properties[n]); + g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } +} + +static void +interface_proxy_init (InterfaceProxy *proxy) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + proxy->priv = interface_proxy_get_instance_private (proxy); +#else + proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, TYPE_INTERFACE_PROXY, InterfaceProxyPrivate); +#endif + + g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), interface_interface_info ()); +} + +static void +interface_proxy_class_init (InterfaceProxyClass *klass) +{ + GObjectClass *gobject_class; + GDBusProxyClass *proxy_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = interface_proxy_finalize; + gobject_class->get_property = interface_proxy_get_property; + gobject_class->set_property = interface_proxy_set_property; + + proxy_class = G_DBUS_PROXY_CLASS (klass); + proxy_class->g_signal = interface_proxy_g_signal; + proxy_class->g_properties_changed = interface_proxy_g_properties_changed; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (InterfaceProxyPrivate)); +#endif +} + +static void +interface_proxy_iface_init (InterfaceIface *iface) +{ +} + +/** + * interface_proxy_new: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Asynchronously creates a proxy for the D-Bus interface cn.kylinos.interface. See g_dbus_proxy_new() for more details. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call interface_proxy_new_finish() to get the result of the operation. + * + * See interface_proxy_new_sync() for the synchronous, blocking version of this constructor. + */ +void +interface_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_INTERFACE_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.interface", NULL); +} + +/** + * interface_proxy_new_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to interface_proxy_new(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with interface_proxy_new(). + * + * Returns: (transfer full) (type InterfaceProxy): The constructed proxy object or %NULL if @error is set. + */ +Interface * +interface_proxy_new_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return INTERFACE (ret); + else + return NULL; +} + +/** + * interface_proxy_new_sync: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Synchronously creates a proxy for the D-Bus interface cn.kylinos.interface. See g_dbus_proxy_new_sync() for more details. + * + * The calling thread is blocked until a reply is received. + * + * See interface_proxy_new() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type InterfaceProxy): The constructed proxy object or %NULL if @error is set. + */ +Interface * +interface_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_INTERFACE_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.interface", NULL); + if (ret != NULL) + return INTERFACE (ret); + else + return NULL; +} + + +/** + * interface_proxy_new_for_bus: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Like interface_proxy_new() but takes a #GBusType instead of a #GDBusConnection. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call interface_proxy_new_for_bus_finish() to get the result of the operation. + * + * See interface_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. + */ +void +interface_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_INTERFACE_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.interface", NULL); +} + +/** + * interface_proxy_new_for_bus_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to interface_proxy_new_for_bus(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with interface_proxy_new_for_bus(). + * + * Returns: (transfer full) (type InterfaceProxy): The constructed proxy object or %NULL if @error is set. + */ +Interface * +interface_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return INTERFACE (ret); + else + return NULL; +} + +/** + * interface_proxy_new_for_bus_sync: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Like interface_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. + * + * The calling thread is blocked until a reply is received. + * + * See interface_proxy_new_for_bus() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type InterfaceProxy): The constructed proxy object or %NULL if @error is set. + */ +Interface * +interface_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_INTERFACE_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.interface", NULL); + if (ret != NULL) + return INTERFACE (ret); + else + return NULL; +} + + +/* ------------------------------------------------------------------------ */ + +/** + * InterfaceSkeleton: + * + * The #InterfaceSkeleton structure contains only private data and should only be accessed using the provided API. + */ + +/** + * InterfaceSkeletonClass: + * @parent_class: The parent class. + * + * Class structure for #InterfaceSkeleton. + */ + +struct _InterfaceSkeletonPrivate +{ + GValue *properties; + GList *changed_properties; + GSource *changed_properties_idle_source; + GMainContext *context; + GMutex lock; +}; + +static void +_interface_skeleton_handle_method_call ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name, + const gchar *method_name, + GVariant *parameters, + GDBusMethodInvocation *invocation, + gpointer user_data) +{ + InterfaceSkeleton *skeleton = INTERFACE_SKELETON (user_data); + _ExtendedGDBusMethodInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + guint num_extra; + gsize n; + guint signal_id; + GValue return_value = G_VALUE_INIT; + info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); + g_assert (info != NULL); + num_params = g_variant_n_children (parameters); + num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); + n = 0; + g_value_init (¶mv[n], TYPE_INTERFACE); + g_value_set_object (¶mv[n++], skeleton); + g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); + g_value_set_object (¶mv[n++], invocation); + if (info->pass_fdlist) + { +#ifdef G_OS_UNIX + g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); + g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); +#else + g_assert_not_reached (); +#endif + } + g_variant_iter_init (&iter, parameters); + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_INTERFACE); + g_value_init (&return_value, G_TYPE_BOOLEAN); + g_signal_emitv (paramv, signal_id, 0, &return_value); + if (!g_value_get_boolean (&return_value)) + g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); + g_value_unset (&return_value); + for (n = 0; n < num_params + num_extra; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static GVariant * +_interface_skeleton_handle_get_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GError **error, + gpointer user_data) +{ + InterfaceSkeleton *skeleton = INTERFACE_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + GVariant *ret; + ret = NULL; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_interface_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + g_value_init (&value, pspec->value_type); + g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); + ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); + g_value_unset (&value); + } + return ret; +} + +static gboolean +_interface_skeleton_handle_set_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GVariant *variant, + GError **error, + gpointer user_data) +{ + InterfaceSkeleton *skeleton = INTERFACE_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + gboolean ret; + ret = FALSE; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_interface_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + if (info->use_gvariant) + g_value_set_variant (&value, variant); + else + g_dbus_gvariant_to_gvalue (variant, &value); + g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); + g_value_unset (&value); + ret = TRUE; + } + return ret; +} + +static const GDBusInterfaceVTable _interface_skeleton_vtable = +{ + _interface_skeleton_handle_method_call, + _interface_skeleton_handle_get_property, + _interface_skeleton_handle_set_property, + {NULL} +}; + +static GDBusInterfaceInfo * +interface_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return interface_interface_info (); +} + +static GDBusInterfaceVTable * +interface_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return (GDBusInterfaceVTable *) &_interface_skeleton_vtable; +} + +static GVariant * +interface_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) +{ + InterfaceSkeleton *skeleton = INTERFACE_SKELETON (_skeleton); + + GVariantBuilder builder; + guint n; + g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); + if (_interface_interface_info.parent_struct.properties == NULL) + goto out; + for (n = 0; _interface_interface_info.parent_struct.properties[n] != NULL; n++) + { + GDBusPropertyInfo *info = _interface_interface_info.parent_struct.properties[n]; + if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) + { + GVariant *value; + value = _interface_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "cn.kylinos.interface", info->name, NULL, skeleton); + if (value != NULL) + { + g_variant_take_ref (value); + g_variant_builder_add (&builder, "{sv}", info->name, value); + g_variant_unref (value); + } + } + } +out: + return g_variant_builder_end (&builder); +} + +static void +interface_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) +{ +} + +static void interface_skeleton_iface_init (InterfaceIface *iface); +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (InterfaceSkeleton, interface_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_ADD_PRIVATE (InterfaceSkeleton) + G_IMPLEMENT_INTERFACE (TYPE_INTERFACE, interface_skeleton_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (InterfaceSkeleton, interface_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_IMPLEMENT_INTERFACE (TYPE_INTERFACE, interface_skeleton_iface_init)) + +#endif +static void +interface_skeleton_finalize (GObject *object) +{ + InterfaceSkeleton *skeleton = INTERFACE_SKELETON (object); + g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); + if (skeleton->priv->changed_properties_idle_source != NULL) + g_source_destroy (skeleton->priv->changed_properties_idle_source); + g_main_context_unref (skeleton->priv->context); + g_mutex_clear (&skeleton->priv->lock); + G_OBJECT_CLASS (interface_skeleton_parent_class)->finalize (object); +} + +static void +interface_skeleton_init (InterfaceSkeleton *skeleton) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + skeleton->priv = interface_skeleton_get_instance_private (skeleton); +#else + skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_INTERFACE_SKELETON, InterfaceSkeletonPrivate); +#endif + + g_mutex_init (&skeleton->priv->lock); + skeleton->priv->context = g_main_context_ref_thread_default (); +} + +static void +interface_skeleton_class_init (InterfaceSkeletonClass *klass) +{ + GObjectClass *gobject_class; + GDBusInterfaceSkeletonClass *skeleton_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = interface_skeleton_finalize; + + skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); + skeleton_class->get_info = interface_skeleton_dbus_interface_get_info; + skeleton_class->get_properties = interface_skeleton_dbus_interface_get_properties; + skeleton_class->flush = interface_skeleton_dbus_interface_flush; + skeleton_class->get_vtable = interface_skeleton_dbus_interface_get_vtable; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (InterfaceSkeletonPrivate)); +#endif +} + +static void +interface_skeleton_iface_init (InterfaceIface *iface) +{ +} + +/** + * interface_skeleton_new: + * + * Creates a skeleton object for the D-Bus interface cn.kylinos.interface. + * + * Returns: (transfer full) (type InterfaceSkeleton): The skeleton object. + */ +Interface * +interface_skeleton_new (void) +{ + return INTERFACE (g_object_new (TYPE_INTERFACE_SKELETON, NULL)); +} + diff --git a/src/hardware/keyboard/interface-generated.h b/src/hardware/keyboard/interface-generated.h new file mode 100644 index 0000000..ea8cc5b --- /dev/null +++ b/src/hardware/keyboard/interface-generated.h @@ -0,0 +1,343 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +G_BEGIN_DECLS + + +/* ------------------------------------------------------------------------ */ +/* Declarations for cn.kylinos.interface */ + +#define TYPE_INTERFACE (interface_get_type ()) +#define INTERFACE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_INTERFACE, Interface)) +#define IS_INTERFACE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_INTERFACE)) +#define INTERFACE_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), TYPE_INTERFACE, InterfaceIface)) + +struct _Interface; +typedef struct _Interface Interface; +typedef struct _InterfaceIface InterfaceIface; + +struct _InterfaceIface +{ + GTypeInterface parent_iface; + + gboolean (*handle_get_bool_value) ( + Interface *object, + GDBusMethodInvocation *invocation, + const gchar *arg_InArg); + + gboolean (*handle_get_int_value) ( + Interface *object, + GDBusMethodInvocation *invocation, + const gchar *arg_InArg); + + gboolean (*handle_get_string_value) ( + Interface *object, + GDBusMethodInvocation *invocation, + const gchar *arg_InArg); + + gboolean (*handle_transfer_bool_value) ( + Interface *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + + gboolean (*handle_transfer_int_value) ( + Interface *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + + gboolean (*handle_transfer_string_value) ( + Interface *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + +}; + +GType interface_get_type (void) G_GNUC_CONST; + +GDBusInterfaceInfo *interface_interface_info (void); +guint interface_override_properties (GObjectClass *klass, guint property_id_begin); + + +/* D-Bus method call completion functions: */ +void interface_complete_transfer_bool_value ( + Interface *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + +void interface_complete_get_bool_value ( + Interface *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + +void interface_complete_transfer_int_value ( + Interface *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + +void interface_complete_get_int_value ( + Interface *object, + GDBusMethodInvocation *invocation, + gint OutArg); + +void interface_complete_transfer_string_value ( + Interface *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + +void interface_complete_get_string_value ( + Interface *object, + GDBusMethodInvocation *invocation, + const gchar *OutArg); + + + +/* D-Bus method calls: */ +void interface_call_transfer_bool_value ( + Interface *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean interface_call_transfer_bool_value_finish ( + Interface *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean interface_call_transfer_bool_value_sync ( + Interface *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + +void interface_call_get_bool_value ( + Interface *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean interface_call_get_bool_value_finish ( + Interface *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean interface_call_get_bool_value_sync ( + Interface *proxy, + const gchar *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + +void interface_call_transfer_int_value ( + Interface *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean interface_call_transfer_int_value_finish ( + Interface *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean interface_call_transfer_int_value_sync ( + Interface *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + +void interface_call_get_int_value ( + Interface *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean interface_call_get_int_value_finish ( + Interface *proxy, + gint *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean interface_call_get_int_value_sync ( + Interface *proxy, + const gchar *arg_InArg, + gint *out_OutArg, + GCancellable *cancellable, + GError **error); + +void interface_call_transfer_string_value ( + Interface *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean interface_call_transfer_string_value_finish ( + Interface *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean interface_call_transfer_string_value_sync ( + Interface *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + +void interface_call_get_string_value ( + Interface *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean interface_call_get_string_value_finish ( + Interface *proxy, + gchar **out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean interface_call_get_string_value_sync ( + Interface *proxy, + const gchar *arg_InArg, + gchar **out_OutArg, + GCancellable *cancellable, + GError **error); + + + +/* ---- */ + +#define TYPE_INTERFACE_PROXY (interface_proxy_get_type ()) +#define INTERFACE_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_INTERFACE_PROXY, InterfaceProxy)) +#define INTERFACE_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_INTERFACE_PROXY, InterfaceProxyClass)) +#define INTERFACE_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_INTERFACE_PROXY, InterfaceProxyClass)) +#define IS_INTERFACE_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_INTERFACE_PROXY)) +#define IS_INTERFACE_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_INTERFACE_PROXY)) + +typedef struct _InterfaceProxy InterfaceProxy; +typedef struct _InterfaceProxyClass InterfaceProxyClass; +typedef struct _InterfaceProxyPrivate InterfaceProxyPrivate; + +struct _InterfaceProxy +{ + /*< private >*/ + GDBusProxy parent_instance; + InterfaceProxyPrivate *priv; +}; + +struct _InterfaceProxyClass +{ + GDBusProxyClass parent_class; +}; + +GType interface_proxy_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (InterfaceProxy, g_object_unref) +#endif + +void interface_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Interface *interface_proxy_new_finish ( + GAsyncResult *res, + GError **error); +Interface *interface_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + +void interface_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Interface *interface_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error); +Interface *interface_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + + +/* ---- */ + +#define TYPE_INTERFACE_SKELETON (interface_skeleton_get_type ()) +#define INTERFACE_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_INTERFACE_SKELETON, InterfaceSkeleton)) +#define INTERFACE_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_INTERFACE_SKELETON, InterfaceSkeletonClass)) +#define INTERFACE_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_INTERFACE_SKELETON, InterfaceSkeletonClass)) +#define IS_INTERFACE_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_INTERFACE_SKELETON)) +#define IS_INTERFACE_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_INTERFACE_SKELETON)) + +typedef struct _InterfaceSkeleton InterfaceSkeleton; +typedef struct _InterfaceSkeletonClass InterfaceSkeletonClass; +typedef struct _InterfaceSkeletonPrivate InterfaceSkeletonPrivate; + +struct _InterfaceSkeleton +{ + /*< private >*/ + GDBusInterfaceSkeleton parent_instance; + InterfaceSkeletonPrivate *priv; +}; + +struct _InterfaceSkeletonClass +{ + GDBusInterfaceSkeletonClass parent_class; +}; + +GType interface_skeleton_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (InterfaceSkeleton, g_object_unref) +#endif + +Interface *interface_skeleton_new (void); + + +G_END_DECLS + +#endif /* __INTERFACE_GENERATED_H__ */ diff --git a/src/hardware/keyboard/keyboard-dbus.h b/src/hardware/keyboard/keyboard-dbus.h new file mode 100644 index 0000000..7e05c1d --- /dev/null +++ b/src/hardware/keyboard/keyboard-dbus.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 /* Bus define */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define KEYBOARD_BUS G_BUS_TYPE_SESSION +#define KEYBOARD_BUS_NAME "cn.kylinos.keyboard" +#define KEYBOARD_OBJECT_PATH "/cn/kylinos/keyboard" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/hardware/keyboard/keyboard-generated.c b/src/hardware/keyboard/keyboard-generated.c new file mode 100644 index 0000000..fc0a892 --- /dev/null +++ b/src/hardware/keyboard/keyboard-generated.c @@ -0,0 +1,1667 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#ifdef G_OS_UNIX +# include +#endif + +typedef struct +{ + GDBusArgInfo parent_struct; + gboolean use_gvariant; +} _ExtendedGDBusArgInfo; + +typedef struct +{ + GDBusMethodInfo parent_struct; + const gchar *signal_name; + gboolean pass_fdlist; +} _ExtendedGDBusMethodInfo; + +typedef struct +{ + GDBusSignalInfo parent_struct; + const gchar *signal_name; +} _ExtendedGDBusSignalInfo; + +typedef struct +{ + GDBusPropertyInfo parent_struct; + const gchar *hyphen_name; + guint use_gvariant : 1; + guint emits_changed_signal : 1; +} _ExtendedGDBusPropertyInfo; + +typedef struct +{ + GDBusInterfaceInfo parent_struct; + const gchar *hyphen_name; +} _ExtendedGDBusInterfaceInfo; + +typedef struct +{ + const _ExtendedGDBusPropertyInfo *info; + guint prop_id; + GValue orig_value; /* the value before the change */ +} ChangedProperty; + +static void +_changed_property_free (ChangedProperty *data) +{ + g_value_unset (&data->orig_value); + g_free (data); +} + +static gboolean +_g_strv_equal0 (gchar **a, gchar **b) +{ + gboolean ret = FALSE; + guint n; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + if (g_strv_length (a) != g_strv_length (b)) + goto out; + for (n = 0; a[n] != NULL; n++) + if (g_strcmp0 (a[n], b[n]) != 0) + goto out; + ret = TRUE; +out: + return ret; +} + +static gboolean +_g_variant_equal0 (GVariant *a, GVariant *b) +{ + gboolean ret = FALSE; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + ret = g_variant_equal (a, b); +out: + return ret; +} + +G_GNUC_UNUSED static gboolean +_g_value_equal (const GValue *a, const GValue *b) +{ + gboolean ret = FALSE; + g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); + switch (G_VALUE_TYPE (a)) + { + case G_TYPE_BOOLEAN: + ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); + break; + case G_TYPE_UCHAR: + ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); + break; + case G_TYPE_INT: + ret = (g_value_get_int (a) == g_value_get_int (b)); + break; + case G_TYPE_UINT: + ret = (g_value_get_uint (a) == g_value_get_uint (b)); + break; + case G_TYPE_INT64: + ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); + break; + case G_TYPE_UINT64: + ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); + break; + case G_TYPE_DOUBLE: + { + /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ + gdouble da = g_value_get_double (a); + gdouble db = g_value_get_double (b); + ret = memcmp (&da, &db, sizeof (gdouble)) == 0; + } + break; + case G_TYPE_STRING: + ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); + break; + case G_TYPE_VARIANT: + ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); + break; + default: + if (G_VALUE_TYPE (a) == G_TYPE_STRV) + ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); + else + g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); + break; + } + return ret; +} + +/* ------------------------------------------------------------------------ + * Code for interface cn.kylinos.keyboard + * ------------------------------------------------------------------------ + */ + +/** + * SECTION:Keyboard + * @title: Keyboard + * @short_description: Generated C code for the cn.kylinos.keyboard D-Bus interface + * + * This section contains code for working with the cn.kylinos.keyboard D-Bus interface in C. + */ + +/* ---- Introspection data for cn.kylinos.keyboard ---- */ + +static const _ExtendedGDBusArgInfo _keyboard_method_info_transfer_bool_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(sb)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _keyboard_method_info_transfer_bool_value_IN_ARG_pointers[] = +{ + &_keyboard_method_info_transfer_bool_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _keyboard_method_info_transfer_bool_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _keyboard_method_info_transfer_bool_value_OUT_ARG_pointers[] = +{ + &_keyboard_method_info_transfer_bool_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _keyboard_method_info_transfer_bool_value = +{ + { + -1, + (gchar *) "TransferBoolValue", + (GDBusArgInfo **) &_keyboard_method_info_transfer_bool_value_IN_ARG_pointers, + (GDBusArgInfo **) &_keyboard_method_info_transfer_bool_value_OUT_ARG_pointers, + NULL + }, + "handle-transfer-bool-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _keyboard_method_info_get_bool_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "s", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _keyboard_method_info_get_bool_value_IN_ARG_pointers[] = +{ + &_keyboard_method_info_get_bool_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _keyboard_method_info_get_bool_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _keyboard_method_info_get_bool_value_OUT_ARG_pointers[] = +{ + &_keyboard_method_info_get_bool_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _keyboard_method_info_get_bool_value = +{ + { + -1, + (gchar *) "GetBoolValue", + (GDBusArgInfo **) &_keyboard_method_info_get_bool_value_IN_ARG_pointers, + (GDBusArgInfo **) &_keyboard_method_info_get_bool_value_OUT_ARG_pointers, + NULL + }, + "handle-get-bool-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _keyboard_method_info_transfer_int_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(si)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _keyboard_method_info_transfer_int_value_IN_ARG_pointers[] = +{ + &_keyboard_method_info_transfer_int_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _keyboard_method_info_transfer_int_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _keyboard_method_info_transfer_int_value_OUT_ARG_pointers[] = +{ + &_keyboard_method_info_transfer_int_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _keyboard_method_info_transfer_int_value = +{ + { + -1, + (gchar *) "TransferIntValue", + (GDBusArgInfo **) &_keyboard_method_info_transfer_int_value_IN_ARG_pointers, + (GDBusArgInfo **) &_keyboard_method_info_transfer_int_value_OUT_ARG_pointers, + NULL + }, + "handle-transfer-int-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _keyboard_method_info_get_int_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "s", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _keyboard_method_info_get_int_value_IN_ARG_pointers[] = +{ + &_keyboard_method_info_get_int_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _keyboard_method_info_get_int_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "i", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _keyboard_method_info_get_int_value_OUT_ARG_pointers[] = +{ + &_keyboard_method_info_get_int_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _keyboard_method_info_get_int_value = +{ + { + -1, + (gchar *) "GetIntValue", + (GDBusArgInfo **) &_keyboard_method_info_get_int_value_IN_ARG_pointers, + (GDBusArgInfo **) &_keyboard_method_info_get_int_value_OUT_ARG_pointers, + NULL + }, + "handle-get-int-value", + FALSE +}; + +static const GDBusMethodInfo * const _keyboard_method_info_pointers[] = +{ + &_keyboard_method_info_transfer_bool_value.parent_struct, + &_keyboard_method_info_get_bool_value.parent_struct, + &_keyboard_method_info_transfer_int_value.parent_struct, + &_keyboard_method_info_get_int_value.parent_struct, + NULL +}; + +static const _ExtendedGDBusInterfaceInfo _keyboard_interface_info = +{ + { + -1, + (gchar *) "cn.kylinos.keyboard", + (GDBusMethodInfo **) &_keyboard_method_info_pointers, + NULL, + NULL, + NULL + }, + "keyboard", +}; + + +/** + * keyboard_interface_info: + * + * Gets a machine-readable description of the cn.kylinos.keyboard D-Bus interface. + * + * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. + */ +GDBusInterfaceInfo * +keyboard_interface_info (void) +{ + return (GDBusInterfaceInfo *) &_keyboard_interface_info.parent_struct; +} + +/** + * keyboard_override_properties: + * @klass: The class structure for a #GObject derived class. + * @property_id_begin: The property id to assign to the first overridden property. + * + * Overrides all #GObject properties in the #Keyboard interface for a concrete class. + * The properties are overridden in the order they are defined. + * + * Returns: The last property id. + */ +guint +keyboard_override_properties (GObjectClass *klass, guint property_id_begin) +{ + return property_id_begin - 1; +} + + + +/** + * Keyboard: + * + * Abstract interface type for the D-Bus interface cn.kylinos.keyboard. + */ + +/** + * KeyboardIface: + * @parent_iface: The parent interface. + * @handle_get_bool_value: Handler for the #Keyboard::handle-get-bool-value signal. + * @handle_get_int_value: Handler for the #Keyboard::handle-get-int-value signal. + * @handle_transfer_bool_value: Handler for the #Keyboard::handle-transfer-bool-value signal. + * @handle_transfer_int_value: Handler for the #Keyboard::handle-transfer-int-value signal. + * + * Virtual table for the D-Bus interface cn.kylinos.keyboard. + */ + +typedef KeyboardIface KeyboardInterface; +G_DEFINE_INTERFACE (Keyboard, keyboard, G_TYPE_OBJECT) + +static void +keyboard_default_init (KeyboardIface *iface) +{ + /* GObject signals for incoming D-Bus method calls: */ + /** + * Keyboard::handle-transfer-bool-value: + * @object: A #Keyboard. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferBoolValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call keyboard_complete_transfer_bool_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-bool-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (KeyboardIface, handle_transfer_bool_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Keyboard::handle-get-bool-value: + * @object: A #Keyboard. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the GetBoolValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call keyboard_complete_get_bool_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-get-bool-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (KeyboardIface, handle_get_bool_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_STRING); + + /** + * Keyboard::handle-transfer-int-value: + * @object: A #Keyboard. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferIntValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call keyboard_complete_transfer_int_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-int-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (KeyboardIface, handle_transfer_int_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Keyboard::handle-get-int-value: + * @object: A #Keyboard. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the GetIntValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call keyboard_complete_get_int_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-get-int-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (KeyboardIface, handle_get_int_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_STRING); + +} + +/** + * keyboard_call_transfer_bool_value: + * @proxy: A #KeyboardProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferBoolValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call keyboard_call_transfer_bool_value_finish() to get the result of the operation. + * + * See keyboard_call_transfer_bool_value_sync() for the synchronous, blocking version of this method. + */ +void +keyboard_call_transfer_bool_value ( + Keyboard *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * keyboard_call_transfer_bool_value_finish: + * @proxy: A #KeyboardProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to keyboard_call_transfer_bool_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with keyboard_call_transfer_bool_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +keyboard_call_transfer_bool_value_finish ( + Keyboard *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * keyboard_call_transfer_bool_value_sync: + * @proxy: A #KeyboardProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferBoolValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See keyboard_call_transfer_bool_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +keyboard_call_transfer_bool_value_sync ( + Keyboard *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * keyboard_call_get_bool_value: + * @proxy: A #KeyboardProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the GetBoolValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call keyboard_call_get_bool_value_finish() to get the result of the operation. + * + * See keyboard_call_get_bool_value_sync() for the synchronous, blocking version of this method. + */ +void +keyboard_call_get_bool_value ( + Keyboard *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "GetBoolValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * keyboard_call_get_bool_value_finish: + * @proxy: A #KeyboardProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to keyboard_call_get_bool_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with keyboard_call_get_bool_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +keyboard_call_get_bool_value_finish ( + Keyboard *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * keyboard_call_get_bool_value_sync: + * @proxy: A #KeyboardProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the GetBoolValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See keyboard_call_get_bool_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +keyboard_call_get_bool_value_sync ( + Keyboard *proxy, + const gchar *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "GetBoolValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * keyboard_call_transfer_int_value: + * @proxy: A #KeyboardProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferIntValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call keyboard_call_transfer_int_value_finish() to get the result of the operation. + * + * See keyboard_call_transfer_int_value_sync() for the synchronous, blocking version of this method. + */ +void +keyboard_call_transfer_int_value ( + Keyboard *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * keyboard_call_transfer_int_value_finish: + * @proxy: A #KeyboardProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to keyboard_call_transfer_int_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with keyboard_call_transfer_int_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +keyboard_call_transfer_int_value_finish ( + Keyboard *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * keyboard_call_transfer_int_value_sync: + * @proxy: A #KeyboardProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferIntValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See keyboard_call_transfer_int_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +keyboard_call_transfer_int_value_sync ( + Keyboard *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * keyboard_call_get_int_value: + * @proxy: A #KeyboardProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the GetIntValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call keyboard_call_get_int_value_finish() to get the result of the operation. + * + * See keyboard_call_get_int_value_sync() for the synchronous, blocking version of this method. + */ +void +keyboard_call_get_int_value ( + Keyboard *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "GetIntValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * keyboard_call_get_int_value_finish: + * @proxy: A #KeyboardProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to keyboard_call_get_int_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with keyboard_call_get_int_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +keyboard_call_get_int_value_finish ( + Keyboard *proxy, + gint *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(i)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * keyboard_call_get_int_value_sync: + * @proxy: A #KeyboardProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the GetIntValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See keyboard_call_get_int_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +keyboard_call_get_int_value_sync ( + Keyboard *proxy, + const gchar *arg_InArg, + gint *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "GetIntValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(i)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * keyboard_complete_transfer_bool_value: + * @object: A #Keyboard. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the TransferBoolValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +keyboard_complete_transfer_bool_value ( + Keyboard *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/** + * keyboard_complete_get_bool_value: + * @object: A #Keyboard. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the GetBoolValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +keyboard_complete_get_bool_value ( + Keyboard *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/** + * keyboard_complete_transfer_int_value: + * @object: A #Keyboard. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the TransferIntValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +keyboard_complete_transfer_int_value ( + Keyboard *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/** + * keyboard_complete_get_int_value: + * @object: A #Keyboard. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the GetIntValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +keyboard_complete_get_int_value ( + Keyboard *object, + GDBusMethodInvocation *invocation, + gint OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(i)", + OutArg)); +} + +/* ------------------------------------------------------------------------ */ + +/** + * KeyboardProxy: + * + * The #KeyboardProxy structure contains only private data and should only be accessed using the provided API. + */ + +/** + * KeyboardProxyClass: + * @parent_class: The parent class. + * + * Class structure for #KeyboardProxy. + */ + +struct _KeyboardProxyPrivate +{ + GData *qdata; +}; + +static void keyboard_proxy_iface_init (KeyboardIface *iface); + +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (KeyboardProxy, keyboard_proxy, G_TYPE_DBUS_PROXY, + G_ADD_PRIVATE (KeyboardProxy) + G_IMPLEMENT_INTERFACE (TYPE_KEYBOARD, keyboard_proxy_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (KeyboardProxy, keyboard_proxy, G_TYPE_DBUS_PROXY, + G_IMPLEMENT_INTERFACE (TYPE_KEYBOARD, keyboard_proxy_iface_init)) + +#endif +static void +keyboard_proxy_finalize (GObject *object) +{ + KeyboardProxy *proxy = KEYBOARD_PROXY (object); + g_datalist_clear (&proxy->priv->qdata); + G_OBJECT_CLASS (keyboard_proxy_parent_class)->finalize (object); +} + +static void +keyboard_proxy_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +keyboard_proxy_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +keyboard_proxy_g_signal (GDBusProxy *proxy, + const gchar *sender_name G_GNUC_UNUSED, + const gchar *signal_name, + GVariant *parameters) +{ + _ExtendedGDBusSignalInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + gsize n; + guint signal_id; + info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_keyboard_interface_info.parent_struct, signal_name); + if (info == NULL) + return; + num_params = g_variant_n_children (parameters); + paramv = g_new0 (GValue, num_params + 1); + g_value_init (¶mv[0], TYPE_KEYBOARD); + g_value_set_object (¶mv[0], proxy); + g_variant_iter_init (&iter, parameters); + n = 1; + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_KEYBOARD); + g_signal_emitv (paramv, signal_id, 0, NULL); + for (n = 0; n < num_params + 1; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static void +keyboard_proxy_g_properties_changed (GDBusProxy *_proxy, + GVariant *changed_properties, + const gchar *const *invalidated_properties) +{ + KeyboardProxy *proxy = KEYBOARD_PROXY (_proxy); + guint n; + const gchar *key; + GVariantIter *iter; + _ExtendedGDBusPropertyInfo *info; + g_variant_get (changed_properties, "a{sv}", &iter); + while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_keyboard_interface_info.parent_struct, key); + g_datalist_remove_data (&proxy->priv->qdata, key); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } + g_variant_iter_free (iter); + for (n = 0; invalidated_properties[n] != NULL; n++) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_keyboard_interface_info.parent_struct, invalidated_properties[n]); + g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } +} + +static void +keyboard_proxy_init (KeyboardProxy *proxy) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + proxy->priv = keyboard_proxy_get_instance_private (proxy); +#else + proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, TYPE_KEYBOARD_PROXY, KeyboardProxyPrivate); +#endif + + g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), keyboard_interface_info ()); +} + +static void +keyboard_proxy_class_init (KeyboardProxyClass *klass) +{ + GObjectClass *gobject_class; + GDBusProxyClass *proxy_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = keyboard_proxy_finalize; + gobject_class->get_property = keyboard_proxy_get_property; + gobject_class->set_property = keyboard_proxy_set_property; + + proxy_class = G_DBUS_PROXY_CLASS (klass); + proxy_class->g_signal = keyboard_proxy_g_signal; + proxy_class->g_properties_changed = keyboard_proxy_g_properties_changed; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (KeyboardProxyPrivate)); +#endif +} + +static void +keyboard_proxy_iface_init (KeyboardIface *iface) +{ +} + +/** + * keyboard_proxy_new: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Asynchronously creates a proxy for the D-Bus interface cn.kylinos.keyboard. See g_dbus_proxy_new() for more details. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call keyboard_proxy_new_finish() to get the result of the operation. + * + * See keyboard_proxy_new_sync() for the synchronous, blocking version of this constructor. + */ +void +keyboard_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_KEYBOARD_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.keyboard", NULL); +} + +/** + * keyboard_proxy_new_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to keyboard_proxy_new(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with keyboard_proxy_new(). + * + * Returns: (transfer full) (type KeyboardProxy): The constructed proxy object or %NULL if @error is set. + */ +Keyboard * +keyboard_proxy_new_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return KEYBOARD (ret); + else + return NULL; +} + +/** + * keyboard_proxy_new_sync: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Synchronously creates a proxy for the D-Bus interface cn.kylinos.keyboard. See g_dbus_proxy_new_sync() for more details. + * + * The calling thread is blocked until a reply is received. + * + * See keyboard_proxy_new() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type KeyboardProxy): The constructed proxy object or %NULL if @error is set. + */ +Keyboard * +keyboard_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_KEYBOARD_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.keyboard", NULL); + if (ret != NULL) + return KEYBOARD (ret); + else + return NULL; +} + + +/** + * keyboard_proxy_new_for_bus: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Like keyboard_proxy_new() but takes a #GBusType instead of a #GDBusConnection. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call keyboard_proxy_new_for_bus_finish() to get the result of the operation. + * + * See keyboard_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. + */ +void +keyboard_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_KEYBOARD_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.keyboard", NULL); +} + +/** + * keyboard_proxy_new_for_bus_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to keyboard_proxy_new_for_bus(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with keyboard_proxy_new_for_bus(). + * + * Returns: (transfer full) (type KeyboardProxy): The constructed proxy object or %NULL if @error is set. + */ +Keyboard * +keyboard_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return KEYBOARD (ret); + else + return NULL; +} + +/** + * keyboard_proxy_new_for_bus_sync: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Like keyboard_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. + * + * The calling thread is blocked until a reply is received. + * + * See keyboard_proxy_new_for_bus() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type KeyboardProxy): The constructed proxy object or %NULL if @error is set. + */ +Keyboard * +keyboard_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_KEYBOARD_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.keyboard", NULL); + if (ret != NULL) + return KEYBOARD (ret); + else + return NULL; +} + + +/* ------------------------------------------------------------------------ */ + +/** + * KeyboardSkeleton: + * + * The #KeyboardSkeleton structure contains only private data and should only be accessed using the provided API. + */ + +/** + * KeyboardSkeletonClass: + * @parent_class: The parent class. + * + * Class structure for #KeyboardSkeleton. + */ + +struct _KeyboardSkeletonPrivate +{ + GValue *properties; + GList *changed_properties; + GSource *changed_properties_idle_source; + GMainContext *context; + GMutex lock; +}; + +static void +_keyboard_skeleton_handle_method_call ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name, + const gchar *method_name, + GVariant *parameters, + GDBusMethodInvocation *invocation, + gpointer user_data) +{ + KeyboardSkeleton *skeleton = KEYBOARD_SKELETON (user_data); + _ExtendedGDBusMethodInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + guint num_extra; + gsize n; + guint signal_id; + GValue return_value = G_VALUE_INIT; + info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); + g_assert (info != NULL); + num_params = g_variant_n_children (parameters); + num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); + n = 0; + g_value_init (¶mv[n], TYPE_KEYBOARD); + g_value_set_object (¶mv[n++], skeleton); + g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); + g_value_set_object (¶mv[n++], invocation); + if (info->pass_fdlist) + { +#ifdef G_OS_UNIX + g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); + g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); +#else + g_assert_not_reached (); +#endif + } + g_variant_iter_init (&iter, parameters); + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_KEYBOARD); + g_value_init (&return_value, G_TYPE_BOOLEAN); + g_signal_emitv (paramv, signal_id, 0, &return_value); + if (!g_value_get_boolean (&return_value)) + g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); + g_value_unset (&return_value); + for (n = 0; n < num_params + num_extra; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static GVariant * +_keyboard_skeleton_handle_get_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GError **error, + gpointer user_data) +{ + KeyboardSkeleton *skeleton = KEYBOARD_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + GVariant *ret; + ret = NULL; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_keyboard_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + g_value_init (&value, pspec->value_type); + g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); + ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); + g_value_unset (&value); + } + return ret; +} + +static gboolean +_keyboard_skeleton_handle_set_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GVariant *variant, + GError **error, + gpointer user_data) +{ + KeyboardSkeleton *skeleton = KEYBOARD_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + gboolean ret; + ret = FALSE; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_keyboard_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + if (info->use_gvariant) + g_value_set_variant (&value, variant); + else + g_dbus_gvariant_to_gvalue (variant, &value); + g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); + g_value_unset (&value); + ret = TRUE; + } + return ret; +} + +static const GDBusInterfaceVTable _keyboard_skeleton_vtable = +{ + _keyboard_skeleton_handle_method_call, + _keyboard_skeleton_handle_get_property, + _keyboard_skeleton_handle_set_property, + {NULL} +}; + +static GDBusInterfaceInfo * +keyboard_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return keyboard_interface_info (); +} + +static GDBusInterfaceVTable * +keyboard_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return (GDBusInterfaceVTable *) &_keyboard_skeleton_vtable; +} + +static GVariant * +keyboard_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) +{ + KeyboardSkeleton *skeleton = KEYBOARD_SKELETON (_skeleton); + + GVariantBuilder builder; + guint n; + g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); + if (_keyboard_interface_info.parent_struct.properties == NULL) + goto out; + for (n = 0; _keyboard_interface_info.parent_struct.properties[n] != NULL; n++) + { + GDBusPropertyInfo *info = _keyboard_interface_info.parent_struct.properties[n]; + if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) + { + GVariant *value; + value = _keyboard_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "cn.kylinos.keyboard", info->name, NULL, skeleton); + if (value != NULL) + { + g_variant_take_ref (value); + g_variant_builder_add (&builder, "{sv}", info->name, value); + g_variant_unref (value); + } + } + } +out: + return g_variant_builder_end (&builder); +} + +static void +keyboard_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) +{ +} + +static void keyboard_skeleton_iface_init (KeyboardIface *iface); +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (KeyboardSkeleton, keyboard_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_ADD_PRIVATE (KeyboardSkeleton) + G_IMPLEMENT_INTERFACE (TYPE_KEYBOARD, keyboard_skeleton_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (KeyboardSkeleton, keyboard_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_IMPLEMENT_INTERFACE (TYPE_KEYBOARD, keyboard_skeleton_iface_init)) + +#endif +static void +keyboard_skeleton_finalize (GObject *object) +{ + KeyboardSkeleton *skeleton = KEYBOARD_SKELETON (object); + g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); + if (skeleton->priv->changed_properties_idle_source != NULL) + g_source_destroy (skeleton->priv->changed_properties_idle_source); + g_main_context_unref (skeleton->priv->context); + g_mutex_clear (&skeleton->priv->lock); + G_OBJECT_CLASS (keyboard_skeleton_parent_class)->finalize (object); +} + +static void +keyboard_skeleton_init (KeyboardSkeleton *skeleton) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + skeleton->priv = keyboard_skeleton_get_instance_private (skeleton); +#else + skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_KEYBOARD_SKELETON, KeyboardSkeletonPrivate); +#endif + + g_mutex_init (&skeleton->priv->lock); + skeleton->priv->context = g_main_context_ref_thread_default (); +} + +static void +keyboard_skeleton_class_init (KeyboardSkeletonClass *klass) +{ + GObjectClass *gobject_class; + GDBusInterfaceSkeletonClass *skeleton_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = keyboard_skeleton_finalize; + + skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); + skeleton_class->get_info = keyboard_skeleton_dbus_interface_get_info; + skeleton_class->get_properties = keyboard_skeleton_dbus_interface_get_properties; + skeleton_class->flush = keyboard_skeleton_dbus_interface_flush; + skeleton_class->get_vtable = keyboard_skeleton_dbus_interface_get_vtable; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (KeyboardSkeletonPrivate)); +#endif +} + +static void +keyboard_skeleton_iface_init (KeyboardIface *iface) +{ +} + +/** + * keyboard_skeleton_new: + * + * Creates a skeleton object for the D-Bus interface cn.kylinos.keyboard. + * + * Returns: (transfer full) (type KeyboardSkeleton): The skeleton object. + */ +Keyboard * +keyboard_skeleton_new (void) +{ + return KEYBOARD (g_object_new (TYPE_KEYBOARD_SKELETON, NULL)); +} + diff --git a/src/hardware/keyboard/keyboard-generated.h b/src/hardware/keyboard/keyboard-generated.h new file mode 100644 index 0000000..0a11ecd --- /dev/null +++ b/src/hardware/keyboard/keyboard-generated.h @@ -0,0 +1,283 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +G_BEGIN_DECLS + + +/* ------------------------------------------------------------------------ */ +/* Declarations for cn.kylinos.keyboard */ + +#define TYPE_KEYBOARD (keyboard_get_type ()) +#define KEYBOARD(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_KEYBOARD, Keyboard)) +#define IS_KEYBOARD(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_KEYBOARD)) +#define KEYBOARD_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), TYPE_KEYBOARD, KeyboardIface)) + +struct _Keyboard; +typedef struct _Keyboard Keyboard; +typedef struct _KeyboardIface KeyboardIface; + +struct _KeyboardIface +{ + GTypeInterface parent_iface; + + gboolean (*handle_get_bool_value) ( + Keyboard *object, + GDBusMethodInvocation *invocation, + const gchar *arg_InArg); + + gboolean (*handle_get_int_value) ( + Keyboard *object, + GDBusMethodInvocation *invocation, + const gchar *arg_InArg); + + gboolean (*handle_transfer_bool_value) ( + Keyboard *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + + gboolean (*handle_transfer_int_value) ( + Keyboard *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + +}; + +GType keyboard_get_type (void) G_GNUC_CONST; + +GDBusInterfaceInfo *keyboard_interface_info (void); +guint keyboard_override_properties (GObjectClass *klass, guint property_id_begin); + + +/* D-Bus method call completion functions: */ +void keyboard_complete_transfer_bool_value ( + Keyboard *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + +void keyboard_complete_get_bool_value ( + Keyboard *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + +void keyboard_complete_transfer_int_value ( + Keyboard *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + +void keyboard_complete_get_int_value ( + Keyboard *object, + GDBusMethodInvocation *invocation, + gint OutArg); + + + +/* D-Bus method calls: */ +void keyboard_call_transfer_bool_value ( + Keyboard *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean keyboard_call_transfer_bool_value_finish ( + Keyboard *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean keyboard_call_transfer_bool_value_sync ( + Keyboard *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + +void keyboard_call_get_bool_value ( + Keyboard *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean keyboard_call_get_bool_value_finish ( + Keyboard *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean keyboard_call_get_bool_value_sync ( + Keyboard *proxy, + const gchar *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + +void keyboard_call_transfer_int_value ( + Keyboard *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean keyboard_call_transfer_int_value_finish ( + Keyboard *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean keyboard_call_transfer_int_value_sync ( + Keyboard *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + +void keyboard_call_get_int_value ( + Keyboard *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean keyboard_call_get_int_value_finish ( + Keyboard *proxy, + gint *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean keyboard_call_get_int_value_sync ( + Keyboard *proxy, + const gchar *arg_InArg, + gint *out_OutArg, + GCancellable *cancellable, + GError **error); + + + +/* ---- */ + +#define TYPE_KEYBOARD_PROXY (keyboard_proxy_get_type ()) +#define KEYBOARD_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_KEYBOARD_PROXY, KeyboardProxy)) +#define KEYBOARD_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_KEYBOARD_PROXY, KeyboardProxyClass)) +#define KEYBOARD_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_KEYBOARD_PROXY, KeyboardProxyClass)) +#define IS_KEYBOARD_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_KEYBOARD_PROXY)) +#define IS_KEYBOARD_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_KEYBOARD_PROXY)) + +typedef struct _KeyboardProxy KeyboardProxy; +typedef struct _KeyboardProxyClass KeyboardProxyClass; +typedef struct _KeyboardProxyPrivate KeyboardProxyPrivate; + +struct _KeyboardProxy +{ + /*< private >*/ + GDBusProxy parent_instance; + KeyboardProxyPrivate *priv; +}; + +struct _KeyboardProxyClass +{ + GDBusProxyClass parent_class; +}; + +GType keyboard_proxy_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (KeyboardProxy, g_object_unref) +#endif + +void keyboard_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Keyboard *keyboard_proxy_new_finish ( + GAsyncResult *res, + GError **error); +Keyboard *keyboard_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + +void keyboard_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Keyboard *keyboard_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error); +Keyboard *keyboard_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + + +/* ---- */ + +#define TYPE_KEYBOARD_SKELETON (keyboard_skeleton_get_type ()) +#define KEYBOARD_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_KEYBOARD_SKELETON, KeyboardSkeleton)) +#define KEYBOARD_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_KEYBOARD_SKELETON, KeyboardSkeletonClass)) +#define KEYBOARD_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_KEYBOARD_SKELETON, KeyboardSkeletonClass)) +#define IS_KEYBOARD_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_KEYBOARD_SKELETON)) +#define IS_KEYBOARD_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_KEYBOARD_SKELETON)) + +typedef struct _KeyboardSkeleton KeyboardSkeleton; +typedef struct _KeyboardSkeletonClass KeyboardSkeletonClass; +typedef struct _KeyboardSkeletonPrivate KeyboardSkeletonPrivate; + +struct _KeyboardSkeleton +{ + /*< private >*/ + GDBusInterfaceSkeleton parent_instance; + KeyboardSkeletonPrivate *priv; +}; + +struct _KeyboardSkeletonClass +{ + GDBusInterfaceSkeletonClass parent_class; +}; + +GType keyboard_skeleton_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (KeyboardSkeleton, g_object_unref) +#endif + +Keyboard *keyboard_skeleton_new (void); + + +G_END_DECLS + +#endif /* __KEYBOARD_GENERATED_H__ */ diff --git a/src/hardware/keyboard/kylin-interface-interface.c b/src/hardware/keyboard/kylin-interface-interface.c new file mode 100644 index 0000000..a0ec8c4 --- /dev/null +++ b/src/hardware/keyboard/kylin-interface-interface.c @@ -0,0 +1,250 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#define CB "cursor-blink" +#define CBT "cursor-blink-time" +#define FN "font-name" +#define DFN "document-font-name" +#define MFN "monospace-font-name" + +static GMainLoop *pLoop = NULL; +static GDBusConnection *pConnection = NULL; +static Interface *pProxy = NULL; + +bool kylin_hardware_keyboard_set_cursorblink(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=CB; + gboolean retv; + arg=g_variant_new("(sb)", key, in_arg); + interface_call_transfer_bool_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_keyboard_cursorblink. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +bool kylin_hardware_keyboard_get_cursorblink() +{ + gchar *key=CB; + gboolean value; + GError* pError=NULL; + interface_call_get_bool_value_sync(pProxy, key, &value, NULL, &pError); + return value; + +} + +bool kylin_hardware_keyboard_set_cursorblinktime(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=CBT; + gboolean retv; + arg=g_variant_new("(si)",key,in_arg); + interface_call_transfer_int_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_keyboard_cursorblinktime. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; + +} + +int kylin_hardware_keyboard_get_cursorblinktime() +{ + gchar *key=CBT; + int value; + GError* pError=NULL; + interface_call_get_int_value_sync(pProxy, key, &value, NULL, &pError); + return value; +} + +bool kylin_personal_fonts_set_fontname(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=FN; + gboolean retv; + arg=g_variant_new("(ss)", key, in_arg); + interface_call_transfer_string_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_fontname. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +char *kylin_personal_fonts_get_fontname() +{ + gchar *key=FN; + char *value; + GError* pError=NULL; + interface_call_get_string_value_sync(pProxy, key, &value, NULL, &pError); + return value; +} + +bool kylin_personal_fonts_set_documentfont(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=DFN; + gboolean retv; + arg=g_variant_new("(ss)", key, in_arg); + interface_call_transfer_string_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_documentfont. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +char *kylin_personal_fonts_get_documentfont() +{ + gchar *key=DFN; + char *value; + GError* pError=NULL; + interface_call_get_string_value_sync(pProxy, key, &value, NULL, &pError); + return value; +} + +bool kylin_personal_fonts_set_monospacefont(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=MFN; + gboolean retv; + arg=g_variant_new("(ss)", key, in_arg); + interface_call_transfer_string_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_monospacefont. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +char *kylin_personal_fonts_get_monospacefont() +{ + gchar *key=MFN; + char *value; + GError* pError=NULL; + interface_call_get_string_value_sync(pProxy, key, &value, NULL, &pError); + return value; +} + +void *run(void* arg) +{ + /** start the main event loop which manages all available sources of events */ + g_main_loop_run(pLoop); + + return ((void*)0); +} + +int thread_create(void) + { + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if(0 != err){ + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; + } + +bool InitDBusInterface(void) + { + bool bRet = TRUE; + GError *pConnError = NULL; + GError *pProxyError = NULL; + + do{ + bRet = TRUE; + pLoop = g_main_loop_new(NULL, FALSE); /** create main loop, but do not start it.*/ + + /** First step: get a connection */ + pConnection = g_bus_get_sync(INTERFACE_BUS, NULL, &pConnError); + + if (NULL == pConnError){ + /** Second step: try to get a connection to the given bus.*/ + pProxy = interface_proxy_new_sync(pConnection, + G_DBUS_PROXY_FLAGS_NONE, + INTERFACE_BUS_NAME, + INTERFACE_OBJECT_PATH, + NULL, + &pProxyError); + if (0 == pProxy){ + print_error("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message); + g_error_free(pProxyError); + bRet = FALSE; + } + + + } + else{ + print_error("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message); + g_error_free(pConnError); + bRet = FALSE; + } + }while(FALSE == bRet); + + thread_create(); + + return bRet; + } + +bool DeInitDBusInterface(void) +{ + bool bRet = FALSE; + + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} diff --git a/src/hardware/keyboard/kylin-interface-interface.h b/src/hardware/keyboard/kylin-interface-interface.h new file mode 100644 index 0000000..66baf92 --- /dev/null +++ b/src/hardware/keyboard/kylin-interface-interface.h @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Initialize the DBus Communication. + */ +bool InitDBusInterface(void); + +/** + * Delete the DBus Communication. + */ +bool DeInitDBusInterface(void); + +/** + * Set cursor blink. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_keyboard_set_cursorblink(const bool in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +bool kylin_hardware_keyboard_get_cursorblink(); + +/** + * Set cursor blink time. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_keyboard_set_cursorblinktime(const int in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +int kylin_hardware_keyboard_get_cursorblinktime(); + +/** + * Set the name of the default font used by gtk+. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_personal_fonts_set_fontname(const char *in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +char *kylin_personal_fonts_get_fontname(); + +/** + * Set the name of the default font used for reading documents. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_personal_fonts_set_documentfont(const char *in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +char *kylin_personal_fonts_get_documentfont(); + +/** + * Set the name of a monospaced (fixed-width) font for use in locations like terminals. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_personal_fonts_set_monospacefont(const char *in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +char *kylin_personal_fonts_get_monospacefont(); +#ifdef __cplusplus +} +#endif + +#endif + + + + + + + + + + + + + diff --git a/src/hardware/keyboard/kylin-interface-server.c b/src/hardware/keyboard/kylin-interface-server.c new file mode 100644 index 0000000..c3890c2 --- /dev/null +++ b/src/hardware/keyboard/kylin-interface-server.c @@ -0,0 +1,267 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include "interface-dbus.h" +#include "src/common/kylin-print.h" +#include "interface-generated.h" +#include +#include + +#define schemaID "org.mate.interface" + +static GMainLoop *pLoop = NULL; +static Interface *pSkeleton = NULL; + +static gboolean kylin_set_bool(Interface* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gboolean value; + gint i; + g_variant_get(in_arg, "(sb)", &key, &value); + if(value==false)i=0; + else i=1; + + GSettings *setting=g_settings_new(schemaID); + gboolean retv=g_settings_set_boolean(setting,key,value); + g_object_unref(setting); + g_settings_sync(); + + interface_complete_transfer_bool_value(object, invocation, retv); + + print_info("(%s, %d)\n", key, i); + + return TRUE; +} + +static gboolean kylin_get_bool(Interface* object, + GDBusMethodInvocation* invocation, + gchar *in_arg, + gpointer user_data) +{ + GSettings *setting=g_settings_new(schemaID); + gboolean ret=g_settings_get_boolean(setting, in_arg); + g_object_unref(setting); + interface_complete_get_bool_value(object, invocation, ret); + return TRUE; + +} + + +static gboolean kylin_set_int(Interface* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gint value; + g_variant_get(in_arg, "(si)", &key, &value); + + GSettings *setting=g_settings_new(schemaID); + gboolean retv=g_settings_set_int(setting,key,value); + g_object_unref(setting); + g_settings_sync(); + + interface_complete_transfer_int_value(object, invocation, retv); + + print_info("(%s, %d)\n", key, value); + + return TRUE; +} + +static gboolean kylin_get_int(Interface* object, + GDBusMethodInvocation* invocation, + gchar *in_arg, + gpointer user_data) +{ + GSettings *setting=g_settings_new(schemaID); + gint ret=g_settings_get_int(setting, in_arg); + g_object_unref(setting); + interface_complete_get_int_value(object, invocation, ret); + return TRUE; + +} + +static gboolean kylin_set_char(Interface* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gchar *value=NULL; + g_variant_get(in_arg, "(ss)", &key, &value); + + GSettings *setting=g_settings_new(schemaID); + gboolean retv=g_settings_set_string(setting,key,value); + g_object_unref(setting); + g_settings_sync(); + + interface_complete_transfer_string_value(object, invocation, retv); + + print_info("(%s, %s)\n", key, value); + + return TRUE; +} + +static gboolean kylin_get_char(Interface* object, + GDBusMethodInvocation* invocation, + gchar *in_arg, + gpointer user_data) +{ + GSettings *setting=g_settings_new(schemaID); + gchar *ret=g_settings_get_string(setting, in_arg); + g_object_unref(setting); + interface_complete_get_string_value(object, invocation, ret); + return TRUE; + +} + +static void bus_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + + GError *pError = NULL; + + /** Second step: Try to get a connection to the given bus. */ + pSkeleton = interface_skeleton_new(); + + /** Third step: Attach to dbus signals. */ + (void) g_signal_connect(pSkeleton, "handle-transfer-bool-value", G_CALLBACK(kylin_set_bool), NULL); + (void) g_signal_connect(pSkeleton, "handle-transfer-int-value", G_CALLBACK(kylin_set_int), NULL); + (void) g_signal_connect(pSkeleton, "handle-transfer-string-value", G_CALLBACK(kylin_set_char), NULL); + (void) g_signal_connect(pSkeleton, "handle-get-bool-value", G_CALLBACK(kylin_get_bool), NULL); + (void) g_signal_connect(pSkeleton, "handle-get-int-value", G_CALLBACK(kylin_get_int), NULL); + (void) g_signal_connect(pSkeleton, "handle-get-string-value", G_CALLBACK(kylin_get_char), NULL); + + /** Fourth step: Export interface skeleton. */ + (void)g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(pSkeleton), + connection, + INTERFACE_OBJECT_PATH, + &pError); + + if(pError != NULL){ + print_error("Error: Failed to export object. Reason: %s.\n", pError->message); + g_error_free(pError); + g_main_loop_quit(pLoop); + } +} + +static void name_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + print_info("name_acquired_cb call, Acquired bus name: %s.\n", INTERFACE_BUS_NAME); +} + +static void name_lost_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + if(connection == NULL) + { + print_error("name_lost_cb call, Error: Failed to connect to dbus.\n"); + } + else + { + print_error("name_lost_cb call, Error: Failed to obtain bus name: %s.\n", INTERFACE_BUS_NAME); + } + + g_main_loop_quit(pLoop); +} + +void* run(void* para) +{ + /** Start the Main Event Loop which manages all available sources of events */ + g_main_loop_run( pLoop ); + + return ((void*)0); +} + +int thread_create(void) +{ + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if (err != 0) + { + + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; +} + +bool InitDBusCommunicationServer(void) +{ + bool bRet = TRUE; + + g_print("InitDBusCommunicationServer: Server started.\n"); + + /** create main loop, but do not start it. */ + pLoop = g_main_loop_new(NULL, FALSE); + + /** first step: connect to dbus */ + (void)g_bus_own_name(INTERFACE_BUS, + INTERFACE_BUS_NAME, + G_BUS_NAME_OWNER_FLAGS_NONE, + &bus_acquired_cb, + &name_acquired_cb, + &name_lost_cb, + NULL, + NULL); + + thread_create(); + + return bRet; +} + +bool DeinitDBusCommunicationServer(void) +{ + bool bRet = FALSE; + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} + +int main(void) +{ + InitDBusCommunicationServer(); + + sleep(100); + + DeinitDBusCommunicationServer(); + + return 0; +} diff --git a/src/hardware/keyboard/kylin-keyboard-interface.c b/src/hardware/keyboard/kylin-keyboard-interface.c new file mode 100644 index 0000000..835bf36 --- /dev/null +++ b/src/hardware/keyboard/kylin-keyboard-interface.c @@ -0,0 +1,196 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#define REP "repeat" +#define RAT "rate" +#define DEL "delay" + +static GMainLoop *pLoop = NULL; +static GDBusConnection *pConnection = NULL; +static Keyboard *pProxy = NULL; + +bool kylin_hardware_keyboard_set_repeat(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=REP; + gboolean retv; + arg=g_variant_new("(sb)", key, in_arg); + keyboard_call_transfer_bool_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_keyboard_repeat. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +bool kylin_hardware_keyboard_get_repeat() +{ + GError* pError=NULL; + gchar *key=REP; + gboolean value; + keyboard_call_get_bool_value_sync(pProxy, key, &value, NULL, &pError); + return value; +} + +bool kylin_hardware_keyboard_set_rate(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=RAT; + gboolean retv; + arg=g_variant_new("(si)",key,in_arg); + keyboard_call_transfer_int_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_keyboard_rate. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; + +} + +int kylin_hardware_keyboard_get_rate() +{ + gchar *key=RAT; + GError* pError=NULL; + gint value; + keyboard_call_get_int_value_sync(pProxy, key, &value, NULL, &pError); + return value; +} + +bool kylin_hardware_keyboard_set_delay(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=DEL; + gboolean retv; + arg=g_variant_new("(si)",key,in_arg); + keyboard_call_transfer_int_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_keyboard_delay. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; + +} + +int kylin_hardware_keyboard_get_delay() +{ + gchar *key=DEL; + GError* pError=NULL; + gint value; + keyboard_call_get_int_value_sync(pProxy, key, &value, NULL, &pError); + return value; +} + +void *run(void* arg) +{ + /** start the main event loop which manages all available sources of events */ + g_main_loop_run(pLoop); + + return ((void*)0); +} + +int thread_create(void) + { + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if(0 != err){ + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; + } + +bool InitDBusKeyboard(void) + { + bool bRet = TRUE; + GError *pConnError = NULL; + GError *pProxyError = NULL; + + do{ + bRet = TRUE; + pLoop = g_main_loop_new(NULL, FALSE); /** create main loop, but do not start it.*/ + + /** First step: get a connection */ + pConnection = g_bus_get_sync(KEYBOARD_BUS, NULL, &pConnError); + + if (NULL == pConnError){ + /** Second step: try to get a connection to the given bus.*/ + pProxy = keyboard_proxy_new_sync(pConnection, + G_DBUS_PROXY_FLAGS_NONE, + KEYBOARD_BUS_NAME, + KEYBOARD_OBJECT_PATH, + NULL, + &pProxyError); + if (0 == pProxy){ + print_error("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message); + g_error_free(pProxyError); + bRet = FALSE; + } + + + } + else{ + print_error("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message); + g_error_free(pConnError); + bRet = FALSE; + } + }while(FALSE == bRet); + + thread_create(); + + return bRet; + } + +bool DeInitDBusKeyboard(void) +{ + bool bRet = FALSE; + + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} diff --git a/src/hardware/keyboard/kylin-keyboard-interface.h b/src/hardware/keyboard/kylin-keyboard-interface.h new file mode 100644 index 0000000..9332d2c --- /dev/null +++ b/src/hardware/keyboard/kylin-keyboard-interface.h @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Initialize the DBus Communication + */ +bool InitDBusKeyboard(void); + +/** + * Delete the DBus Communication. + */ +bool DeInitDBusKeyboard(void); + +/** + * Repeat the key when holding down a key. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_keyboard_set_repeat(const bool in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +bool kylin_hardware_keyboard_get_repeat(); + +/** + * Set key speed. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_keyboard_set_rate(const int in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +int kylin_hardware_keyboard_get_rate(); + +/** + * Set time delay. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_keyboard_set_delay(const int in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +int kylin_hardware_keyboard_get_delay(); + +#ifdef __cplusplus +} +#endif + +#endif + + + + + + + + + + + + + diff --git a/src/hardware/keyboard/kylin-keyboard-server.c b/src/hardware/keyboard/kylin-keyboard-server.c new file mode 100644 index 0000000..49bed25 --- /dev/null +++ b/src/hardware/keyboard/kylin-keyboard-server.c @@ -0,0 +1,229 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include "keyboard-dbus.h" +#include "src/common/kylin-print.h" +#include "keyboard-generated.h" +#include +#include + +#define schemaID "org.mate.peripherals-keyboard" + +static GMainLoop *pLoop = NULL; +static Keyboard *pSkeleton = NULL; + +static gboolean kylin_set_bool(Keyboard* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gboolean value; + gint i; + g_variant_get(in_arg, "(sb)", &key, &value); + if(value==false)i=0; + else i=1; + + GSettings *setting=g_settings_new(schemaID); + gboolean retv=g_settings_set_boolean(setting,key,value); + g_object_unref(setting); + g_settings_sync(); + + keyboard_complete_transfer_bool_value(object, invocation, retv); + + print_info("(%s, %d)\n", key, i); + + return TRUE; +} + +static gboolean kylin_get_bool(Keyboard* object, + GDBusMethodInvocation* invocation, + gchar *in_arg, + gpointer user_data) +{ + GSettings *setting=g_settings_new(schemaID); + gboolean ret=g_settings_get_boolean(setting, in_arg); + g_object_unref(setting); + keyboard_complete_get_bool_value(object, invocation, ret); + return TRUE; + +} + +static gboolean kylin_set_int(Keyboard* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gint value; + g_variant_get(in_arg, "(si)", &key, &value); + + GSettings *setting=g_settings_new(schemaID); + gboolean retv=g_settings_set_int(setting,key,value); + g_object_unref(setting); + g_settings_sync(); + + keyboard_complete_transfer_int_value(object, invocation, retv); + + print_info("(%s, %d)\n", key, value); + + return TRUE; +} + +static gboolean kylin_get_int(Keyboard* object, + GDBusMethodInvocation* invocation, + gchar *in_arg, + gpointer user_data) +{ + GSettings *setting=g_settings_new(schemaID); + gint ret=g_settings_get_int(setting, in_arg); + g_object_unref(setting); + keyboard_complete_get_int_value(object, invocation, ret); + return TRUE; + +} + +static void bus_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + + GError *pError = NULL; + + /** Second step: Try to get a connection to the given bus. */ + pSkeleton = keyboard_skeleton_new(); + + /** Third step: Attach to dbus signals. */ + (void) g_signal_connect(pSkeleton, "handle-transfer-bool-value", G_CALLBACK(kylin_set_bool), NULL); + (void) g_signal_connect(pSkeleton, "handle-get-bool-value", G_CALLBACK(kylin_get_bool), NULL); + (void) g_signal_connect(pSkeleton, "handle-transfer-int-value", G_CALLBACK(kylin_set_int), NULL); + (void) g_signal_connect(pSkeleton, "handle-get-int-value", G_CALLBACK(kylin_get_int), NULL); + + /** Fourth step: Export interface skeleton. */ + (void)g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(pSkeleton), + connection, + KEYBOARD_OBJECT_PATH, + &pError); + + if(pError != NULL){ + print_error("Error: Failed to export object. Reason: %s.\n", pError->message); + g_error_free(pError); + g_main_loop_quit(pLoop); + } +} + +static void name_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + print_info("name_acquired_cb call, Acquired bus name: %s.\n", KEYBOARD_BUS_NAME); +} + +static void name_lost_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + if(connection == NULL) + { + print_error("name_lost_cb call, Error: Failed to connect to dbus.\n"); + } + else + { + print_error("name_lost_cb call, Error: Failed to obtain bus name: %s.\n", KEYBOARD_BUS_NAME); + } + + g_main_loop_quit(pLoop); +} + +void* run(void* para) +{ + /** Start the Main Event Loop which manages all available sources of events */ + g_main_loop_run( pLoop ); + + return ((void*)0); +} + +int thread_create(void) +{ + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if (err != 0) + { + + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; +} + +bool InitDBusCommunicationServer(void) +{ + bool bRet = TRUE; + + g_print("InitDBusCommunicationServer: Server started.\n"); + + /** create main loop, but do not start it. */ + pLoop = g_main_loop_new(NULL, FALSE); + + /** first step: connect to dbus */ + (void)g_bus_own_name(KEYBOARD_BUS, + KEYBOARD_BUS_NAME, + G_BUS_NAME_OWNER_FLAGS_NONE, + &bus_acquired_cb, + &name_acquired_cb, + &name_lost_cb, + NULL, + NULL); + + thread_create(); + + return bRet; +} + +bool DeinitDBusCommunicationServer(void) +{ + bool bRet = FALSE; + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} + +int main(void) +{ + InitDBusCommunicationServer(); + + sleep(100); + + DeinitDBusCommunicationServer(); + return 0; +} diff --git a/src/hardware/keyboard/kylin-xkbgeneral-interface.c b/src/hardware/keyboard/kylin-xkbgeneral-interface.c new file mode 100644 index 0000000..fc30e2b --- /dev/null +++ b/src/hardware/keyboard/kylin-xkbgeneral-interface.c @@ -0,0 +1,140 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#define GPW "group-per-window" + +static GMainLoop *pLoop = NULL; +static GDBusConnection *pConnection = NULL; +static Xkbgeneral *pProxy = NULL; + +bool kylin_hardware_keyboard_set_groupperwindow(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=GPW; + gboolean retv; + arg=g_variant_new("(sb)", key, in_arg); + xkbgeneral_call_transfer_bool_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_keyboard_groupperwindow. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +bool kylin_hardware_keyboard_get_groupperwindow() +{ + GError* pError=NULL; + gchar *key=GPW; + gboolean value; + xkbgeneral_call_get_bool_value_sync(pProxy, key, &value, NULL, &pError); + return value; +} + +void *run(void* arg) +{ + /** start the main event loop which manages all available sources of events */ + g_main_loop_run(pLoop); + + return ((void*)0); +} + +int thread_create(void) + { + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if(0 != err){ + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; + } + +bool InitDBusXkbgeneral(void) + { + bool bRet = TRUE; + GError *pConnError = NULL; + GError *pProxyError = NULL; + + do{ + bRet = TRUE; + pLoop = g_main_loop_new(NULL, FALSE); /** create main loop, but do not start it.*/ + + /** First step: get a connection */ + pConnection = g_bus_get_sync(XKBGENERAL_BUS, NULL, &pConnError); + + if (NULL == pConnError){ + /** Second step: try to get a connection to the given bus.*/ + pProxy = xkbgeneral_proxy_new_sync(pConnection, + G_DBUS_PROXY_FLAGS_NONE, + XKBGENERAL_BUS_NAME, + XKBGENERAL_OBJECT_PATH, + NULL, + &pProxyError); + if (0 == pProxy){ + print_error("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message); + g_error_free(pProxyError); + bRet = FALSE; + } + + + } + else{ + print_error("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message); + g_error_free(pConnError); + bRet = FALSE; + } + }while(FALSE == bRet); + + thread_create(); + + return bRet; + } + +bool DeInitDBusXkbgeneral(void) +{ + bool bRet = FALSE; + + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} diff --git a/src/hardware/keyboard/kylin-xkbgeneral-interface.h b/src/hardware/keyboard/kylin-xkbgeneral-interface.h new file mode 100644 index 0000000..c6b2927 --- /dev/null +++ b/src/hardware/keyboard/kylin-xkbgeneral-interface.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Initialize the DBus Communication + */ +bool InitDBusXkbgeneral(void); + +/** + * Delete the DBus Communication + */ +bool DeInitDBusXkbgeneral(void); + +/** + * Keep and manage separate group per window. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_keyboard_set_groupperwindow(const bool in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +bool kylin_hardware_keyboard_get_groupperwindow(); + +#ifdef __cplusplus +} +#endif + +#endif + + + + + + + + + + + + + diff --git a/src/hardware/keyboard/kylin-xkbgeneral-server.c b/src/hardware/keyboard/kylin-xkbgeneral-server.c new file mode 100644 index 0000000..30eb013 --- /dev/null +++ b/src/hardware/keyboard/kylin-xkbgeneral-server.c @@ -0,0 +1,193 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include "xkbgeneral-dbus.h" +#include "src/common/kylin-print.h" +#include "xkbgeneral-generated.h" +#include +#include + +#define schemaID "org.mate.peripherals-keyboard-xkb.general" + +static GMainLoop *pLoop = NULL; +static Xkbgeneral *pSkeleton = NULL; + +static gboolean kylin_set_bool(Xkbgeneral* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gboolean value; + gint i; + g_variant_get(in_arg, "(sb)", &key, &value); + if(value==false)i=0; + else i=1; + + GSettings *setting=g_settings_new(schemaID); + gboolean retv=g_settings_set_boolean(setting,key,value); + g_object_unref(setting); + g_settings_sync(); + + xkbgeneral_complete_transfer_bool_value(object, invocation, retv); + + print_info("(%s, %d)\n", key, i); + + return TRUE; +} + +static gboolean kylin_get_bool(Xkbgeneral* object, + GDBusMethodInvocation* invocation, + gchar *in_arg, + gpointer user_data) +{ + GSettings *setting=g_settings_new(schemaID); + gboolean ret=g_settings_get_boolean(setting, in_arg); + g_object_unref(setting); + xkbgeneral_complete_get_bool_value(object, invocation, ret); + return TRUE; + +} + +static void bus_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + + GError *pError = NULL; + + /** Second step: Try to get a connection to the given bus. */ + pSkeleton = xkbgeneral_skeleton_new(); + + /** Third step: Attach to dbus signals. */ + (void) g_signal_connect(pSkeleton, "handle-transfer-bool-value", G_CALLBACK(kylin_set_bool), NULL); + (void) g_signal_connect(pSkeleton, "handle-get-bool-value", G_CALLBACK(kylin_get_bool), NULL); + + /** Fourth step: Export interface skeleton. */ + (void)g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(pSkeleton), + connection, + XKBGENERAL_OBJECT_PATH, + &pError); + + if(pError != NULL){ + print_error("Error: Failed to export object. Reason: %s.\n", pError->message); + g_error_free(pError); + g_main_loop_quit(pLoop); + } +} + +static void name_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + print_info("name_acquired_cb call, Acquired bus name: %s.\n", XKBGENERAL_BUS_NAME); +} + +static void name_lost_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + if(connection == NULL) + { + print_error("name_lost_cb call, Error: Failed to connect to dbus.\n"); + } + else + { + print_error("name_lost_cb call, Error: Failed to obtain bus name: %s.\n", XKBGENERAL_BUS_NAME); + } + + g_main_loop_quit(pLoop); +} + +void* run(void* para) +{ + /** Start the Main Event Loop which manages all available sources of events */ + g_main_loop_run( pLoop ); + + return ((void*)0); +} + +int thread_create(void) +{ + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if (err != 0) + { + + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; +} + +bool InitDBusCommunicationServer(void) +{ + bool bRet = TRUE; + + g_print("InitDBusCommunicationServer: Server started.\n"); + + /** create main loop, but do not start it. */ + pLoop = g_main_loop_new(NULL, FALSE); + + /** first step: connect to dbus */ + (void)g_bus_own_name(XKBGENERAL_BUS, + XKBGENERAL_BUS_NAME, + G_BUS_NAME_OWNER_FLAGS_NONE, + &bus_acquired_cb, + &name_acquired_cb, + &name_lost_cb, + NULL, + NULL); + + thread_create(); + + return bRet; +} + +bool DeinitDBusCommunicationServer(void) +{ + bool bRet = FALSE; + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} + +int main(void) +{ + InitDBusCommunicationServer(); + + sleep(100); + + DeinitDBusCommunicationServer(); + return 0; +} diff --git a/src/hardware/keyboard/xkbgeneral-dbus.h b/src/hardware/keyboard/xkbgeneral-dbus.h new file mode 100644 index 0000000..043509f --- /dev/null +++ b/src/hardware/keyboard/xkbgeneral-dbus.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 /* Bus define */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define XKBGENERAL_BUS G_BUS_TYPE_SESSION +#define XKBGENERAL_BUS_NAME "cn.kylinos.xkbgeneral" +#define XKBGENERAL_OBJECT_PATH "/cn/kylinos/xkbgeneral" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/hardware/keyboard/xkbgeneral-generated.c b/src/hardware/keyboard/xkbgeneral-generated.c new file mode 100644 index 0000000..b9c103c --- /dev/null +++ b/src/hardware/keyboard/xkbgeneral-generated.c @@ -0,0 +1,1273 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#ifdef G_OS_UNIX +# include +#endif + +typedef struct +{ + GDBusArgInfo parent_struct; + gboolean use_gvariant; +} _ExtendedGDBusArgInfo; + +typedef struct +{ + GDBusMethodInfo parent_struct; + const gchar *signal_name; + gboolean pass_fdlist; +} _ExtendedGDBusMethodInfo; + +typedef struct +{ + GDBusSignalInfo parent_struct; + const gchar *signal_name; +} _ExtendedGDBusSignalInfo; + +typedef struct +{ + GDBusPropertyInfo parent_struct; + const gchar *hyphen_name; + guint use_gvariant : 1; + guint emits_changed_signal : 1; +} _ExtendedGDBusPropertyInfo; + +typedef struct +{ + GDBusInterfaceInfo parent_struct; + const gchar *hyphen_name; +} _ExtendedGDBusInterfaceInfo; + +typedef struct +{ + const _ExtendedGDBusPropertyInfo *info; + guint prop_id; + GValue orig_value; /* the value before the change */ +} ChangedProperty; + +static void +_changed_property_free (ChangedProperty *data) +{ + g_value_unset (&data->orig_value); + g_free (data); +} + +static gboolean +_g_strv_equal0 (gchar **a, gchar **b) +{ + gboolean ret = FALSE; + guint n; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + if (g_strv_length (a) != g_strv_length (b)) + goto out; + for (n = 0; a[n] != NULL; n++) + if (g_strcmp0 (a[n], b[n]) != 0) + goto out; + ret = TRUE; +out: + return ret; +} + +static gboolean +_g_variant_equal0 (GVariant *a, GVariant *b) +{ + gboolean ret = FALSE; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + ret = g_variant_equal (a, b); +out: + return ret; +} + +G_GNUC_UNUSED static gboolean +_g_value_equal (const GValue *a, const GValue *b) +{ + gboolean ret = FALSE; + g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); + switch (G_VALUE_TYPE (a)) + { + case G_TYPE_BOOLEAN: + ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); + break; + case G_TYPE_UCHAR: + ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); + break; + case G_TYPE_INT: + ret = (g_value_get_int (a) == g_value_get_int (b)); + break; + case G_TYPE_UINT: + ret = (g_value_get_uint (a) == g_value_get_uint (b)); + break; + case G_TYPE_INT64: + ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); + break; + case G_TYPE_UINT64: + ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); + break; + case G_TYPE_DOUBLE: + { + /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ + gdouble da = g_value_get_double (a); + gdouble db = g_value_get_double (b); + ret = memcmp (&da, &db, sizeof (gdouble)) == 0; + } + break; + case G_TYPE_STRING: + ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); + break; + case G_TYPE_VARIANT: + ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); + break; + default: + if (G_VALUE_TYPE (a) == G_TYPE_STRV) + ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); + else + g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); + break; + } + return ret; +} + +/* ------------------------------------------------------------------------ + * Code for interface cn.kylinos.xkbgeneral + * ------------------------------------------------------------------------ + */ + +/** + * SECTION:Xkbgeneral + * @title: Xkbgeneral + * @short_description: Generated C code for the cn.kylinos.xkbgeneral D-Bus interface + * + * This section contains code for working with the cn.kylinos.xkbgeneral D-Bus interface in C. + */ + +/* ---- Introspection data for cn.kylinos.xkbgeneral ---- */ + +static const _ExtendedGDBusArgInfo _xkbgeneral_method_info_transfer_bool_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(sb)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _xkbgeneral_method_info_transfer_bool_value_IN_ARG_pointers[] = +{ + &_xkbgeneral_method_info_transfer_bool_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _xkbgeneral_method_info_transfer_bool_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _xkbgeneral_method_info_transfer_bool_value_OUT_ARG_pointers[] = +{ + &_xkbgeneral_method_info_transfer_bool_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _xkbgeneral_method_info_transfer_bool_value = +{ + { + -1, + (gchar *) "TransferBoolValue", + (GDBusArgInfo **) &_xkbgeneral_method_info_transfer_bool_value_IN_ARG_pointers, + (GDBusArgInfo **) &_xkbgeneral_method_info_transfer_bool_value_OUT_ARG_pointers, + NULL + }, + "handle-transfer-bool-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _xkbgeneral_method_info_get_bool_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "s", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _xkbgeneral_method_info_get_bool_value_IN_ARG_pointers[] = +{ + &_xkbgeneral_method_info_get_bool_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _xkbgeneral_method_info_get_bool_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _xkbgeneral_method_info_get_bool_value_OUT_ARG_pointers[] = +{ + &_xkbgeneral_method_info_get_bool_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _xkbgeneral_method_info_get_bool_value = +{ + { + -1, + (gchar *) "GetBoolValue", + (GDBusArgInfo **) &_xkbgeneral_method_info_get_bool_value_IN_ARG_pointers, + (GDBusArgInfo **) &_xkbgeneral_method_info_get_bool_value_OUT_ARG_pointers, + NULL + }, + "handle-get-bool-value", + FALSE +}; + +static const GDBusMethodInfo * const _xkbgeneral_method_info_pointers[] = +{ + &_xkbgeneral_method_info_transfer_bool_value.parent_struct, + &_xkbgeneral_method_info_get_bool_value.parent_struct, + NULL +}; + +static const _ExtendedGDBusInterfaceInfo _xkbgeneral_interface_info = +{ + { + -1, + (gchar *) "cn.kylinos.xkbgeneral", + (GDBusMethodInfo **) &_xkbgeneral_method_info_pointers, + NULL, + NULL, + NULL + }, + "xkbgeneral", +}; + + +/** + * xkbgeneral_interface_info: + * + * Gets a machine-readable description of the cn.kylinos.xkbgeneral D-Bus interface. + * + * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. + */ +GDBusInterfaceInfo * +xkbgeneral_interface_info (void) +{ + return (GDBusInterfaceInfo *) &_xkbgeneral_interface_info.parent_struct; +} + +/** + * xkbgeneral_override_properties: + * @klass: The class structure for a #GObject derived class. + * @property_id_begin: The property id to assign to the first overridden property. + * + * Overrides all #GObject properties in the #Xkbgeneral interface for a concrete class. + * The properties are overridden in the order they are defined. + * + * Returns: The last property id. + */ +guint +xkbgeneral_override_properties (GObjectClass *klass, guint property_id_begin) +{ + return property_id_begin - 1; +} + + + +/** + * Xkbgeneral: + * + * Abstract interface type for the D-Bus interface cn.kylinos.xkbgeneral. + */ + +/** + * XkbgeneralIface: + * @parent_iface: The parent interface. + * @handle_get_bool_value: Handler for the #Xkbgeneral::handle-get-bool-value signal. + * @handle_transfer_bool_value: Handler for the #Xkbgeneral::handle-transfer-bool-value signal. + * + * Virtual table for the D-Bus interface cn.kylinos.xkbgeneral. + */ + +typedef XkbgeneralIface XkbgeneralInterface; +G_DEFINE_INTERFACE (Xkbgeneral, xkbgeneral, G_TYPE_OBJECT) + +static void +xkbgeneral_default_init (XkbgeneralIface *iface) +{ + /* GObject signals for incoming D-Bus method calls: */ + /** + * Xkbgeneral::handle-transfer-bool-value: + * @object: A #Xkbgeneral. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferBoolValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call xkbgeneral_complete_transfer_bool_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-bool-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (XkbgeneralIface, handle_transfer_bool_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Xkbgeneral::handle-get-bool-value: + * @object: A #Xkbgeneral. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the GetBoolValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call xkbgeneral_complete_get_bool_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-get-bool-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (XkbgeneralIface, handle_get_bool_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_STRING); + +} + +/** + * xkbgeneral_call_transfer_bool_value: + * @proxy: A #XkbgeneralProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferBoolValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call xkbgeneral_call_transfer_bool_value_finish() to get the result of the operation. + * + * See xkbgeneral_call_transfer_bool_value_sync() for the synchronous, blocking version of this method. + */ +void +xkbgeneral_call_transfer_bool_value ( + Xkbgeneral *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * xkbgeneral_call_transfer_bool_value_finish: + * @proxy: A #XkbgeneralProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to xkbgeneral_call_transfer_bool_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with xkbgeneral_call_transfer_bool_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +xkbgeneral_call_transfer_bool_value_finish ( + Xkbgeneral *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * xkbgeneral_call_transfer_bool_value_sync: + * @proxy: A #XkbgeneralProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferBoolValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See xkbgeneral_call_transfer_bool_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +xkbgeneral_call_transfer_bool_value_sync ( + Xkbgeneral *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * xkbgeneral_call_get_bool_value: + * @proxy: A #XkbgeneralProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the GetBoolValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call xkbgeneral_call_get_bool_value_finish() to get the result of the operation. + * + * See xkbgeneral_call_get_bool_value_sync() for the synchronous, blocking version of this method. + */ +void +xkbgeneral_call_get_bool_value ( + Xkbgeneral *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "GetBoolValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * xkbgeneral_call_get_bool_value_finish: + * @proxy: A #XkbgeneralProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to xkbgeneral_call_get_bool_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with xkbgeneral_call_get_bool_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +xkbgeneral_call_get_bool_value_finish ( + Xkbgeneral *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * xkbgeneral_call_get_bool_value_sync: + * @proxy: A #XkbgeneralProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the GetBoolValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See xkbgeneral_call_get_bool_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +xkbgeneral_call_get_bool_value_sync ( + Xkbgeneral *proxy, + const gchar *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "GetBoolValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * xkbgeneral_complete_transfer_bool_value: + * @object: A #Xkbgeneral. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the TransferBoolValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +xkbgeneral_complete_transfer_bool_value ( + Xkbgeneral *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/** + * xkbgeneral_complete_get_bool_value: + * @object: A #Xkbgeneral. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the GetBoolValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +xkbgeneral_complete_get_bool_value ( + Xkbgeneral *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/* ------------------------------------------------------------------------ */ + +/** + * XkbgeneralProxy: + * + * The #XkbgeneralProxy structure contains only private data and should only be accessed using the provided API. + */ + +/** + * XkbgeneralProxyClass: + * @parent_class: The parent class. + * + * Class structure for #XkbgeneralProxy. + */ + +struct _XkbgeneralProxyPrivate +{ + GData *qdata; +}; + +static void xkbgeneral_proxy_iface_init (XkbgeneralIface *iface); + +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (XkbgeneralProxy, xkbgeneral_proxy, G_TYPE_DBUS_PROXY, + G_ADD_PRIVATE (XkbgeneralProxy) + G_IMPLEMENT_INTERFACE (TYPE_XKBGENERAL, xkbgeneral_proxy_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (XkbgeneralProxy, xkbgeneral_proxy, G_TYPE_DBUS_PROXY, + G_IMPLEMENT_INTERFACE (TYPE_XKBGENERAL, xkbgeneral_proxy_iface_init)) + +#endif +static void +xkbgeneral_proxy_finalize (GObject *object) +{ + XkbgeneralProxy *proxy = XKBGENERAL_PROXY (object); + g_datalist_clear (&proxy->priv->qdata); + G_OBJECT_CLASS (xkbgeneral_proxy_parent_class)->finalize (object); +} + +static void +xkbgeneral_proxy_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +xkbgeneral_proxy_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +xkbgeneral_proxy_g_signal (GDBusProxy *proxy, + const gchar *sender_name G_GNUC_UNUSED, + const gchar *signal_name, + GVariant *parameters) +{ + _ExtendedGDBusSignalInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + gsize n; + guint signal_id; + info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_xkbgeneral_interface_info.parent_struct, signal_name); + if (info == NULL) + return; + num_params = g_variant_n_children (parameters); + paramv = g_new0 (GValue, num_params + 1); + g_value_init (¶mv[0], TYPE_XKBGENERAL); + g_value_set_object (¶mv[0], proxy); + g_variant_iter_init (&iter, parameters); + n = 1; + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_XKBGENERAL); + g_signal_emitv (paramv, signal_id, 0, NULL); + for (n = 0; n < num_params + 1; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static void +xkbgeneral_proxy_g_properties_changed (GDBusProxy *_proxy, + GVariant *changed_properties, + const gchar *const *invalidated_properties) +{ + XkbgeneralProxy *proxy = XKBGENERAL_PROXY (_proxy); + guint n; + const gchar *key; + GVariantIter *iter; + _ExtendedGDBusPropertyInfo *info; + g_variant_get (changed_properties, "a{sv}", &iter); + while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_xkbgeneral_interface_info.parent_struct, key); + g_datalist_remove_data (&proxy->priv->qdata, key); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } + g_variant_iter_free (iter); + for (n = 0; invalidated_properties[n] != NULL; n++) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_xkbgeneral_interface_info.parent_struct, invalidated_properties[n]); + g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } +} + +static void +xkbgeneral_proxy_init (XkbgeneralProxy *proxy) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + proxy->priv = xkbgeneral_proxy_get_instance_private (proxy); +#else + proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, TYPE_XKBGENERAL_PROXY, XkbgeneralProxyPrivate); +#endif + + g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), xkbgeneral_interface_info ()); +} + +static void +xkbgeneral_proxy_class_init (XkbgeneralProxyClass *klass) +{ + GObjectClass *gobject_class; + GDBusProxyClass *proxy_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = xkbgeneral_proxy_finalize; + gobject_class->get_property = xkbgeneral_proxy_get_property; + gobject_class->set_property = xkbgeneral_proxy_set_property; + + proxy_class = G_DBUS_PROXY_CLASS (klass); + proxy_class->g_signal = xkbgeneral_proxy_g_signal; + proxy_class->g_properties_changed = xkbgeneral_proxy_g_properties_changed; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (XkbgeneralProxyPrivate)); +#endif +} + +static void +xkbgeneral_proxy_iface_init (XkbgeneralIface *iface) +{ +} + +/** + * xkbgeneral_proxy_new: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Asynchronously creates a proxy for the D-Bus interface cn.kylinos.xkbgeneral. See g_dbus_proxy_new() for more details. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call xkbgeneral_proxy_new_finish() to get the result of the operation. + * + * See xkbgeneral_proxy_new_sync() for the synchronous, blocking version of this constructor. + */ +void +xkbgeneral_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_XKBGENERAL_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.xkbgeneral", NULL); +} + +/** + * xkbgeneral_proxy_new_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to xkbgeneral_proxy_new(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with xkbgeneral_proxy_new(). + * + * Returns: (transfer full) (type XkbgeneralProxy): The constructed proxy object or %NULL if @error is set. + */ +Xkbgeneral * +xkbgeneral_proxy_new_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return XKBGENERAL (ret); + else + return NULL; +} + +/** + * xkbgeneral_proxy_new_sync: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Synchronously creates a proxy for the D-Bus interface cn.kylinos.xkbgeneral. See g_dbus_proxy_new_sync() for more details. + * + * The calling thread is blocked until a reply is received. + * + * See xkbgeneral_proxy_new() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type XkbgeneralProxy): The constructed proxy object or %NULL if @error is set. + */ +Xkbgeneral * +xkbgeneral_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_XKBGENERAL_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.xkbgeneral", NULL); + if (ret != NULL) + return XKBGENERAL (ret); + else + return NULL; +} + + +/** + * xkbgeneral_proxy_new_for_bus: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Like xkbgeneral_proxy_new() but takes a #GBusType instead of a #GDBusConnection. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call xkbgeneral_proxy_new_for_bus_finish() to get the result of the operation. + * + * See xkbgeneral_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. + */ +void +xkbgeneral_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_XKBGENERAL_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.xkbgeneral", NULL); +} + +/** + * xkbgeneral_proxy_new_for_bus_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to xkbgeneral_proxy_new_for_bus(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with xkbgeneral_proxy_new_for_bus(). + * + * Returns: (transfer full) (type XkbgeneralProxy): The constructed proxy object or %NULL if @error is set. + */ +Xkbgeneral * +xkbgeneral_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return XKBGENERAL (ret); + else + return NULL; +} + +/** + * xkbgeneral_proxy_new_for_bus_sync: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Like xkbgeneral_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. + * + * The calling thread is blocked until a reply is received. + * + * See xkbgeneral_proxy_new_for_bus() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type XkbgeneralProxy): The constructed proxy object or %NULL if @error is set. + */ +Xkbgeneral * +xkbgeneral_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_XKBGENERAL_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.xkbgeneral", NULL); + if (ret != NULL) + return XKBGENERAL (ret); + else + return NULL; +} + + +/* ------------------------------------------------------------------------ */ + +/** + * XkbgeneralSkeleton: + * + * The #XkbgeneralSkeleton structure contains only private data and should only be accessed using the provided API. + */ + +/** + * XkbgeneralSkeletonClass: + * @parent_class: The parent class. + * + * Class structure for #XkbgeneralSkeleton. + */ + +struct _XkbgeneralSkeletonPrivate +{ + GValue *properties; + GList *changed_properties; + GSource *changed_properties_idle_source; + GMainContext *context; + GMutex lock; +}; + +static void +_xkbgeneral_skeleton_handle_method_call ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name, + const gchar *method_name, + GVariant *parameters, + GDBusMethodInvocation *invocation, + gpointer user_data) +{ + XkbgeneralSkeleton *skeleton = XKBGENERAL_SKELETON (user_data); + _ExtendedGDBusMethodInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + guint num_extra; + gsize n; + guint signal_id; + GValue return_value = G_VALUE_INIT; + info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); + g_assert (info != NULL); + num_params = g_variant_n_children (parameters); + num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); + n = 0; + g_value_init (¶mv[n], TYPE_XKBGENERAL); + g_value_set_object (¶mv[n++], skeleton); + g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); + g_value_set_object (¶mv[n++], invocation); + if (info->pass_fdlist) + { +#ifdef G_OS_UNIX + g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); + g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); +#else + g_assert_not_reached (); +#endif + } + g_variant_iter_init (&iter, parameters); + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_XKBGENERAL); + g_value_init (&return_value, G_TYPE_BOOLEAN); + g_signal_emitv (paramv, signal_id, 0, &return_value); + if (!g_value_get_boolean (&return_value)) + g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); + g_value_unset (&return_value); + for (n = 0; n < num_params + num_extra; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static GVariant * +_xkbgeneral_skeleton_handle_get_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GError **error, + gpointer user_data) +{ + XkbgeneralSkeleton *skeleton = XKBGENERAL_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + GVariant *ret; + ret = NULL; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_xkbgeneral_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + g_value_init (&value, pspec->value_type); + g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); + ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); + g_value_unset (&value); + } + return ret; +} + +static gboolean +_xkbgeneral_skeleton_handle_set_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GVariant *variant, + GError **error, + gpointer user_data) +{ + XkbgeneralSkeleton *skeleton = XKBGENERAL_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + gboolean ret; + ret = FALSE; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_xkbgeneral_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + if (info->use_gvariant) + g_value_set_variant (&value, variant); + else + g_dbus_gvariant_to_gvalue (variant, &value); + g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); + g_value_unset (&value); + ret = TRUE; + } + return ret; +} + +static const GDBusInterfaceVTable _xkbgeneral_skeleton_vtable = +{ + _xkbgeneral_skeleton_handle_method_call, + _xkbgeneral_skeleton_handle_get_property, + _xkbgeneral_skeleton_handle_set_property, + {NULL} +}; + +static GDBusInterfaceInfo * +xkbgeneral_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return xkbgeneral_interface_info (); +} + +static GDBusInterfaceVTable * +xkbgeneral_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return (GDBusInterfaceVTable *) &_xkbgeneral_skeleton_vtable; +} + +static GVariant * +xkbgeneral_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) +{ + XkbgeneralSkeleton *skeleton = XKBGENERAL_SKELETON (_skeleton); + + GVariantBuilder builder; + guint n; + g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); + if (_xkbgeneral_interface_info.parent_struct.properties == NULL) + goto out; + for (n = 0; _xkbgeneral_interface_info.parent_struct.properties[n] != NULL; n++) + { + GDBusPropertyInfo *info = _xkbgeneral_interface_info.parent_struct.properties[n]; + if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) + { + GVariant *value; + value = _xkbgeneral_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "cn.kylinos.xkbgeneral", info->name, NULL, skeleton); + if (value != NULL) + { + g_variant_take_ref (value); + g_variant_builder_add (&builder, "{sv}", info->name, value); + g_variant_unref (value); + } + } + } +out: + return g_variant_builder_end (&builder); +} + +static void +xkbgeneral_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) +{ +} + +static void xkbgeneral_skeleton_iface_init (XkbgeneralIface *iface); +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (XkbgeneralSkeleton, xkbgeneral_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_ADD_PRIVATE (XkbgeneralSkeleton) + G_IMPLEMENT_INTERFACE (TYPE_XKBGENERAL, xkbgeneral_skeleton_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (XkbgeneralSkeleton, xkbgeneral_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_IMPLEMENT_INTERFACE (TYPE_XKBGENERAL, xkbgeneral_skeleton_iface_init)) + +#endif +static void +xkbgeneral_skeleton_finalize (GObject *object) +{ + XkbgeneralSkeleton *skeleton = XKBGENERAL_SKELETON (object); + g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); + if (skeleton->priv->changed_properties_idle_source != NULL) + g_source_destroy (skeleton->priv->changed_properties_idle_source); + g_main_context_unref (skeleton->priv->context); + g_mutex_clear (&skeleton->priv->lock); + G_OBJECT_CLASS (xkbgeneral_skeleton_parent_class)->finalize (object); +} + +static void +xkbgeneral_skeleton_init (XkbgeneralSkeleton *skeleton) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + skeleton->priv = xkbgeneral_skeleton_get_instance_private (skeleton); +#else + skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_XKBGENERAL_SKELETON, XkbgeneralSkeletonPrivate); +#endif + + g_mutex_init (&skeleton->priv->lock); + skeleton->priv->context = g_main_context_ref_thread_default (); +} + +static void +xkbgeneral_skeleton_class_init (XkbgeneralSkeletonClass *klass) +{ + GObjectClass *gobject_class; + GDBusInterfaceSkeletonClass *skeleton_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = xkbgeneral_skeleton_finalize; + + skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); + skeleton_class->get_info = xkbgeneral_skeleton_dbus_interface_get_info; + skeleton_class->get_properties = xkbgeneral_skeleton_dbus_interface_get_properties; + skeleton_class->flush = xkbgeneral_skeleton_dbus_interface_flush; + skeleton_class->get_vtable = xkbgeneral_skeleton_dbus_interface_get_vtable; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (XkbgeneralSkeletonPrivate)); +#endif +} + +static void +xkbgeneral_skeleton_iface_init (XkbgeneralIface *iface) +{ +} + +/** + * xkbgeneral_skeleton_new: + * + * Creates a skeleton object for the D-Bus interface cn.kylinos.xkbgeneral. + * + * Returns: (transfer full) (type XkbgeneralSkeleton): The skeleton object. + */ +Xkbgeneral * +xkbgeneral_skeleton_new (void) +{ + return XKBGENERAL (g_object_new (TYPE_XKBGENERAL_SKELETON, NULL)); +} + diff --git a/src/hardware/keyboard/xkbgeneral-generated.h b/src/hardware/keyboard/xkbgeneral-generated.h new file mode 100644 index 0000000..f06ac80 --- /dev/null +++ b/src/hardware/keyboard/xkbgeneral-generated.h @@ -0,0 +1,223 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +G_BEGIN_DECLS + + +/* ------------------------------------------------------------------------ */ +/* Declarations for cn.kylinos.xkbgeneral */ + +#define TYPE_XKBGENERAL (xkbgeneral_get_type ()) +#define XKBGENERAL(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_XKBGENERAL, Xkbgeneral)) +#define IS_XKBGENERAL(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_XKBGENERAL)) +#define XKBGENERAL_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), TYPE_XKBGENERAL, XkbgeneralIface)) + +struct _Xkbgeneral; +typedef struct _Xkbgeneral Xkbgeneral; +typedef struct _XkbgeneralIface XkbgeneralIface; + +struct _XkbgeneralIface +{ + GTypeInterface parent_iface; + + gboolean (*handle_get_bool_value) ( + Xkbgeneral *object, + GDBusMethodInvocation *invocation, + const gchar *arg_InArg); + + gboolean (*handle_transfer_bool_value) ( + Xkbgeneral *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + +}; + +GType xkbgeneral_get_type (void) G_GNUC_CONST; + +GDBusInterfaceInfo *xkbgeneral_interface_info (void); +guint xkbgeneral_override_properties (GObjectClass *klass, guint property_id_begin); + + +/* D-Bus method call completion functions: */ +void xkbgeneral_complete_transfer_bool_value ( + Xkbgeneral *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + +void xkbgeneral_complete_get_bool_value ( + Xkbgeneral *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + + + +/* D-Bus method calls: */ +void xkbgeneral_call_transfer_bool_value ( + Xkbgeneral *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean xkbgeneral_call_transfer_bool_value_finish ( + Xkbgeneral *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean xkbgeneral_call_transfer_bool_value_sync ( + Xkbgeneral *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + +void xkbgeneral_call_get_bool_value ( + Xkbgeneral *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean xkbgeneral_call_get_bool_value_finish ( + Xkbgeneral *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean xkbgeneral_call_get_bool_value_sync ( + Xkbgeneral *proxy, + const gchar *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + + + +/* ---- */ + +#define TYPE_XKBGENERAL_PROXY (xkbgeneral_proxy_get_type ()) +#define XKBGENERAL_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_XKBGENERAL_PROXY, XkbgeneralProxy)) +#define XKBGENERAL_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_XKBGENERAL_PROXY, XkbgeneralProxyClass)) +#define XKBGENERAL_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_XKBGENERAL_PROXY, XkbgeneralProxyClass)) +#define IS_XKBGENERAL_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_XKBGENERAL_PROXY)) +#define IS_XKBGENERAL_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_XKBGENERAL_PROXY)) + +typedef struct _XkbgeneralProxy XkbgeneralProxy; +typedef struct _XkbgeneralProxyClass XkbgeneralProxyClass; +typedef struct _XkbgeneralProxyPrivate XkbgeneralProxyPrivate; + +struct _XkbgeneralProxy +{ + /*< private >*/ + GDBusProxy parent_instance; + XkbgeneralProxyPrivate *priv; +}; + +struct _XkbgeneralProxyClass +{ + GDBusProxyClass parent_class; +}; + +GType xkbgeneral_proxy_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (XkbgeneralProxy, g_object_unref) +#endif + +void xkbgeneral_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Xkbgeneral *xkbgeneral_proxy_new_finish ( + GAsyncResult *res, + GError **error); +Xkbgeneral *xkbgeneral_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + +void xkbgeneral_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Xkbgeneral *xkbgeneral_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error); +Xkbgeneral *xkbgeneral_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + + +/* ---- */ + +#define TYPE_XKBGENERAL_SKELETON (xkbgeneral_skeleton_get_type ()) +#define XKBGENERAL_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_XKBGENERAL_SKELETON, XkbgeneralSkeleton)) +#define XKBGENERAL_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_XKBGENERAL_SKELETON, XkbgeneralSkeletonClass)) +#define XKBGENERAL_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_XKBGENERAL_SKELETON, XkbgeneralSkeletonClass)) +#define IS_XKBGENERAL_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_XKBGENERAL_SKELETON)) +#define IS_XKBGENERAL_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_XKBGENERAL_SKELETON)) + +typedef struct _XkbgeneralSkeleton XkbgeneralSkeleton; +typedef struct _XkbgeneralSkeletonClass XkbgeneralSkeletonClass; +typedef struct _XkbgeneralSkeletonPrivate XkbgeneralSkeletonPrivate; + +struct _XkbgeneralSkeleton +{ + /*< private >*/ + GDBusInterfaceSkeleton parent_instance; + XkbgeneralSkeletonPrivate *priv; +}; + +struct _XkbgeneralSkeletonClass +{ + GDBusInterfaceSkeletonClass parent_class; +}; + +GType xkbgeneral_skeleton_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (XkbgeneralSkeleton, g_object_unref) +#endif + +Xkbgeneral *xkbgeneral_skeleton_new (void); + + +G_END_DECLS + +#endif /* __XKBGENERAL_GENERATED_H__ */ diff --git a/src/hardware/mouse/Makefile.am b/src/hardware/mouse/Makefile.am new file mode 100644 index 0000000..a322d81 --- /dev/null +++ b/src/hardware/mouse/Makefile.am @@ -0,0 +1,55 @@ +COMM_PRINT= -L$(top_srcdir)/src/common -lukui-print +COMM_GSETTINGS= -L$(top_srcdir)/src/common -lukui-gsettings + +#generate the .c and .h file which used by client and server side by XML file +#$(top_srcdir) represents the top-level directory of the project +DESC_XML = $(top_srcdir)/data/cn.kylinos.mouse.xml +GENERATED_CH = mouse-generated + +mouse-generated.h mouse-generated.c: $(DESC_XML) + gdbus-codegen --interface-prefix cn.kylinos. --generate-c-code $(GENERATED_CH) $(DESC_XML) + +#Generata binary file +lib_LTLIBRARIES = libukui-mouseclient.la + +#gcc -wall: displays all the errors and warning information when compiling +#gcc -g: add the debugging code when compiling +COMM_CFS = -Wall -g + +#Add the dependent source file for libmouseclient.la +#mouse-generated.c must be front of kylin-mouse-interface.c +libukui_mouseclient_la_SOURCES = mouse-generated.c kylin-mouse-interface.c \ + $(NULL) + +#The header files that need to be installed +include_HEADERS= kylin-mouse-interface.h \ + $(NULL) + +#Additional C compiler flags +libukui_mouseclient_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_mouseclient_la_LDFLAGS= $(COMM_PRINT) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Generata binary file +bin_PROGRAMS = ukui-mouseserver + +#Add the dependent source file for mouseserver +ukui_mouseserver_SOURCES = \ + mouse-generated.h mouse-generated.c \ + kylin-mouse-server.c \ + $(NULL) + +#Additional C compiler flags +ukui_mouseserver_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +ukui_mouseserver_LDFLAGS= $(COMM_PRINT) $(COMM_GSETTINGS) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) diff --git a/src/hardware/mouse/kylin-mouse-interface.c b/src/hardware/mouse/kylin-mouse-interface.c new file mode 100644 index 0000000..f8621bd --- /dev/null +++ b/src/hardware/mouse/kylin-mouse-interface.c @@ -0,0 +1,390 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#define LH "left-handed" +#define MA "motion-acceleration" +#define MT "motion-threshold" +#define DT "drag-threshold" +#define DC "double-click" +#define MBE "middle-button-enabled" +#define LP "locate-pointer" +#define CF "cursor-font" +#define CT "cursor-theme" +#define CS "cursor-size" + +static GMainLoop *pLoop = NULL; +static GDBusConnection *pConnection = NULL; +static Mouse *pProxy = NULL; + +bool kylin_hardware_mouse_set_lefthanded(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=LH; + gboolean retv; + arg=g_variant_new("(sb)", key, in_arg); + mouse_call_transfer_bool_value_sync(pProxy, arg, &retv,NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_mouse_lefthanded. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +bool kylin_hardware_mouse_get_lefthanded() +{ + gchar *key=LH; + gboolean value; + GError* pError=NULL; + mouse_call_get_bool_value_sync(pProxy, key,&value, NULL, &pError); + return value; + +} + + +bool kylin_hardware_mouse_set_motionacceleration(const double in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=MA; + gboolean retv; + arg=g_variant_new("(sd)",key,in_arg); + mouse_call_transfer_double_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_mouse_motionacceleration. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +double kylin_hardware_mouse_get_motionacceleration() +{ + gchar *key=MA; + double value; + GError* pError=NULL; + mouse_call_get_double_value_sync(pProxy, key,&value, NULL, &pError); + return value; +} + +bool kylin_hardware_mouse_set_motionthreshold(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=MT; + gboolean retv; + arg=g_variant_new("(si)",key,in_arg); + mouse_call_transfer_int_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_mouse_motionthreshold. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; + +} + +int kylin_hardware_mouse_get_motionthreshold() +{ + gchar *key=MT; + int value; + GError* pError=NULL; + mouse_call_get_int_value_sync(pProxy, key,&value, NULL, &pError); + return value; +} + +bool kylin_hardware_mouse_set_dragthreshold(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=DT; + gboolean retv; + arg=g_variant_new("(si)",key,in_arg); + mouse_call_transfer_int_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_mouse_dragthreshold. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +int kylin_hardware_mouse_get_dragthreshold() +{ + gchar *key=DT; + int value; + GError* pError=NULL; + mouse_call_get_int_value_sync(pProxy, key,&value, NULL, &pError); + return value; + +} + +bool kylin_hardware_mouse_set_doubleclick(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=DC; + gboolean retv; + arg=g_variant_new("(si)",key,in_arg); + mouse_call_transfer_int_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_mouse_doubleclick. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +int kylin_hardware_mouse_get_doubleclick() +{ + gchar *key=DC; + int value; + GError* pError=NULL; + mouse_call_get_int_value_sync(pProxy, key,&value, NULL, &pError); + return value; +} + +bool kylin_hardware_mouse_set_middlebuttonenabled(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=MBE; + gboolean retv; + arg=g_variant_new("(sb)", key, in_arg); + mouse_call_transfer_bool_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_mouse_middlebuttonenabled. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +bool kylin_hardware_mouse_get_middlebuttonenabled() +{ + gchar *key=MBE; + gboolean value; + GError* pError=NULL; + mouse_call_get_bool_value_sync(pProxy, key,&value, NULL, &pError); + return value; + +} + +bool kylin_hardware_mouse_set_locatepointer(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=LP; + gboolean retv; + arg=g_variant_new("(sb)", key, in_arg); + mouse_call_transfer_bool_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_mouse_locatepointer. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +bool kylin_hardware_mouse_get_locatepointer() +{ + gchar *key=LP; + gboolean value; + GError* pError=NULL; + mouse_call_get_bool_value_sync(pProxy, key,&value, NULL, &pError); + return value; + +} + +bool kylin_hardware_mouse_set_cursorfont(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=CF; + gboolean retv; + arg=g_variant_new("(ss)", key, in_arg); + mouse_call_transfer_string_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_mouse_cursorfont. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +char *kylin_hardware_mouse_get_cursorfont() +{ + gchar *key=CF; + char *value; + GError* pError=NULL; + mouse_call_get_string_value_sync(pProxy, key,&value, NULL, &pError); + return value; + +} + +bool kylin_hardware_mouse_set_cursortheme(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=CT; + gboolean retv; + arg=g_variant_new("(ss)", key, in_arg); + mouse_call_transfer_string_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_mouse_cursortheme. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +char *kylin_hardware_mouse_get_cursortheme() +{ + gchar *key=CT; + char *value; + GError* pError=NULL; + mouse_call_get_string_value_sync(pProxy, key,&value, NULL, &pError); + return value; +} + +bool kylin_hardware_mouse_set_cursorsize(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=CS; + gboolean retv; + arg=g_variant_new("(si)",key,in_arg); + mouse_call_transfer_int_value_sync(pProxy, arg, &retv, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_mouse_cursorsize. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return retv; +} + +int kylin_hardware_mouse_get_cursorsize() +{ + gchar *key=CS; + int value; + GError* pError=NULL; + mouse_call_get_int_value_sync(pProxy, key,&value, NULL, &pError); + return value; +} + +void *run(void* arg) +{ + /** start the main event loop which manages all available sources of events */ + g_main_loop_run(pLoop); + + return ((void*)0); +} + +int thread_create(void) + { + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if(0 != err){ + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; + } + +bool InitDBusMouse(void) + { + bool bRet = TRUE; + GError *pConnError = NULL; + GError *pProxyError = NULL; + + do{ + bRet = TRUE; + pLoop = g_main_loop_new(NULL, FALSE); /** create main loop, but do not start it.*/ + + /** First step: get a connection */ + pConnection = g_bus_get_sync(MOUSE_BUS, NULL, &pConnError); + + if (NULL == pConnError){ + /** Second step: try to get a connection to the given bus.*/ + pProxy =mouse_proxy_new_sync(pConnection, + G_DBUS_PROXY_FLAGS_NONE, + MOUSE_BUS_NAME, + MOUSE_OBJECT_PATH, + NULL, + &pProxyError); + if (0 == pProxy){ + print_error("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message); + g_error_free(pProxyError); + bRet = FALSE; + } + + + } + else{ + print_error("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message); + g_error_free(pConnError); + bRet = FALSE; + } + }while(FALSE == bRet); + + thread_create(); + + return bRet; + } + +bool DeInitDBusMouse(void) +{ + bool bRet = FALSE; + + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} diff --git a/src/hardware/mouse/kylin-mouse-interface.h b/src/hardware/mouse/kylin-mouse-interface.h new file mode 100644 index 0000000..133033c --- /dev/null +++ b/src/hardware/mouse/kylin-mouse-interface.h @@ -0,0 +1,186 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Initialize the DBus Communication. + */ +bool InitDBusMouse(void); + +/** + * Delete the DBus Communication. + */ +bool DeInitDBusMouse(void); + +/** + * Swap left and right mouse buttons for left-handed mice. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_mouse_set_lefthanded(const bool in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +bool kylin_hardware_mouse_get_lefthanded(); + +/** + * Set acceleration multiplier for mouse motion. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_mouse_set_motionacceleration(const double in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +double kylin_hardware_mouse_get_motionacceleration(); + +/** + * Set the distance in pixels the pointer must move before accelerated mouse motion is activated. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_mouse_set_motionthreshold(const int in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +int kylin_hardware_mouse_get_motionthreshold(); + +/** + * Set the distance before a drag is started. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_mouse_set_dragthreshold(const int in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +int kylin_hardware_mouse_get_dragthreshold(); + +/** + * Set the length of a double click. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_mouse_set_doubleclick(const int in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +int kylin_hardware_mouse_get_doubleclick(); + +/** + * Enable middle mouse button emulation through simultaneous left and right button click. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_mouse_set_middlebuttonenabled(const bool in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +bool kylin_hardware_mouse_get_middlebuttonenabled(); + +/** + * Highlight the current location of the pointer when the Control key is pressed and released. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_mouse_set_locatepointer(const bool in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +bool kylin_hardware_mouse_get_locatepointer(); + +/** + * Set font name of the cursor. If unset, the default font is used. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_mouse_set_cursorfont(const char *in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +char *kylin_hardware_mouse_get_cursorfont(); + +/** + * Set cursor theme name. Used only by Xservers that support Xcursor,such as XFree86 4.3 and later. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_mouse_set_cursortheme(const char *in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +char *kylin_hardware_mouse_get_cursortheme(); + +/** + * Set the size of the cursor referenced by cursor_theme. + * @param in_arg is the value you want to set. + * @return true if setting successfully. + */ +bool kylin_hardware_mouse_set_cursorsize(const int in_arg); + +/** + * Get the value of key. + * @return the value of key. + */ +int kylin_hardware_mouse_get_cursorsize(); + +#ifdef __cplusplus +} +#endif + +#endif + + + + + + + + + + + + + diff --git a/src/hardware/mouse/kylin-mouse-server.c b/src/hardware/mouse/kylin-mouse-server.c new file mode 100644 index 0000000..5777e2d --- /dev/null +++ b/src/hardware/mouse/kylin-mouse-server.c @@ -0,0 +1,296 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include "mouse-dbus.h" +#include "src/common/kylin-print.h" +#include "mouse-generated.h" +#include + +#define schemaID "org.mate.peripherals-mouse" + +static GMainLoop *pLoop = NULL; +static Mouse *pSkeleton = NULL; + +static gboolean kylin_set_bool(Mouse* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gboolean value; + gint i; + g_variant_get(in_arg, "(sb)", &key, &value); + if(value==false)i=0; + else i=1; + + GSettings *setting=g_settings_new(schemaID); + gboolean retv=g_settings_set_boolean(setting,key,value); + g_object_unref(setting); + g_settings_sync(); + + mouse_complete_transfer_bool_value(object, invocation, retv); + + print_info("(%s, %d)\n", key, i); + + return TRUE; +} + +static gboolean kylin_get_bool(Mouse *object, + GDBusMethodInvocation* invocation, + char *in_arg, + gpointer user_data) +{ + GSettings *setting=g_settings_new(schemaID); + gboolean ret=g_settings_get_boolean(setting, in_arg); + g_object_unref(setting); + mouse_complete_get_bool_value(object, invocation, ret); + return TRUE; +} + +static gboolean kylin_set_double(Mouse* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + double value; + g_variant_get(in_arg, "(sd)", &key, &value); + + GSettings *setting=g_settings_new(schemaID); + gboolean retv=g_settings_set_double(setting,key,value); + g_object_unref(setting); + g_settings_sync(); + + mouse_complete_transfer_double_value(object, invocation, retv); + + print_info("(%s, %f)\n", key, value); + + return TRUE; +} + +static gboolean kylin_get_double(Mouse *object, + GDBusMethodInvocation* invocation, + char *in_arg, + gpointer user_data) +{ + GSettings *setting=g_settings_new(schemaID); + gdouble ret=g_settings_get_double(setting, in_arg); + g_object_unref(setting); + mouse_complete_get_double_value(object, invocation, ret); + return TRUE; +} + +static gboolean kylin_set_int(Mouse* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gint value; + g_variant_get(in_arg, "(si)", &key, &value); + + GSettings *setting=g_settings_new(schemaID); + gboolean retv=g_settings_set_int(setting,key,value); + g_object_unref(setting); + g_settings_sync(); + + mouse_complete_transfer_int_value(object, invocation, retv); + + print_info("(%s, %d)\n", key, value); + + return TRUE; +} + +static gboolean kylin_get_int(Mouse *object, + GDBusMethodInvocation* invocation, + char *in_arg, + gpointer user_data) +{ + GSettings *setting=g_settings_new(schemaID); + gint ret=g_settings_get_int(setting, in_arg); + g_object_unref(setting); + mouse_complete_get_int_value(object, invocation, ret); + return TRUE; +} + +static gboolean kylin_set_char(Mouse* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gchar *value=NULL; + g_variant_get(in_arg, "(ss)", &key, &value); + + GSettings *setting=g_settings_new(schemaID); + gboolean retv=g_settings_set_string(setting,key,value); + g_object_unref(setting); + g_settings_sync(); + + mouse_complete_transfer_string_value(object, invocation, retv); + + print_info("(%s, %s)\n", key, value); + + return TRUE; +} + +static gboolean kylin_get_char(Mouse *object, + GDBusMethodInvocation* invocation, + char *in_arg, + gpointer user_data) +{ + GSettings *setting=g_settings_new(schemaID); + gchar *ret=g_settings_get_string(setting, in_arg); + g_object_unref(setting); + mouse_complete_get_string_value(object, invocation,ret); + return TRUE; +} + +static void bus_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + + GError *pError = NULL; + + /** Second step: Try to get a connection to the given bus. */ + pSkeleton = mouse_skeleton_new(); + + /** Third step: Attach to dbus signals. */ + (void) g_signal_connect(pSkeleton, "handle-transfer-bool-value", G_CALLBACK(kylin_set_bool), NULL); + (void) g_signal_connect(pSkeleton, "handle-get-bool-value", G_CALLBACK(kylin_get_bool), NULL); + (void) g_signal_connect(pSkeleton, "handle-transfer-double-value", G_CALLBACK(kylin_set_double), NULL); + (void) g_signal_connect(pSkeleton, "handle-get-double-value", G_CALLBACK(kylin_get_double), NULL); + (void) g_signal_connect(pSkeleton, "handle-transfer-int-value", G_CALLBACK(kylin_set_int), NULL); + (void) g_signal_connect(pSkeleton, "handle-get-int-value", G_CALLBACK(kylin_get_int), NULL); + (void) g_signal_connect(pSkeleton, "handle-transfer-string-value", G_CALLBACK(kylin_set_char), NULL); + (void) g_signal_connect(pSkeleton, "handle-get-string-value", G_CALLBACK(kylin_get_char), NULL); + + /** Fourth step: Export interface skeleton. */ + (void)g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(pSkeleton), + connection, + MOUSE_OBJECT_PATH, + &pError); + + if(pError != NULL){ + print_error("Error: Failed to export object. Reason: %s.\n", pError->message); + g_error_free(pError); + g_main_loop_quit(pLoop); + } +} + +static void name_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + print_info("name_acquired_cb call, Acquired bus name: %s.\n", MOUSE_BUS_NAME); +} + +static void name_lost_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + if(connection == NULL) + { + print_error("name_lost_cb call, Error: Failed to connect to dbus.\n"); + } + else + { + print_error("name_lost_cb call, Error: Failed to obtain bus name: %s.\n", MOUSE_BUS_NAME); + } + + g_main_loop_quit(pLoop); +} + +void* run(void* para) +{ + /** Start the Main Event Loop which manages all available sources of events */ + g_main_loop_run( pLoop ); + + return ((void*)0); +} + +int thread_create(void) +{ + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if (err != 0) + { + + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; +} + +bool InitDBusCommunicationServer(void) +{ + bool bRet = TRUE; + + g_print("InitDBusCommunicationServer: Server started.\n"); + + /** create main loop, but do not start it. */ + pLoop = g_main_loop_new(NULL, FALSE); + + /** first step: connect to dbus */ + (void)g_bus_own_name(MOUSE_BUS, + MOUSE_BUS_NAME, + G_BUS_NAME_OWNER_FLAGS_NONE, + &bus_acquired_cb, + &name_acquired_cb, + &name_lost_cb, + NULL, + NULL); + + thread_create(); + + return bRet; +} + +bool DeinitDBusCommunicationServer(void) +{ + bool bRet = FALSE; + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} + +int main(void) +{ + InitDBusCommunicationServer(); + + sleep(100); + + DeinitDBusCommunicationServer(); + return 0; +} diff --git a/src/hardware/mouse/mouse-dbus.h b/src/hardware/mouse/mouse-dbus.h new file mode 100644 index 0000000..42a4cfc --- /dev/null +++ b/src/hardware/mouse/mouse-dbus.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 /* Bus define */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define MOUSE_BUS G_BUS_TYPE_SESSION +#define MOUSE_BUS_NAME "cn.kylinos.mouse" +#define MOUSE_OBJECT_PATH "/cn/kylinos/mouse" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/hardware/mouse/mouse-generated.c b/src/hardware/mouse/mouse-generated.c new file mode 100644 index 0000000..bedcf98 --- /dev/null +++ b/src/hardware/mouse/mouse-generated.c @@ -0,0 +1,2455 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#ifdef G_OS_UNIX +# include +#endif + +typedef struct +{ + GDBusArgInfo parent_struct; + gboolean use_gvariant; +} _ExtendedGDBusArgInfo; + +typedef struct +{ + GDBusMethodInfo parent_struct; + const gchar *signal_name; + gboolean pass_fdlist; +} _ExtendedGDBusMethodInfo; + +typedef struct +{ + GDBusSignalInfo parent_struct; + const gchar *signal_name; +} _ExtendedGDBusSignalInfo; + +typedef struct +{ + GDBusPropertyInfo parent_struct; + const gchar *hyphen_name; + guint use_gvariant : 1; + guint emits_changed_signal : 1; +} _ExtendedGDBusPropertyInfo; + +typedef struct +{ + GDBusInterfaceInfo parent_struct; + const gchar *hyphen_name; +} _ExtendedGDBusInterfaceInfo; + +typedef struct +{ + const _ExtendedGDBusPropertyInfo *info; + guint prop_id; + GValue orig_value; /* the value before the change */ +} ChangedProperty; + +static void +_changed_property_free (ChangedProperty *data) +{ + g_value_unset (&data->orig_value); + g_free (data); +} + +static gboolean +_g_strv_equal0 (gchar **a, gchar **b) +{ + gboolean ret = FALSE; + guint n; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + if (g_strv_length (a) != g_strv_length (b)) + goto out; + for (n = 0; a[n] != NULL; n++) + if (g_strcmp0 (a[n], b[n]) != 0) + goto out; + ret = TRUE; +out: + return ret; +} + +static gboolean +_g_variant_equal0 (GVariant *a, GVariant *b) +{ + gboolean ret = FALSE; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + ret = g_variant_equal (a, b); +out: + return ret; +} + +G_GNUC_UNUSED static gboolean +_g_value_equal (const GValue *a, const GValue *b) +{ + gboolean ret = FALSE; + g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); + switch (G_VALUE_TYPE (a)) + { + case G_TYPE_BOOLEAN: + ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); + break; + case G_TYPE_UCHAR: + ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); + break; + case G_TYPE_INT: + ret = (g_value_get_int (a) == g_value_get_int (b)); + break; + case G_TYPE_UINT: + ret = (g_value_get_uint (a) == g_value_get_uint (b)); + break; + case G_TYPE_INT64: + ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); + break; + case G_TYPE_UINT64: + ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); + break; + case G_TYPE_DOUBLE: + { + /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ + gdouble da = g_value_get_double (a); + gdouble db = g_value_get_double (b); + ret = memcmp (&da, &db, sizeof (gdouble)) == 0; + } + break; + case G_TYPE_STRING: + ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); + break; + case G_TYPE_VARIANT: + ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); + break; + default: + if (G_VALUE_TYPE (a) == G_TYPE_STRV) + ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); + else + g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); + break; + } + return ret; +} + +/* ------------------------------------------------------------------------ + * Code for interface cn.kylinos.mouse + * ------------------------------------------------------------------------ + */ + +/** + * SECTION:Mouse + * @title: Mouse + * @short_description: Generated C code for the cn.kylinos.mouse D-Bus interface + * + * This section contains code for working with the cn.kylinos.mouse D-Bus interface in C. + */ + +/* ---- Introspection data for cn.kylinos.mouse ---- */ + +static const _ExtendedGDBusArgInfo _mouse_method_info_transfer_bool_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(sb)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_transfer_bool_value_IN_ARG_pointers[] = +{ + &_mouse_method_info_transfer_bool_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_transfer_bool_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_transfer_bool_value_OUT_ARG_pointers[] = +{ + &_mouse_method_info_transfer_bool_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _mouse_method_info_transfer_bool_value = +{ + { + -1, + (gchar *) "TransferBoolValue", + (GDBusArgInfo **) &_mouse_method_info_transfer_bool_value_IN_ARG_pointers, + (GDBusArgInfo **) &_mouse_method_info_transfer_bool_value_OUT_ARG_pointers, + NULL + }, + "handle-transfer-bool-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_get_bool_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "s", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_get_bool_value_IN_ARG_pointers[] = +{ + &_mouse_method_info_get_bool_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_get_bool_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_get_bool_value_OUT_ARG_pointers[] = +{ + &_mouse_method_info_get_bool_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _mouse_method_info_get_bool_value = +{ + { + -1, + (gchar *) "GetBoolValue", + (GDBusArgInfo **) &_mouse_method_info_get_bool_value_IN_ARG_pointers, + (GDBusArgInfo **) &_mouse_method_info_get_bool_value_OUT_ARG_pointers, + NULL + }, + "handle-get-bool-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_transfer_string_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(ss)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_transfer_string_value_IN_ARG_pointers[] = +{ + &_mouse_method_info_transfer_string_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_transfer_string_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_transfer_string_value_OUT_ARG_pointers[] = +{ + &_mouse_method_info_transfer_string_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _mouse_method_info_transfer_string_value = +{ + { + -1, + (gchar *) "TransferStringValue", + (GDBusArgInfo **) &_mouse_method_info_transfer_string_value_IN_ARG_pointers, + (GDBusArgInfo **) &_mouse_method_info_transfer_string_value_OUT_ARG_pointers, + NULL + }, + "handle-transfer-string-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_get_string_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "s", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_get_string_value_IN_ARG_pointers[] = +{ + &_mouse_method_info_get_string_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_get_string_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "s", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_get_string_value_OUT_ARG_pointers[] = +{ + &_mouse_method_info_get_string_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _mouse_method_info_get_string_value = +{ + { + -1, + (gchar *) "GetStringValue", + (GDBusArgInfo **) &_mouse_method_info_get_string_value_IN_ARG_pointers, + (GDBusArgInfo **) &_mouse_method_info_get_string_value_OUT_ARG_pointers, + NULL + }, + "handle-get-string-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_transfer_int_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(si)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_transfer_int_value_IN_ARG_pointers[] = +{ + &_mouse_method_info_transfer_int_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_transfer_int_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_transfer_int_value_OUT_ARG_pointers[] = +{ + &_mouse_method_info_transfer_int_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _mouse_method_info_transfer_int_value = +{ + { + -1, + (gchar *) "TransferIntValue", + (GDBusArgInfo **) &_mouse_method_info_transfer_int_value_IN_ARG_pointers, + (GDBusArgInfo **) &_mouse_method_info_transfer_int_value_OUT_ARG_pointers, + NULL + }, + "handle-transfer-int-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_get_int_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "s", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_get_int_value_IN_ARG_pointers[] = +{ + &_mouse_method_info_get_int_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_get_int_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "i", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_get_int_value_OUT_ARG_pointers[] = +{ + &_mouse_method_info_get_int_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _mouse_method_info_get_int_value = +{ + { + -1, + (gchar *) "GetIntValue", + (GDBusArgInfo **) &_mouse_method_info_get_int_value_IN_ARG_pointers, + (GDBusArgInfo **) &_mouse_method_info_get_int_value_OUT_ARG_pointers, + NULL + }, + "handle-get-int-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_transfer_double_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(sd)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_transfer_double_value_IN_ARG_pointers[] = +{ + &_mouse_method_info_transfer_double_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_transfer_double_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "b", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_transfer_double_value_OUT_ARG_pointers[] = +{ + &_mouse_method_info_transfer_double_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _mouse_method_info_transfer_double_value = +{ + { + -1, + (gchar *) "TransferDoubleValue", + (GDBusArgInfo **) &_mouse_method_info_transfer_double_value_IN_ARG_pointers, + (GDBusArgInfo **) &_mouse_method_info_transfer_double_value_OUT_ARG_pointers, + NULL + }, + "handle-transfer-double-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_get_double_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "s", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_get_double_value_IN_ARG_pointers[] = +{ + &_mouse_method_info_get_double_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusArgInfo _mouse_method_info_get_double_value_OUT_ARG_OutArg = +{ + { + -1, + (gchar *) "OutArg", + (gchar *) "d", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _mouse_method_info_get_double_value_OUT_ARG_pointers[] = +{ + &_mouse_method_info_get_double_value_OUT_ARG_OutArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _mouse_method_info_get_double_value = +{ + { + -1, + (gchar *) "GetDoubleValue", + (GDBusArgInfo **) &_mouse_method_info_get_double_value_IN_ARG_pointers, + (GDBusArgInfo **) &_mouse_method_info_get_double_value_OUT_ARG_pointers, + NULL + }, + "handle-get-double-value", + FALSE +}; + +static const GDBusMethodInfo * const _mouse_method_info_pointers[] = +{ + &_mouse_method_info_transfer_bool_value.parent_struct, + &_mouse_method_info_get_bool_value.parent_struct, + &_mouse_method_info_transfer_string_value.parent_struct, + &_mouse_method_info_get_string_value.parent_struct, + &_mouse_method_info_transfer_int_value.parent_struct, + &_mouse_method_info_get_int_value.parent_struct, + &_mouse_method_info_transfer_double_value.parent_struct, + &_mouse_method_info_get_double_value.parent_struct, + NULL +}; + +static const _ExtendedGDBusInterfaceInfo _mouse_interface_info = +{ + { + -1, + (gchar *) "cn.kylinos.mouse", + (GDBusMethodInfo **) &_mouse_method_info_pointers, + NULL, + NULL, + NULL + }, + "mouse", +}; + + +/** + * mouse_interface_info: + * + * Gets a machine-readable description of the cn.kylinos.mouse D-Bus interface. + * + * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. + */ +GDBusInterfaceInfo * +mouse_interface_info (void) +{ + return (GDBusInterfaceInfo *) &_mouse_interface_info.parent_struct; +} + +/** + * mouse_override_properties: + * @klass: The class structure for a #GObject derived class. + * @property_id_begin: The property id to assign to the first overridden property. + * + * Overrides all #GObject properties in the #Mouse interface for a concrete class. + * The properties are overridden in the order they are defined. + * + * Returns: The last property id. + */ +guint +mouse_override_properties (GObjectClass *klass, guint property_id_begin) +{ + return property_id_begin - 1; +} + + + +/** + * Mouse: + * + * Abstract interface type for the D-Bus interface cn.kylinos.mouse. + */ + +/** + * MouseIface: + * @parent_iface: The parent interface. + * @handle_get_bool_value: Handler for the #Mouse::handle-get-bool-value signal. + * @handle_get_double_value: Handler for the #Mouse::handle-get-double-value signal. + * @handle_get_int_value: Handler for the #Mouse::handle-get-int-value signal. + * @handle_get_string_value: Handler for the #Mouse::handle-get-string-value signal. + * @handle_transfer_bool_value: Handler for the #Mouse::handle-transfer-bool-value signal. + * @handle_transfer_double_value: Handler for the #Mouse::handle-transfer-double-value signal. + * @handle_transfer_int_value: Handler for the #Mouse::handle-transfer-int-value signal. + * @handle_transfer_string_value: Handler for the #Mouse::handle-transfer-string-value signal. + * + * Virtual table for the D-Bus interface cn.kylinos.mouse. + */ + +typedef MouseIface MouseInterface; +G_DEFINE_INTERFACE (Mouse, mouse, G_TYPE_OBJECT) + +static void +mouse_default_init (MouseIface *iface) +{ + /* GObject signals for incoming D-Bus method calls: */ + /** + * Mouse::handle-transfer-bool-value: + * @object: A #Mouse. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferBoolValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call mouse_complete_transfer_bool_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-bool-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (MouseIface, handle_transfer_bool_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Mouse::handle-get-bool-value: + * @object: A #Mouse. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the GetBoolValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call mouse_complete_get_bool_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-get-bool-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (MouseIface, handle_get_bool_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_STRING); + + /** + * Mouse::handle-transfer-string-value: + * @object: A #Mouse. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferStringValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call mouse_complete_transfer_string_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-string-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (MouseIface, handle_transfer_string_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Mouse::handle-get-string-value: + * @object: A #Mouse. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the GetStringValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call mouse_complete_get_string_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-get-string-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (MouseIface, handle_get_string_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_STRING); + + /** + * Mouse::handle-transfer-int-value: + * @object: A #Mouse. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferIntValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call mouse_complete_transfer_int_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-int-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (MouseIface, handle_transfer_int_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Mouse::handle-get-int-value: + * @object: A #Mouse. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the GetIntValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call mouse_complete_get_int_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-get-int-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (MouseIface, handle_get_int_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_STRING); + + /** + * Mouse::handle-transfer-double-value: + * @object: A #Mouse. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferDoubleValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call mouse_complete_transfer_double_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-double-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (MouseIface, handle_transfer_double_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Mouse::handle-get-double-value: + * @object: A #Mouse. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the GetDoubleValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call mouse_complete_get_double_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-get-double-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (MouseIface, handle_get_double_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_STRING); + +} + +/** + * mouse_call_transfer_bool_value: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferBoolValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call mouse_call_transfer_bool_value_finish() to get the result of the operation. + * + * See mouse_call_transfer_bool_value_sync() for the synchronous, blocking version of this method. + */ +void +mouse_call_transfer_bool_value ( + Mouse *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * mouse_call_transfer_bool_value_finish: + * @proxy: A #MouseProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to mouse_call_transfer_bool_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with mouse_call_transfer_bool_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_transfer_bool_value_finish ( + Mouse *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_transfer_bool_value_sync: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferBoolValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See mouse_call_transfer_bool_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_transfer_bool_value_sync ( + Mouse *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_get_bool_value: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the GetBoolValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call mouse_call_get_bool_value_finish() to get the result of the operation. + * + * See mouse_call_get_bool_value_sync() for the synchronous, blocking version of this method. + */ +void +mouse_call_get_bool_value ( + Mouse *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "GetBoolValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * mouse_call_get_bool_value_finish: + * @proxy: A #MouseProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to mouse_call_get_bool_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with mouse_call_get_bool_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_get_bool_value_finish ( + Mouse *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_get_bool_value_sync: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the GetBoolValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See mouse_call_get_bool_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_get_bool_value_sync ( + Mouse *proxy, + const gchar *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "GetBoolValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_transfer_string_value: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferStringValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call mouse_call_transfer_string_value_finish() to get the result of the operation. + * + * See mouse_call_transfer_string_value_sync() for the synchronous, blocking version of this method. + */ +void +mouse_call_transfer_string_value ( + Mouse *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferStringValue", + g_variant_new ("(@(ss))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * mouse_call_transfer_string_value_finish: + * @proxy: A #MouseProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to mouse_call_transfer_string_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with mouse_call_transfer_string_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_transfer_string_value_finish ( + Mouse *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_transfer_string_value_sync: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferStringValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See mouse_call_transfer_string_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_transfer_string_value_sync ( + Mouse *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferStringValue", + g_variant_new ("(@(ss))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_get_string_value: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the GetStringValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call mouse_call_get_string_value_finish() to get the result of the operation. + * + * See mouse_call_get_string_value_sync() for the synchronous, blocking version of this method. + */ +void +mouse_call_get_string_value ( + Mouse *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "GetStringValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * mouse_call_get_string_value_finish: + * @proxy: A #MouseProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to mouse_call_get_string_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with mouse_call_get_string_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_get_string_value_finish ( + Mouse *proxy, + gchar **out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(s)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_get_string_value_sync: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the GetStringValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See mouse_call_get_string_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_get_string_value_sync ( + Mouse *proxy, + const gchar *arg_InArg, + gchar **out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "GetStringValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(s)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_transfer_int_value: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferIntValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call mouse_call_transfer_int_value_finish() to get the result of the operation. + * + * See mouse_call_transfer_int_value_sync() for the synchronous, blocking version of this method. + */ +void +mouse_call_transfer_int_value ( + Mouse *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * mouse_call_transfer_int_value_finish: + * @proxy: A #MouseProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to mouse_call_transfer_int_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with mouse_call_transfer_int_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_transfer_int_value_finish ( + Mouse *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_transfer_int_value_sync: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferIntValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See mouse_call_transfer_int_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_transfer_int_value_sync ( + Mouse *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_get_int_value: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the GetIntValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call mouse_call_get_int_value_finish() to get the result of the operation. + * + * See mouse_call_get_int_value_sync() for the synchronous, blocking version of this method. + */ +void +mouse_call_get_int_value ( + Mouse *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "GetIntValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * mouse_call_get_int_value_finish: + * @proxy: A #MouseProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to mouse_call_get_int_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with mouse_call_get_int_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_get_int_value_finish ( + Mouse *proxy, + gint *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(i)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_get_int_value_sync: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the GetIntValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See mouse_call_get_int_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_get_int_value_sync ( + Mouse *proxy, + const gchar *arg_InArg, + gint *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "GetIntValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(i)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_transfer_double_value: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferDoubleValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call mouse_call_transfer_double_value_finish() to get the result of the operation. + * + * See mouse_call_transfer_double_value_sync() for the synchronous, blocking version of this method. + */ +void +mouse_call_transfer_double_value ( + Mouse *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferDoubleValue", + g_variant_new ("(@(sd))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * mouse_call_transfer_double_value_finish: + * @proxy: A #MouseProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to mouse_call_transfer_double_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with mouse_call_transfer_double_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_transfer_double_value_finish ( + Mouse *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_transfer_double_value_sync: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferDoubleValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See mouse_call_transfer_double_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_transfer_double_value_sync ( + Mouse *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferDoubleValue", + g_variant_new ("(@(sd))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(b)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_get_double_value: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the GetDoubleValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call mouse_call_get_double_value_finish() to get the result of the operation. + * + * See mouse_call_get_double_value_sync() for the synchronous, blocking version of this method. + */ +void +mouse_call_get_double_value ( + Mouse *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "GetDoubleValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * mouse_call_get_double_value_finish: + * @proxy: A #MouseProxy. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to mouse_call_get_double_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with mouse_call_get_double_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_get_double_value_finish ( + Mouse *proxy, + gdouble *out_OutArg, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(d)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_call_get_double_value_sync: + * @proxy: A #MouseProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @out_OutArg: (out) (optional): Return location for return parameter or %NULL to ignore. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the GetDoubleValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See mouse_call_get_double_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +mouse_call_get_double_value_sync ( + Mouse *proxy, + const gchar *arg_InArg, + gdouble *out_OutArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "GetDoubleValue", + g_variant_new ("(s)", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "(d)", + out_OutArg); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * mouse_complete_transfer_bool_value: + * @object: A #Mouse. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the TransferBoolValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +mouse_complete_transfer_bool_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/** + * mouse_complete_get_bool_value: + * @object: A #Mouse. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the GetBoolValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +mouse_complete_get_bool_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/** + * mouse_complete_transfer_string_value: + * @object: A #Mouse. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the TransferStringValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +mouse_complete_transfer_string_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/** + * mouse_complete_get_string_value: + * @object: A #Mouse. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the GetStringValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +mouse_complete_get_string_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + const gchar *OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(s)", + OutArg)); +} + +/** + * mouse_complete_transfer_int_value: + * @object: A #Mouse. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the TransferIntValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +mouse_complete_transfer_int_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/** + * mouse_complete_get_int_value: + * @object: A #Mouse. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the GetIntValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +mouse_complete_get_int_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gint OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(i)", + OutArg)); +} + +/** + * mouse_complete_transfer_double_value: + * @object: A #Mouse. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the TransferDoubleValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +mouse_complete_transfer_double_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gboolean OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(b)", + OutArg)); +} + +/** + * mouse_complete_get_double_value: + * @object: A #Mouse. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * @OutArg: Parameter to return. + * + * Helper function used in service implementations to finish handling invocations of the GetDoubleValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +mouse_complete_get_double_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gdouble OutArg) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("(d)", + OutArg)); +} + +/* ------------------------------------------------------------------------ */ + +/** + * MouseProxy: + * + * The #MouseProxy structure contains only private data and should only be accessed using the provided API. + */ + +/** + * MouseProxyClass: + * @parent_class: The parent class. + * + * Class structure for #MouseProxy. + */ + +struct _MouseProxyPrivate +{ + GData *qdata; +}; + +static void mouse_proxy_iface_init (MouseIface *iface); + +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (MouseProxy, mouse_proxy, G_TYPE_DBUS_PROXY, + G_ADD_PRIVATE (MouseProxy) + G_IMPLEMENT_INTERFACE (TYPE_MOUSE, mouse_proxy_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (MouseProxy, mouse_proxy, G_TYPE_DBUS_PROXY, + G_IMPLEMENT_INTERFACE (TYPE_MOUSE, mouse_proxy_iface_init)) + +#endif +static void +mouse_proxy_finalize (GObject *object) +{ + MouseProxy *proxy = MOUSE_PROXY (object); + g_datalist_clear (&proxy->priv->qdata); + G_OBJECT_CLASS (mouse_proxy_parent_class)->finalize (object); +} + +static void +mouse_proxy_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +mouse_proxy_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +mouse_proxy_g_signal (GDBusProxy *proxy, + const gchar *sender_name G_GNUC_UNUSED, + const gchar *signal_name, + GVariant *parameters) +{ + _ExtendedGDBusSignalInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + gsize n; + guint signal_id; + info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_mouse_interface_info.parent_struct, signal_name); + if (info == NULL) + return; + num_params = g_variant_n_children (parameters); + paramv = g_new0 (GValue, num_params + 1); + g_value_init (¶mv[0], TYPE_MOUSE); + g_value_set_object (¶mv[0], proxy); + g_variant_iter_init (&iter, parameters); + n = 1; + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_MOUSE); + g_signal_emitv (paramv, signal_id, 0, NULL); + for (n = 0; n < num_params + 1; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static void +mouse_proxy_g_properties_changed (GDBusProxy *_proxy, + GVariant *changed_properties, + const gchar *const *invalidated_properties) +{ + MouseProxy *proxy = MOUSE_PROXY (_proxy); + guint n; + const gchar *key; + GVariantIter *iter; + _ExtendedGDBusPropertyInfo *info; + g_variant_get (changed_properties, "a{sv}", &iter); + while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_mouse_interface_info.parent_struct, key); + g_datalist_remove_data (&proxy->priv->qdata, key); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } + g_variant_iter_free (iter); + for (n = 0; invalidated_properties[n] != NULL; n++) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_mouse_interface_info.parent_struct, invalidated_properties[n]); + g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } +} + +static void +mouse_proxy_init (MouseProxy *proxy) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + proxy->priv = mouse_proxy_get_instance_private (proxy); +#else + proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, TYPE_MOUSE_PROXY, MouseProxyPrivate); +#endif + + g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), mouse_interface_info ()); +} + +static void +mouse_proxy_class_init (MouseProxyClass *klass) +{ + GObjectClass *gobject_class; + GDBusProxyClass *proxy_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = mouse_proxy_finalize; + gobject_class->get_property = mouse_proxy_get_property; + gobject_class->set_property = mouse_proxy_set_property; + + proxy_class = G_DBUS_PROXY_CLASS (klass); + proxy_class->g_signal = mouse_proxy_g_signal; + proxy_class->g_properties_changed = mouse_proxy_g_properties_changed; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (MouseProxyPrivate)); +#endif +} + +static void +mouse_proxy_iface_init (MouseIface *iface) +{ +} + +/** + * mouse_proxy_new: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Asynchronously creates a proxy for the D-Bus interface cn.kylinos.mouse. See g_dbus_proxy_new() for more details. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call mouse_proxy_new_finish() to get the result of the operation. + * + * See mouse_proxy_new_sync() for the synchronous, blocking version of this constructor. + */ +void +mouse_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_MOUSE_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.mouse", NULL); +} + +/** + * mouse_proxy_new_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to mouse_proxy_new(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with mouse_proxy_new(). + * + * Returns: (transfer full) (type MouseProxy): The constructed proxy object or %NULL if @error is set. + */ +Mouse * +mouse_proxy_new_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return MOUSE (ret); + else + return NULL; +} + +/** + * mouse_proxy_new_sync: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Synchronously creates a proxy for the D-Bus interface cn.kylinos.mouse. See g_dbus_proxy_new_sync() for more details. + * + * The calling thread is blocked until a reply is received. + * + * See mouse_proxy_new() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type MouseProxy): The constructed proxy object or %NULL if @error is set. + */ +Mouse * +mouse_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_MOUSE_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.mouse", NULL); + if (ret != NULL) + return MOUSE (ret); + else + return NULL; +} + + +/** + * mouse_proxy_new_for_bus: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Like mouse_proxy_new() but takes a #GBusType instead of a #GDBusConnection. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call mouse_proxy_new_for_bus_finish() to get the result of the operation. + * + * See mouse_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. + */ +void +mouse_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_MOUSE_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.mouse", NULL); +} + +/** + * mouse_proxy_new_for_bus_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to mouse_proxy_new_for_bus(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with mouse_proxy_new_for_bus(). + * + * Returns: (transfer full) (type MouseProxy): The constructed proxy object or %NULL if @error is set. + */ +Mouse * +mouse_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return MOUSE (ret); + else + return NULL; +} + +/** + * mouse_proxy_new_for_bus_sync: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Like mouse_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. + * + * The calling thread is blocked until a reply is received. + * + * See mouse_proxy_new_for_bus() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type MouseProxy): The constructed proxy object or %NULL if @error is set. + */ +Mouse * +mouse_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_MOUSE_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.mouse", NULL); + if (ret != NULL) + return MOUSE (ret); + else + return NULL; +} + + +/* ------------------------------------------------------------------------ */ + +/** + * MouseSkeleton: + * + * The #MouseSkeleton structure contains only private data and should only be accessed using the provided API. + */ + +/** + * MouseSkeletonClass: + * @parent_class: The parent class. + * + * Class structure for #MouseSkeleton. + */ + +struct _MouseSkeletonPrivate +{ + GValue *properties; + GList *changed_properties; + GSource *changed_properties_idle_source; + GMainContext *context; + GMutex lock; +}; + +static void +_mouse_skeleton_handle_method_call ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name, + const gchar *method_name, + GVariant *parameters, + GDBusMethodInvocation *invocation, + gpointer user_data) +{ + MouseSkeleton *skeleton = MOUSE_SKELETON (user_data); + _ExtendedGDBusMethodInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + guint num_extra; + gsize n; + guint signal_id; + GValue return_value = G_VALUE_INIT; + info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); + g_assert (info != NULL); + num_params = g_variant_n_children (parameters); + num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); + n = 0; + g_value_init (¶mv[n], TYPE_MOUSE); + g_value_set_object (¶mv[n++], skeleton); + g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); + g_value_set_object (¶mv[n++], invocation); + if (info->pass_fdlist) + { +#ifdef G_OS_UNIX + g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); + g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); +#else + g_assert_not_reached (); +#endif + } + g_variant_iter_init (&iter, parameters); + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_MOUSE); + g_value_init (&return_value, G_TYPE_BOOLEAN); + g_signal_emitv (paramv, signal_id, 0, &return_value); + if (!g_value_get_boolean (&return_value)) + g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); + g_value_unset (&return_value); + for (n = 0; n < num_params + num_extra; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static GVariant * +_mouse_skeleton_handle_get_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GError **error, + gpointer user_data) +{ + MouseSkeleton *skeleton = MOUSE_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + GVariant *ret; + ret = NULL; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_mouse_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + g_value_init (&value, pspec->value_type); + g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); + ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); + g_value_unset (&value); + } + return ret; +} + +static gboolean +_mouse_skeleton_handle_set_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GVariant *variant, + GError **error, + gpointer user_data) +{ + MouseSkeleton *skeleton = MOUSE_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + gboolean ret; + ret = FALSE; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_mouse_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + if (info->use_gvariant) + g_value_set_variant (&value, variant); + else + g_dbus_gvariant_to_gvalue (variant, &value); + g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); + g_value_unset (&value); + ret = TRUE; + } + return ret; +} + +static const GDBusInterfaceVTable _mouse_skeleton_vtable = +{ + _mouse_skeleton_handle_method_call, + _mouse_skeleton_handle_get_property, + _mouse_skeleton_handle_set_property, + {NULL} +}; + +static GDBusInterfaceInfo * +mouse_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return mouse_interface_info (); +} + +static GDBusInterfaceVTable * +mouse_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return (GDBusInterfaceVTable *) &_mouse_skeleton_vtable; +} + +static GVariant * +mouse_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) +{ + MouseSkeleton *skeleton = MOUSE_SKELETON (_skeleton); + + GVariantBuilder builder; + guint n; + g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); + if (_mouse_interface_info.parent_struct.properties == NULL) + goto out; + for (n = 0; _mouse_interface_info.parent_struct.properties[n] != NULL; n++) + { + GDBusPropertyInfo *info = _mouse_interface_info.parent_struct.properties[n]; + if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) + { + GVariant *value; + value = _mouse_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "cn.kylinos.mouse", info->name, NULL, skeleton); + if (value != NULL) + { + g_variant_take_ref (value); + g_variant_builder_add (&builder, "{sv}", info->name, value); + g_variant_unref (value); + } + } + } +out: + return g_variant_builder_end (&builder); +} + +static void +mouse_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) +{ +} + +static void mouse_skeleton_iface_init (MouseIface *iface); +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (MouseSkeleton, mouse_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_ADD_PRIVATE (MouseSkeleton) + G_IMPLEMENT_INTERFACE (TYPE_MOUSE, mouse_skeleton_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (MouseSkeleton, mouse_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_IMPLEMENT_INTERFACE (TYPE_MOUSE, mouse_skeleton_iface_init)) + +#endif +static void +mouse_skeleton_finalize (GObject *object) +{ + MouseSkeleton *skeleton = MOUSE_SKELETON (object); + g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); + if (skeleton->priv->changed_properties_idle_source != NULL) + g_source_destroy (skeleton->priv->changed_properties_idle_source); + g_main_context_unref (skeleton->priv->context); + g_mutex_clear (&skeleton->priv->lock); + G_OBJECT_CLASS (mouse_skeleton_parent_class)->finalize (object); +} + +static void +mouse_skeleton_init (MouseSkeleton *skeleton) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + skeleton->priv = mouse_skeleton_get_instance_private (skeleton); +#else + skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_MOUSE_SKELETON, MouseSkeletonPrivate); +#endif + + g_mutex_init (&skeleton->priv->lock); + skeleton->priv->context = g_main_context_ref_thread_default (); +} + +static void +mouse_skeleton_class_init (MouseSkeletonClass *klass) +{ + GObjectClass *gobject_class; + GDBusInterfaceSkeletonClass *skeleton_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = mouse_skeleton_finalize; + + skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); + skeleton_class->get_info = mouse_skeleton_dbus_interface_get_info; + skeleton_class->get_properties = mouse_skeleton_dbus_interface_get_properties; + skeleton_class->flush = mouse_skeleton_dbus_interface_flush; + skeleton_class->get_vtable = mouse_skeleton_dbus_interface_get_vtable; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (MouseSkeletonPrivate)); +#endif +} + +static void +mouse_skeleton_iface_init (MouseIface *iface) +{ +} + +/** + * mouse_skeleton_new: + * + * Creates a skeleton object for the D-Bus interface cn.kylinos.mouse. + * + * Returns: (transfer full) (type MouseSkeleton): The skeleton object. + */ +Mouse * +mouse_skeleton_new (void) +{ + return MOUSE (g_object_new (TYPE_MOUSE_SKELETON, NULL)); +} + diff --git a/src/hardware/mouse/mouse-generated.h b/src/hardware/mouse/mouse-generated.h new file mode 100644 index 0000000..b438983 --- /dev/null +++ b/src/hardware/mouse/mouse-generated.h @@ -0,0 +1,403 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +G_BEGIN_DECLS + + +/* ------------------------------------------------------------------------ */ +/* Declarations for cn.kylinos.mouse */ + +#define TYPE_MOUSE (mouse_get_type ()) +#define MOUSE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_MOUSE, Mouse)) +#define IS_MOUSE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_MOUSE)) +#define MOUSE_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), TYPE_MOUSE, MouseIface)) + +struct _Mouse; +typedef struct _Mouse Mouse; +typedef struct _MouseIface MouseIface; + +struct _MouseIface +{ + GTypeInterface parent_iface; + + gboolean (*handle_get_bool_value) ( + Mouse *object, + GDBusMethodInvocation *invocation, + const gchar *arg_InArg); + + gboolean (*handle_get_double_value) ( + Mouse *object, + GDBusMethodInvocation *invocation, + const gchar *arg_InArg); + + gboolean (*handle_get_int_value) ( + Mouse *object, + GDBusMethodInvocation *invocation, + const gchar *arg_InArg); + + gboolean (*handle_get_string_value) ( + Mouse *object, + GDBusMethodInvocation *invocation, + const gchar *arg_InArg); + + gboolean (*handle_transfer_bool_value) ( + Mouse *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + + gboolean (*handle_transfer_double_value) ( + Mouse *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + + gboolean (*handle_transfer_int_value) ( + Mouse *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + + gboolean (*handle_transfer_string_value) ( + Mouse *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + +}; + +GType mouse_get_type (void) G_GNUC_CONST; + +GDBusInterfaceInfo *mouse_interface_info (void); +guint mouse_override_properties (GObjectClass *klass, guint property_id_begin); + + +/* D-Bus method call completion functions: */ +void mouse_complete_transfer_bool_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + +void mouse_complete_get_bool_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + +void mouse_complete_transfer_string_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + +void mouse_complete_get_string_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + const gchar *OutArg); + +void mouse_complete_transfer_int_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + +void mouse_complete_get_int_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gint OutArg); + +void mouse_complete_transfer_double_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gboolean OutArg); + +void mouse_complete_get_double_value ( + Mouse *object, + GDBusMethodInvocation *invocation, + gdouble OutArg); + + + +/* D-Bus method calls: */ +void mouse_call_transfer_bool_value ( + Mouse *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean mouse_call_transfer_bool_value_finish ( + Mouse *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean mouse_call_transfer_bool_value_sync ( + Mouse *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + +void mouse_call_get_bool_value ( + Mouse *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean mouse_call_get_bool_value_finish ( + Mouse *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean mouse_call_get_bool_value_sync ( + Mouse *proxy, + const gchar *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + +void mouse_call_transfer_string_value ( + Mouse *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean mouse_call_transfer_string_value_finish ( + Mouse *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean mouse_call_transfer_string_value_sync ( + Mouse *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + +void mouse_call_get_string_value ( + Mouse *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean mouse_call_get_string_value_finish ( + Mouse *proxy, + gchar **out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean mouse_call_get_string_value_sync ( + Mouse *proxy, + const gchar *arg_InArg, + gchar **out_OutArg, + GCancellable *cancellable, + GError **error); + +void mouse_call_transfer_int_value ( + Mouse *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean mouse_call_transfer_int_value_finish ( + Mouse *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean mouse_call_transfer_int_value_sync ( + Mouse *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + +void mouse_call_get_int_value ( + Mouse *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean mouse_call_get_int_value_finish ( + Mouse *proxy, + gint *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean mouse_call_get_int_value_sync ( + Mouse *proxy, + const gchar *arg_InArg, + gint *out_OutArg, + GCancellable *cancellable, + GError **error); + +void mouse_call_transfer_double_value ( + Mouse *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean mouse_call_transfer_double_value_finish ( + Mouse *proxy, + gboolean *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean mouse_call_transfer_double_value_sync ( + Mouse *proxy, + GVariant *arg_InArg, + gboolean *out_OutArg, + GCancellable *cancellable, + GError **error); + +void mouse_call_get_double_value ( + Mouse *proxy, + const gchar *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean mouse_call_get_double_value_finish ( + Mouse *proxy, + gdouble *out_OutArg, + GAsyncResult *res, + GError **error); + +gboolean mouse_call_get_double_value_sync ( + Mouse *proxy, + const gchar *arg_InArg, + gdouble *out_OutArg, + GCancellable *cancellable, + GError **error); + + + +/* ---- */ + +#define TYPE_MOUSE_PROXY (mouse_proxy_get_type ()) +#define MOUSE_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_MOUSE_PROXY, MouseProxy)) +#define MOUSE_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_MOUSE_PROXY, MouseProxyClass)) +#define MOUSE_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_MOUSE_PROXY, MouseProxyClass)) +#define IS_MOUSE_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_MOUSE_PROXY)) +#define IS_MOUSE_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_MOUSE_PROXY)) + +typedef struct _MouseProxy MouseProxy; +typedef struct _MouseProxyClass MouseProxyClass; +typedef struct _MouseProxyPrivate MouseProxyPrivate; + +struct _MouseProxy +{ + /*< private >*/ + GDBusProxy parent_instance; + MouseProxyPrivate *priv; +}; + +struct _MouseProxyClass +{ + GDBusProxyClass parent_class; +}; + +GType mouse_proxy_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (MouseProxy, g_object_unref) +#endif + +void mouse_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Mouse *mouse_proxy_new_finish ( + GAsyncResult *res, + GError **error); +Mouse *mouse_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + +void mouse_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Mouse *mouse_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error); +Mouse *mouse_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + + +/* ---- */ + +#define TYPE_MOUSE_SKELETON (mouse_skeleton_get_type ()) +#define MOUSE_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_MOUSE_SKELETON, MouseSkeleton)) +#define MOUSE_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_MOUSE_SKELETON, MouseSkeletonClass)) +#define MOUSE_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_MOUSE_SKELETON, MouseSkeletonClass)) +#define IS_MOUSE_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_MOUSE_SKELETON)) +#define IS_MOUSE_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_MOUSE_SKELETON)) + +typedef struct _MouseSkeleton MouseSkeleton; +typedef struct _MouseSkeletonClass MouseSkeletonClass; +typedef struct _MouseSkeletonPrivate MouseSkeletonPrivate; + +struct _MouseSkeleton +{ + /*< private >*/ + GDBusInterfaceSkeleton parent_instance; + MouseSkeletonPrivate *priv; +}; + +struct _MouseSkeletonClass +{ + GDBusInterfaceSkeletonClass parent_class; +}; + +GType mouse_skeleton_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (MouseSkeleton, g_object_unref) +#endif + +Mouse *mouse_skeleton_new (void); + + +G_END_DECLS + +#endif /* __MOUSE_GENERATED_H__ */ diff --git a/src/hardware/power/Makefile.am b/src/hardware/power/Makefile.am new file mode 100644 index 0000000..2273122 --- /dev/null +++ b/src/hardware/power/Makefile.am @@ -0,0 +1,131 @@ +COMM_PRINT= -L$(top_srcdir)/src/common -lukui-print +COMM_GSETTINGS= -L$(top_srcdir)/src/common -lukui-gsettings + +#generate the .c and .h file which used by client and server side by XML file +#$(top_srcdir) represents the top-level directory of the project +POWER_XML = $(top_srcdir)/data/cn.kylinos.power.xml +GENERATED_POW = power-generated + +SCREEN_XML = $(top_srcdir)/data/cn.kylinos.screensaver.xml +GENERATED_SCREEN = screensaver-generated + +SESS_XML = $(top_srcdir)/data/cn.kylinos.session.xml +GENERATED_SESS = session-generated + +power-generated.h power-generated.c: $(POWER_XML) + gdbus-codegen --interface-prefix cn.kylinos. --generate-c-code $(GENERATED_POW) $(POWER_XML) + +screensaver-generated.h screensaver-generated.c: $(SCREEN_XML) + gdbus-codegen --interface-prefix cn.kylinos. --generate-c-code $(GENERATED_SCREEN) $(SCREEN_XML) + +session-generated.h session-generated.c: $(SESS_XML) + gdbus-codegen --interface-prefix cn.kylinos. --generate-c-code $(GENERATED_SESS) $(SESS_XML) + +#Generata binary file +lib_LTLIBRARIES = libukui-powerclient.la libukui-screensaverclient.la libukui-sessionclient.la + +#gcc -wall: displays all the errors and warning information when compiling +#gcc -g: add the debugging code when compiling +COMM_CFS = -Wall -g + +#Add the dependent source file for libpowerclient.la +#power-generated.c must be front of kylin-power-interface.c +libukui_powerclient_la_SOURCES = power-generated.c kylin-power-interface.c \ + $(NULL) + +#The header files that need to be installed +include_HEADERS= kylin-power-interface.h \ + kylin-screensaver-interface.h \ + kylin-session-interface.h \ + $(NULL) + +#Additional C compiler flags +libukui_powerclient_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_powerclient_la_LDFLAGS= $(COMM_PRINT) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Add the dependent source file for libscreensaverclient.la +#screensaver-generated.c must be front of kylin-screensaver-interface.c +libukui_screensaverclient_la_SOURCES = screensaver-generated.c kylin-screensaver-interface.c \ + $(NULL) + +#Additional C compiler flags +libukui_screensaverclient_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_screensaverclient_la_LDFLAGS= $(COMM_PRINT) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Add the dependent source file for libsessionclient.la +#session-generated.c must be front of kylin-session-interface.c +libukui_sessionclient_la_SOURCES = session-generated.c kylin-session-interface.c \ + $(NULL) + +#Additional C compiler flags +libukui_sessionclient_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_sessionclient_la_LDFLAGS= $(COMM_PRINT) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Generata binary file +bin_PROGRAMS = ukui-powerserver ukui-screensaverserver ukui-sessionserver + +#Add the dependent source file for powerserver +ukui_powerserver_SOURCES = \ + power-generated.h power-generated.c \ + kylin-power-server.c \ + $(NULL) + +#Additional C compiler flags +ukui_powerserver_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +ukui_powerserver_LDFLAGS= $(COMM_PRINT) $(COMM_GSETTINGS) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Add the dependent source file for screensaverserver +ukui_screensaverserver_SOURCES = \ + screensaver-generated.h screensaver-generated.c \ + kylin-screensaver-server.c \ + $(NULL) + +#Additional C compiler flags +ukui_screensaverserver_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +ukui_screensaverserver_LDFLAGS= $(COMM_PRINT) $(COMM_GSETTINGS) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Add the dependent source file for sessionserver +ukui_sessionserver_SOURCES = \ + session-generated.h session-generated.c \ + kylin-session-server.c \ + $(NULL) + +#Additional C compiler flags +ukui_sessionserver_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +ukui_sessionserver_LDFLAGS= $(COMM_PRINT) $(COMM_GSETTINGS) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) diff --git a/src/hardware/power/kylin-power-interface.c b/src/hardware/power/kylin-power-interface.c new file mode 100644 index 0000000..61ab166 --- /dev/null +++ b/src/hardware/power/kylin-power-interface.c @@ -0,0 +1,203 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#define SCB "sleep-computer-battery" +#define SCA "sleep-computer-ac" +#define SDB "sleep-display-battery" +#define SDA "sleep-display-ac" +#define IP "icon-policy" + +static GMainLoop *pLoop = NULL; +static GDBusConnection *pConnection = NULL; +static Power *pProxy = NULL; + +void kylin_hardware_power_sleepcomputerbattery(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=SCB; + arg=g_variant_new("(si)",key,in_arg); + power_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_power_sleepcomputerbattery. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; + +} + +void kylin_hardware_power_sleepcomputerac(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=SCA; + arg=g_variant_new("(si)",key,in_arg); + power_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_power_sleepcomputerac. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; + +} + +void kylin_hardware_power_sleepdisplaybattery(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=SDB; + arg=g_variant_new("(si)",key,in_arg); + power_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_power_sleepdisplaybattery. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; + +} + +void kylin_hardware_power_sleepdisplayac(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=SDA; + arg=g_variant_new("(si)",key,in_arg); + power_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_power_sleepdisplayac. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; + +} + +void kylin_hardware_power_iconpolicy(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=IP; + arg=g_variant_new("(si)",key,in_arg); + power_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_power_iconpolicy. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; + +} + +void *run(void* arg) +{ + /** start the main event loop which manages all available sources of events */ + g_main_loop_run(pLoop); + + return ((void*)0); +} + +int thread_create(void) + { + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if(0 != err){ + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; + } + +bool InitDBusPower(void) + { + bool bRet = TRUE; + GError *pConnError = NULL; + GError *pProxyError = NULL; + + do{ + bRet = TRUE; + pLoop = g_main_loop_new(NULL, FALSE); /** create main loop, but do not start it.*/ + + /** First step: get a connection */ + pConnection = g_bus_get_sync(POWER_BUS, NULL, &pConnError); + + if (NULL == pConnError){ + /** Second step: try to get a connection to the given bus.*/ + pProxy = power_proxy_new_sync(pConnection, + G_DBUS_PROXY_FLAGS_NONE, + POWER_BUS_NAME, + POWER_OBJECT_PATH, + NULL, + &pProxyError); + if (0 == pProxy){ + print_error("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message); + g_error_free(pProxyError); + bRet = FALSE; + } + + + } + else{ + print_error("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message); + g_error_free(pConnError); + bRet = FALSE; + } + }while(FALSE == bRet); + + thread_create(); + + return bRet; + } + +bool DeInitDBusPower(void) +{ + bool bRet = FALSE; + + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} diff --git a/src/hardware/power/kylin-power-interface.h b/src/hardware/power/kylin-power-interface.h new file mode 100644 index 0000000..8a30a1f --- /dev/null +++ b/src/hardware/power/kylin-power-interface.h @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +//Initialize the DBus Communication +bool InitDBusPower(void); + +//Delete the DBus Communication +bool DeInitDBusPower(void); +/* + * Sleep timeout computer when on battery + */ +void kylin_hardware_power_sleepcomputerbattery(const int in_arg); + +/* + * Sleep timeout computer when on AC + */ +void kylin_hardware_power_sleepcomputerac(const int in_arg); + +/* + * Sleep timeout display when on battery + */ +void kylin_hardware_power_sleepdisplaybattery(const int in_arg); + +/* + * Sleep timeout display when on AC + */ +void kylin_hardware_power_sleepdisplayac(const int in_arg); + +/* + * Display options for the notification icon. + * Possible values are: + * @in_arg is equal to 0, "always"; + * @in_arg is equal to 1, "present"; + * @in_arg is equal to 2, "charge"; + * @in_arg is equal to 3, "low"; + * @in_arg is equal to 4, "critical"; + * @in_arg is equal to 5, "never". + */ +void kylin_hardware_power_iconpolicy(const int in_arg); + +#ifdef __cplusplus +} +#endif + +#endif + + + + + + + + + + + + + diff --git a/src/hardware/power/kylin-power-server.c b/src/hardware/power/kylin-power-server.c new file mode 100644 index 0000000..baac2be --- /dev/null +++ b/src/hardware/power/kylin-power-server.c @@ -0,0 +1,178 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include "power-dbus.h" +#include "src/common/kylin-gsettings-set.h" +#include "src/common/kylin-print.h" +#include "power-generated.h" +#include +#include + +#define schemaID "org.mate.power-manager" + +static GMainLoop *pLoop = NULL; +static Power *pSkeleton = NULL; + +static gboolean kylin_set_int(Power* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gint value; + g_variant_get(in_arg, "(si)", &key, &value); + + power_complete_transfer_int_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + if(strcmp(key,"icon-policy")==0) + gsettings_set_enum(setting, key, value); + else gsettings_set_int(setting, key, value); + Dec_ref(setting); + + print_info("(%s, %d)\n", key, value); + + return TRUE; +} + +static void bus_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + + GError *pError = NULL; + + /** Second step: Try to get a connection to the given bus. */ + pSkeleton = power_skeleton_new(); + + /** Third step: Attach to dbus signals. */ + (void) g_signal_connect(pSkeleton, "handle-transfer-int-value", G_CALLBACK(kylin_set_int), NULL); + + /** Fourth step: Export interface skeleton. */ + (void)g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(pSkeleton), + connection, + POWER_OBJECT_PATH, + &pError); + + if(pError != NULL){ + print_error("Error: Failed to export object. Reason: %s.\n", pError->message); + g_error_free(pError); + g_main_loop_quit(pLoop); + } +} + +static void name_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + print_info("name_acquired_cb call, Acquired bus name: %s.\n", POWER_BUS_NAME); +} + +static void name_lost_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + if(connection == NULL) + { + print_error("name_lost_cb call, Error: Failed to connect to dbus.\n"); + } + else + { + print_error("name_lost_cb call, Error: Failed to obtain bus name: %s.\n", POWER_BUS_NAME); + } + + g_main_loop_quit(pLoop); +} + +void* run(void* para) +{ + /** Start the Main Event Loop which manages all available sources of events */ + g_main_loop_run( pLoop ); + + return ((void*)0); +} + +int thread_create(void) +{ + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if (err != 0) + { + + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; +} + +bool InitDBusCommunicationServer(void) +{ + bool bRet = TRUE; + + g_print("InitDBusCommunicationServer: Server started.\n"); + + /** create main loop, but do not start it. */ + pLoop = g_main_loop_new(NULL, FALSE); + + /** first step: connect to dbus */ + (void)g_bus_own_name(POWER_BUS, + POWER_BUS_NAME, + G_BUS_NAME_OWNER_FLAGS_NONE, + &bus_acquired_cb, + &name_acquired_cb, + &name_lost_cb, + NULL, + NULL); + + thread_create(); + + return bRet; +} + +bool DeinitDBusCommunicationServer(void) +{ + bool bRet = FALSE; + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} + +int main(void) +{ + InitDBusCommunicationServer(); + + sleep(100); + + DeinitDBusCommunicationServer(); + return 0; +} diff --git a/src/hardware/power/kylin-screensaver-interface.c b/src/hardware/power/kylin-screensaver-interface.c new file mode 100644 index 0000000..1293aa9 --- /dev/null +++ b/src/hardware/power/kylin-screensaver-interface.c @@ -0,0 +1,147 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#define IAE "idle-activation-enabled" +#define LE "lock-enabled" + +static GMainLoop *pLoop = NULL; +static GDBusConnection *pConnection = NULL; +static Screensaver *pProxy = NULL; + +void kylin_hardware_power_idleactivationenabled(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=IAE; + arg=g_variant_new("(sb)", key, in_arg); + screensaver_call_transfer_bool_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_power_idleactivationenabled. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_hardware_power_lockenabled(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=LE; + arg=g_variant_new("(sb)", key, in_arg); + screensaver_call_transfer_bool_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_power_lockenabled. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void *run(void* arg) +{ + /** start the main event loop which manages all available sources of events */ + g_main_loop_run(pLoop); + + return ((void*)0); +} + +int thread_create(void) + { + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if(0 != err){ + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; + } + +bool InitDBusScreensaver(void) + { + bool bRet = TRUE; + GError *pConnError = NULL; + GError *pProxyError = NULL; + + do{ + bRet = TRUE; + pLoop = g_main_loop_new(NULL, FALSE); /** create main loop, but do not start it.*/ + + /** First step: get a connection */ + pConnection = g_bus_get_sync(SCREENSAVER_BUS, NULL, &pConnError); + + if (NULL == pConnError){ + /** Second step: try to get a connection to the given bus.*/ + pProxy = screensaver_proxy_new_sync(pConnection, + G_DBUS_PROXY_FLAGS_NONE, + SCREENSAVER_BUS_NAME, + SCREENSAVER_OBJECT_PATH, + NULL, + &pProxyError); + if (0 == pProxy){ + print_error("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message); + g_error_free(pProxyError); + bRet = FALSE; + } + + + } + else{ + print_error("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message); + g_error_free(pConnError); + bRet = FALSE; + } + }while(FALSE == bRet); + + thread_create(); + + return bRet; + } + +bool DeInitDBusScreensaver(void) +{ + bool bRet = FALSE; + + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} diff --git a/src/hardware/power/kylin-screensaver-interface.h b/src/hardware/power/kylin-screensaver-interface.h new file mode 100644 index 0000000..51057f0 --- /dev/null +++ b/src/hardware/power/kylin-screensaver-interface.h @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +//Initialize the DBus Communication +bool InitDBusScreensaver(void); + +//Delete the DBus Communication +bool DeInitDBusScreensaver(void); + +/* + * Set this to TRUE to activate the screensaver when the session is idle. + * + */ +void kylin_hardware_power_idleactivationenabled(const bool in_arg); + +/* + * Set this to TRUE to lock the screen when the screensaver goes active. + */ +void kylin_hardware_power_lockenabled(const bool in_arg); + +#ifdef __cplusplus +} +#endif + +#endif + + + + + + + + + + + + + diff --git a/src/hardware/power/kylin-screensaver-server.c b/src/hardware/power/kylin-screensaver-server.c new file mode 100644 index 0000000..72f6ceb --- /dev/null +++ b/src/hardware/power/kylin-screensaver-server.c @@ -0,0 +1,179 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include "screensaver-dbus.h" +#include "src/common/kylin-gsettings-set.h" +#include "src/common/kylin-print.h" +#include "screensaver-generated.h" +#include +#include + +#define schemaID "org.mate.screensaver" + +static GMainLoop *pLoop = NULL; +static Screensaver *pSkeleton = NULL; + +static gboolean kylin_set_bool(Screensaver* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gboolean value; + gint i; + g_variant_get(in_arg, "(sb)", &key, &value); + if(value==false)i=0; + else i=1; + + screensaver_complete_transfer_bool_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + gsettings_set_boolean(setting, key, value); + Dec_ref(setting); + + print_info("(%s, %d)\n", key, i); + + return TRUE; +} + +static void bus_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + + GError *pError = NULL; + + /** Second step: Try to get a connection to the given bus. */ + pSkeleton = screensaver_skeleton_new(); + + /** Third step: Attach to dbus signals. */ + (void) g_signal_connect(pSkeleton, "handle-transfer-bool-value", G_CALLBACK(kylin_set_bool), NULL); + + /** Fourth step: Export interface skeleton. */ + (void)g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(pSkeleton), + connection, + SCREENSAVER_OBJECT_PATH, + &pError); + + if(pError != NULL){ + print_error("Error: Failed to export object. Reason: %s.\n", pError->message); + g_error_free(pError); + g_main_loop_quit(pLoop); + } +} + +static void name_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + print_info("name_acquired_cb call, Acquired bus name: %s.\n", SCREENSAVER_BUS_NAME); +} + +static void name_lost_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + if(connection == NULL) + { + print_error("name_lost_cb call, Error: Failed to connect to dbus.\n"); + } + else + { + print_error("name_lost_cb call, Error: Failed to obtain bus name: %s.\n", SCREENSAVER_BUS_NAME); + } + + g_main_loop_quit(pLoop); +} + +void* run(void* para) +{ + /** Start the Main Event Loop which manages all available sources of events */ + g_main_loop_run( pLoop ); + + return ((void*)0); +} + +int thread_create(void) +{ + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if (err != 0) + { + + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; +} + +bool InitDBusCommunicationServer(void) +{ + bool bRet = TRUE; + + g_print("InitDBusCommunicationServer: Server started.\n"); + + /** create main loop, but do not start it. */ + pLoop = g_main_loop_new(NULL, FALSE); + + /** first step: connect to dbus */ + (void)g_bus_own_name(SCREENSAVER_BUS, + SCREENSAVER_BUS_NAME, + G_BUS_NAME_OWNER_FLAGS_NONE, + &bus_acquired_cb, + &name_acquired_cb, + &name_lost_cb, + NULL, + NULL); + + thread_create(); + + return bRet; +} + +bool DeinitDBusCommunicationServer(void) +{ + bool bRet = FALSE; + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} + +int main(void) +{ + InitDBusCommunicationServer(); + + sleep(100); + + DeinitDBusCommunicationServer(); + return 0; +} diff --git a/src/hardware/power/kylin-session-interface.c b/src/hardware/power/kylin-session-interface.c new file mode 100644 index 0000000..7869aca --- /dev/null +++ b/src/hardware/power/kylin-session-interface.c @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#define ID "idle-delay" + +static GMainLoop *pLoop = NULL; +static GDBusConnection *pConnection = NULL; +static Session *pProxy = NULL; + +void kylin_hardware_power_idledelay(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=ID; + arg=g_variant_new("(si)",key,in_arg); + session_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_power_idledelay. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; + +} + +void *run(void* arg) +{ + /** start the main event loop which manages all available sources of events */ + g_main_loop_run(pLoop); + + return ((void*)0); +} + +int thread_create(void) + { + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if(0 != err){ + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; + } + +bool InitDBusSession(void) + { + bool bRet = TRUE; + GError *pConnError = NULL; + GError *pProxyError = NULL; + + do{ + bRet = TRUE; + pLoop = g_main_loop_new(NULL, FALSE); /** create main loop, but do not start it.*/ + + /** First step: get a connection */ + pConnection = g_bus_get_sync(SESSION_BUS, NULL, &pConnError); + + if (NULL == pConnError){ + /** Second step: try to get a connection to the given bus.*/ + pProxy = session_proxy_new_sync(pConnection, + G_DBUS_PROXY_FLAGS_NONE, + SESSION_BUS_NAME, + SESSION_OBJECT_PATH, + NULL, + &pProxyError); + if (0 == pProxy){ + print_error("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message); + g_error_free(pProxyError); + bRet = FALSE; + } + + + } + else{ + print_error("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message); + g_error_free(pConnError); + bRet = FALSE; + } + }while(FALSE == bRet); + + thread_create(); + + return bRet; + } + +bool DeInitDBusSession(void) +{ + bool bRet = FALSE; + + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} diff --git a/src/hardware/power/kylin-session-interface.h b/src/hardware/power/kylin-session-interface.h new file mode 100644 index 0000000..9c7da38 --- /dev/null +++ b/src/hardware/power/kylin-session-interface.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +//Initialize the DBus Communication +bool InitDBusSession(void); + +//Delete the DBus Communication +bool DeInitDBusSession(void); + +/* + * Time before session is considered idle + */ +void kylin_hardware_power_idledelay(const int in_arg); + +#ifdef __cplusplus +} +#endif + +#endif + + + + + + + + + + + + + diff --git a/src/hardware/power/kylin-session-server.c b/src/hardware/power/kylin-session-server.c new file mode 100644 index 0000000..2266ec7 --- /dev/null +++ b/src/hardware/power/kylin-session-server.c @@ -0,0 +1,176 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include "session-dbus.h" +#include "src/common/kylin-gsettings-set.h" +#include "src/common/kylin-print.h" +#include "session-generated.h" +#include +#include + +#define schemaID "org.mate.session" + +static GMainLoop *pLoop = NULL; +static Session *pSkeleton = NULL; + +static gboolean kylin_set_int(Session* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gint value; + g_variant_get(in_arg, "(si)", &key, &value); + + session_complete_transfer_int_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + gsettings_set_int(setting, key, value); + Dec_ref(setting); + + print_info("(%s, %d)\n", key, value); + + return TRUE; +} + +static void bus_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + + GError *pError = NULL; + + /** Second step: Try to get a connection to the given bus. */ + pSkeleton = session_skeleton_new(); + + /** Third step: Attach to dbus signals. */ + (void) g_signal_connect(pSkeleton, "handle-transfer-int-value", G_CALLBACK(kylin_set_int), NULL); + + /** Fourth step: Export interface skeleton. */ + (void)g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(pSkeleton), + connection, + SESSION_OBJECT_PATH, + &pError); + + if(pError != NULL){ + print_error("Error: Failed to export object. Reason: %s.\n", pError->message); + g_error_free(pError); + g_main_loop_quit(pLoop); + } +} + +static void name_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + print_info("name_acquired_cb call, Acquired bus name: %s.\n", SESSION_BUS_NAME); +} + +static void name_lost_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + if(connection == NULL) + { + print_error("name_lost_cb call, Error: Failed to connect to dbus.\n"); + } + else + { + print_error("name_lost_cb call, Error: Failed to obtain bus name: %s.\n", SESSION_BUS_NAME); + } + + g_main_loop_quit(pLoop); +} + +void* run(void* para) +{ + /** Start the Main Event Loop which manages all available sources of events */ + g_main_loop_run( pLoop ); + + return ((void*)0); +} + +int thread_create(void) +{ + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if (err != 0) + { + + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; +} + +bool InitDBusCommunicationServer(void) +{ + bool bRet = TRUE; + + g_print("InitDBusCommunicationServer: Server started.\n"); + + /** create main loop, but do not start it. */ + pLoop = g_main_loop_new(NULL, FALSE); + + /** first step: connect to dbus */ + (void)g_bus_own_name(SESSION_BUS, + SESSION_BUS_NAME, + G_BUS_NAME_OWNER_FLAGS_NONE, + &bus_acquired_cb, + &name_acquired_cb, + &name_lost_cb, + NULL, + NULL); + + thread_create(); + + return bRet; +} + +bool DeinitDBusCommunicationServer(void) +{ + bool bRet = FALSE; + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} + +int main(void) +{ + InitDBusCommunicationServer(); + + sleep(100); + + DeinitDBusCommunicationServer(); + return 0; +} diff --git a/src/hardware/power/power-dbus.h b/src/hardware/power/power-dbus.h new file mode 100644 index 0000000..f5effef --- /dev/null +++ b/src/hardware/power/power-dbus.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 /* Bus define */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define POWER_BUS G_BUS_TYPE_SESSION +#define POWER_BUS_NAME "cn.kylinos.power" +#define POWER_OBJECT_PATH "/cn/kylinos/power" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/hardware/power/power-generated.c b/src/hardware/power/power-generated.c new file mode 100644 index 0000000..e16c909 --- /dev/null +++ b/src/hardware/power/power-generated.c @@ -0,0 +1,1050 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#ifdef G_OS_UNIX +# include +#endif + +typedef struct +{ + GDBusArgInfo parent_struct; + gboolean use_gvariant; +} _ExtendedGDBusArgInfo; + +typedef struct +{ + GDBusMethodInfo parent_struct; + const gchar *signal_name; + gboolean pass_fdlist; +} _ExtendedGDBusMethodInfo; + +typedef struct +{ + GDBusSignalInfo parent_struct; + const gchar *signal_name; +} _ExtendedGDBusSignalInfo; + +typedef struct +{ + GDBusPropertyInfo parent_struct; + const gchar *hyphen_name; + guint use_gvariant : 1; + guint emits_changed_signal : 1; +} _ExtendedGDBusPropertyInfo; + +typedef struct +{ + GDBusInterfaceInfo parent_struct; + const gchar *hyphen_name; +} _ExtendedGDBusInterfaceInfo; + +typedef struct +{ + const _ExtendedGDBusPropertyInfo *info; + guint prop_id; + GValue orig_value; /* the value before the change */ +} ChangedProperty; + +static void +_changed_property_free (ChangedProperty *data) +{ + g_value_unset (&data->orig_value); + g_free (data); +} + +static gboolean +_g_strv_equal0 (gchar **a, gchar **b) +{ + gboolean ret = FALSE; + guint n; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + if (g_strv_length (a) != g_strv_length (b)) + goto out; + for (n = 0; a[n] != NULL; n++) + if (g_strcmp0 (a[n], b[n]) != 0) + goto out; + ret = TRUE; +out: + return ret; +} + +static gboolean +_g_variant_equal0 (GVariant *a, GVariant *b) +{ + gboolean ret = FALSE; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + ret = g_variant_equal (a, b); +out: + return ret; +} + +G_GNUC_UNUSED static gboolean +_g_value_equal (const GValue *a, const GValue *b) +{ + gboolean ret = FALSE; + g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); + switch (G_VALUE_TYPE (a)) + { + case G_TYPE_BOOLEAN: + ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); + break; + case G_TYPE_UCHAR: + ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); + break; + case G_TYPE_INT: + ret = (g_value_get_int (a) == g_value_get_int (b)); + break; + case G_TYPE_UINT: + ret = (g_value_get_uint (a) == g_value_get_uint (b)); + break; + case G_TYPE_INT64: + ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); + break; + case G_TYPE_UINT64: + ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); + break; + case G_TYPE_DOUBLE: + { + /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ + gdouble da = g_value_get_double (a); + gdouble db = g_value_get_double (b); + ret = memcmp (&da, &db, sizeof (gdouble)) == 0; + } + break; + case G_TYPE_STRING: + ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); + break; + case G_TYPE_VARIANT: + ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); + break; + default: + if (G_VALUE_TYPE (a) == G_TYPE_STRV) + ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); + else + g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); + break; + } + return ret; +} + +/* ------------------------------------------------------------------------ + * Code for interface cn.kylinos.power + * ------------------------------------------------------------------------ + */ + +/** + * SECTION:Power + * @title: Power + * @short_description: Generated C code for the cn.kylinos.power D-Bus interface + * + * This section contains code for working with the cn.kylinos.power D-Bus interface in C. + */ + +/* ---- Introspection data for cn.kylinos.power ---- */ + +static const _ExtendedGDBusArgInfo _power_method_info_transfer_int_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(si)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _power_method_info_transfer_int_value_IN_ARG_pointers[] = +{ + &_power_method_info_transfer_int_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _power_method_info_transfer_int_value = +{ + { + -1, + (gchar *) "TransferIntValue", + (GDBusArgInfo **) &_power_method_info_transfer_int_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-int-value", + FALSE +}; + +static const GDBusMethodInfo * const _power_method_info_pointers[] = +{ + &_power_method_info_transfer_int_value.parent_struct, + NULL +}; + +static const _ExtendedGDBusInterfaceInfo _power_interface_info = +{ + { + -1, + (gchar *) "cn.kylinos.power", + (GDBusMethodInfo **) &_power_method_info_pointers, + NULL, + NULL, + NULL + }, + "power", +}; + + +/** + * power_interface_info: + * + * Gets a machine-readable description of the cn.kylinos.power D-Bus interface. + * + * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. + */ +GDBusInterfaceInfo * +power_interface_info (void) +{ + return (GDBusInterfaceInfo *) &_power_interface_info.parent_struct; +} + +/** + * power_override_properties: + * @klass: The class structure for a #GObject derived class. + * @property_id_begin: The property id to assign to the first overridden property. + * + * Overrides all #GObject properties in the #Power interface for a concrete class. + * The properties are overridden in the order they are defined. + * + * Returns: The last property id. + */ +guint +power_override_properties (GObjectClass *klass, guint property_id_begin) +{ + return property_id_begin - 1; +} + + + +/** + * Power: + * + * Abstract interface type for the D-Bus interface cn.kylinos.power. + */ + +/** + * PowerIface: + * @parent_iface: The parent interface. + * @handle_transfer_int_value: Handler for the #Power::handle-transfer-int-value signal. + * + * Virtual table for the D-Bus interface cn.kylinos.power. + */ + +typedef PowerIface PowerInterface; +G_DEFINE_INTERFACE (Power, power, G_TYPE_OBJECT) + +static void +power_default_init (PowerIface *iface) +{ + /* GObject signals for incoming D-Bus method calls: */ + /** + * Power::handle-transfer-int-value: + * @object: A #Power. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferIntValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call power_complete_transfer_int_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-int-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (PowerIface, handle_transfer_int_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + +} + +/** + * power_call_transfer_int_value: + * @proxy: A #PowerProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferIntValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call power_call_transfer_int_value_finish() to get the result of the operation. + * + * See power_call_transfer_int_value_sync() for the synchronous, blocking version of this method. + */ +void +power_call_transfer_int_value ( + Power *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * power_call_transfer_int_value_finish: + * @proxy: A #PowerProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to power_call_transfer_int_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with power_call_transfer_int_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +power_call_transfer_int_value_finish ( + Power *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * power_call_transfer_int_value_sync: + * @proxy: A #PowerProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferIntValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See power_call_transfer_int_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +power_call_transfer_int_value_sync ( + Power *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * power_complete_transfer_int_value: + * @object: A #Power. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferIntValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +power_complete_transfer_int_value ( + Power *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/* ------------------------------------------------------------------------ */ + +/** + * PowerProxy: + * + * The #PowerProxy structure contains only private data and should only be accessed using the provided API. + */ + +/** + * PowerProxyClass: + * @parent_class: The parent class. + * + * Class structure for #PowerProxy. + */ + +struct _PowerProxyPrivate +{ + GData *qdata; +}; + +static void power_proxy_iface_init (PowerIface *iface); + +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (PowerProxy, power_proxy, G_TYPE_DBUS_PROXY, + G_ADD_PRIVATE (PowerProxy) + G_IMPLEMENT_INTERFACE (TYPE_POWER, power_proxy_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (PowerProxy, power_proxy, G_TYPE_DBUS_PROXY, + G_IMPLEMENT_INTERFACE (TYPE_POWER, power_proxy_iface_init)) + +#endif +static void +power_proxy_finalize (GObject *object) +{ + PowerProxy *proxy = POWER_PROXY (object); + g_datalist_clear (&proxy->priv->qdata); + G_OBJECT_CLASS (power_proxy_parent_class)->finalize (object); +} + +static void +power_proxy_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +power_proxy_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +power_proxy_g_signal (GDBusProxy *proxy, + const gchar *sender_name G_GNUC_UNUSED, + const gchar *signal_name, + GVariant *parameters) +{ + _ExtendedGDBusSignalInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + gsize n; + guint signal_id; + info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_power_interface_info.parent_struct, signal_name); + if (info == NULL) + return; + num_params = g_variant_n_children (parameters); + paramv = g_new0 (GValue, num_params + 1); + g_value_init (¶mv[0], TYPE_POWER); + g_value_set_object (¶mv[0], proxy); + g_variant_iter_init (&iter, parameters); + n = 1; + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_POWER); + g_signal_emitv (paramv, signal_id, 0, NULL); + for (n = 0; n < num_params + 1; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static void +power_proxy_g_properties_changed (GDBusProxy *_proxy, + GVariant *changed_properties, + const gchar *const *invalidated_properties) +{ + PowerProxy *proxy = POWER_PROXY (_proxy); + guint n; + const gchar *key; + GVariantIter *iter; + _ExtendedGDBusPropertyInfo *info; + g_variant_get (changed_properties, "a{sv}", &iter); + while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_power_interface_info.parent_struct, key); + g_datalist_remove_data (&proxy->priv->qdata, key); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } + g_variant_iter_free (iter); + for (n = 0; invalidated_properties[n] != NULL; n++) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_power_interface_info.parent_struct, invalidated_properties[n]); + g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } +} + +static void +power_proxy_init (PowerProxy *proxy) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + proxy->priv = power_proxy_get_instance_private (proxy); +#else + proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, TYPE_POWER_PROXY, PowerProxyPrivate); +#endif + + g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), power_interface_info ()); +} + +static void +power_proxy_class_init (PowerProxyClass *klass) +{ + GObjectClass *gobject_class; + GDBusProxyClass *proxy_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = power_proxy_finalize; + gobject_class->get_property = power_proxy_get_property; + gobject_class->set_property = power_proxy_set_property; + + proxy_class = G_DBUS_PROXY_CLASS (klass); + proxy_class->g_signal = power_proxy_g_signal; + proxy_class->g_properties_changed = power_proxy_g_properties_changed; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (PowerProxyPrivate)); +#endif +} + +static void +power_proxy_iface_init (PowerIface *iface) +{ +} + +/** + * power_proxy_new: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Asynchronously creates a proxy for the D-Bus interface cn.kylinos.power. See g_dbus_proxy_new() for more details. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call power_proxy_new_finish() to get the result of the operation. + * + * See power_proxy_new_sync() for the synchronous, blocking version of this constructor. + */ +void +power_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_POWER_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.power", NULL); +} + +/** + * power_proxy_new_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to power_proxy_new(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with power_proxy_new(). + * + * Returns: (transfer full) (type PowerProxy): The constructed proxy object or %NULL if @error is set. + */ +Power * +power_proxy_new_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return POWER (ret); + else + return NULL; +} + +/** + * power_proxy_new_sync: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Synchronously creates a proxy for the D-Bus interface cn.kylinos.power. See g_dbus_proxy_new_sync() for more details. + * + * The calling thread is blocked until a reply is received. + * + * See power_proxy_new() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type PowerProxy): The constructed proxy object or %NULL if @error is set. + */ +Power * +power_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_POWER_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.power", NULL); + if (ret != NULL) + return POWER (ret); + else + return NULL; +} + + +/** + * power_proxy_new_for_bus: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Like power_proxy_new() but takes a #GBusType instead of a #GDBusConnection. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call power_proxy_new_for_bus_finish() to get the result of the operation. + * + * See power_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. + */ +void +power_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_POWER_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.power", NULL); +} + +/** + * power_proxy_new_for_bus_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to power_proxy_new_for_bus(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with power_proxy_new_for_bus(). + * + * Returns: (transfer full) (type PowerProxy): The constructed proxy object or %NULL if @error is set. + */ +Power * +power_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return POWER (ret); + else + return NULL; +} + +/** + * power_proxy_new_for_bus_sync: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Like power_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. + * + * The calling thread is blocked until a reply is received. + * + * See power_proxy_new_for_bus() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type PowerProxy): The constructed proxy object or %NULL if @error is set. + */ +Power * +power_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_POWER_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.power", NULL); + if (ret != NULL) + return POWER (ret); + else + return NULL; +} + + +/* ------------------------------------------------------------------------ */ + +/** + * PowerSkeleton: + * + * The #PowerSkeleton structure contains only private data and should only be accessed using the provided API. + */ + +/** + * PowerSkeletonClass: + * @parent_class: The parent class. + * + * Class structure for #PowerSkeleton. + */ + +struct _PowerSkeletonPrivate +{ + GValue *properties; + GList *changed_properties; + GSource *changed_properties_idle_source; + GMainContext *context; + GMutex lock; +}; + +static void +_power_skeleton_handle_method_call ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name, + const gchar *method_name, + GVariant *parameters, + GDBusMethodInvocation *invocation, + gpointer user_data) +{ + PowerSkeleton *skeleton = POWER_SKELETON (user_data); + _ExtendedGDBusMethodInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + guint num_extra; + gsize n; + guint signal_id; + GValue return_value = G_VALUE_INIT; + info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); + g_assert (info != NULL); + num_params = g_variant_n_children (parameters); + num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); + n = 0; + g_value_init (¶mv[n], TYPE_POWER); + g_value_set_object (¶mv[n++], skeleton); + g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); + g_value_set_object (¶mv[n++], invocation); + if (info->pass_fdlist) + { +#ifdef G_OS_UNIX + g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); + g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); +#else + g_assert_not_reached (); +#endif + } + g_variant_iter_init (&iter, parameters); + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_POWER); + g_value_init (&return_value, G_TYPE_BOOLEAN); + g_signal_emitv (paramv, signal_id, 0, &return_value); + if (!g_value_get_boolean (&return_value)) + g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); + g_value_unset (&return_value); + for (n = 0; n < num_params + num_extra; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static GVariant * +_power_skeleton_handle_get_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GError **error, + gpointer user_data) +{ + PowerSkeleton *skeleton = POWER_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + GVariant *ret; + ret = NULL; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_power_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + g_value_init (&value, pspec->value_type); + g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); + ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); + g_value_unset (&value); + } + return ret; +} + +static gboolean +_power_skeleton_handle_set_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GVariant *variant, + GError **error, + gpointer user_data) +{ + PowerSkeleton *skeleton = POWER_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + gboolean ret; + ret = FALSE; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_power_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + if (info->use_gvariant) + g_value_set_variant (&value, variant); + else + g_dbus_gvariant_to_gvalue (variant, &value); + g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); + g_value_unset (&value); + ret = TRUE; + } + return ret; +} + +static const GDBusInterfaceVTable _power_skeleton_vtable = +{ + _power_skeleton_handle_method_call, + _power_skeleton_handle_get_property, + _power_skeleton_handle_set_property, + {NULL} +}; + +static GDBusInterfaceInfo * +power_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return power_interface_info (); +} + +static GDBusInterfaceVTable * +power_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return (GDBusInterfaceVTable *) &_power_skeleton_vtable; +} + +static GVariant * +power_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) +{ + PowerSkeleton *skeleton = POWER_SKELETON (_skeleton); + + GVariantBuilder builder; + guint n; + g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); + if (_power_interface_info.parent_struct.properties == NULL) + goto out; + for (n = 0; _power_interface_info.parent_struct.properties[n] != NULL; n++) + { + GDBusPropertyInfo *info = _power_interface_info.parent_struct.properties[n]; + if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) + { + GVariant *value; + value = _power_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "cn.kylinos.power", info->name, NULL, skeleton); + if (value != NULL) + { + g_variant_take_ref (value); + g_variant_builder_add (&builder, "{sv}", info->name, value); + g_variant_unref (value); + } + } + } +out: + return g_variant_builder_end (&builder); +} + +static void +power_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) +{ +} + +static void power_skeleton_iface_init (PowerIface *iface); +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (PowerSkeleton, power_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_ADD_PRIVATE (PowerSkeleton) + G_IMPLEMENT_INTERFACE (TYPE_POWER, power_skeleton_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (PowerSkeleton, power_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_IMPLEMENT_INTERFACE (TYPE_POWER, power_skeleton_iface_init)) + +#endif +static void +power_skeleton_finalize (GObject *object) +{ + PowerSkeleton *skeleton = POWER_SKELETON (object); + g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); + if (skeleton->priv->changed_properties_idle_source != NULL) + g_source_destroy (skeleton->priv->changed_properties_idle_source); + g_main_context_unref (skeleton->priv->context); + g_mutex_clear (&skeleton->priv->lock); + G_OBJECT_CLASS (power_skeleton_parent_class)->finalize (object); +} + +static void +power_skeleton_init (PowerSkeleton *skeleton) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + skeleton->priv = power_skeleton_get_instance_private (skeleton); +#else + skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_POWER_SKELETON, PowerSkeletonPrivate); +#endif + + g_mutex_init (&skeleton->priv->lock); + skeleton->priv->context = g_main_context_ref_thread_default (); +} + +static void +power_skeleton_class_init (PowerSkeletonClass *klass) +{ + GObjectClass *gobject_class; + GDBusInterfaceSkeletonClass *skeleton_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = power_skeleton_finalize; + + skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); + skeleton_class->get_info = power_skeleton_dbus_interface_get_info; + skeleton_class->get_properties = power_skeleton_dbus_interface_get_properties; + skeleton_class->flush = power_skeleton_dbus_interface_flush; + skeleton_class->get_vtable = power_skeleton_dbus_interface_get_vtable; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (PowerSkeletonPrivate)); +#endif +} + +static void +power_skeleton_iface_init (PowerIface *iface) +{ +} + +/** + * power_skeleton_new: + * + * Creates a skeleton object for the D-Bus interface cn.kylinos.power. + * + * Returns: (transfer full) (type PowerSkeleton): The skeleton object. + */ +Power * +power_skeleton_new (void) +{ + return POWER (g_object_new (TYPE_POWER_SKELETON, NULL)); +} + diff --git a/src/hardware/power/power-generated.h b/src/hardware/power/power-generated.h new file mode 100644 index 0000000..a4dc045 --- /dev/null +++ b/src/hardware/power/power-generated.h @@ -0,0 +1,190 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +G_BEGIN_DECLS + + +/* ------------------------------------------------------------------------ */ +/* Declarations for cn.kylinos.power */ + +#define TYPE_POWER (power_get_type ()) +#define POWER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_POWER, Power)) +#define IS_POWER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_POWER)) +#define POWER_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), TYPE_POWER, PowerIface)) + +struct _Power; +typedef struct _Power Power; +typedef struct _PowerIface PowerIface; + +struct _PowerIface +{ + GTypeInterface parent_iface; + + gboolean (*handle_transfer_int_value) ( + Power *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + +}; + +GType power_get_type (void) G_GNUC_CONST; + +GDBusInterfaceInfo *power_interface_info (void); +guint power_override_properties (GObjectClass *klass, guint property_id_begin); + + +/* D-Bus method call completion functions: */ +void power_complete_transfer_int_value ( + Power *object, + GDBusMethodInvocation *invocation); + + + +/* D-Bus method calls: */ +void power_call_transfer_int_value ( + Power *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean power_call_transfer_int_value_finish ( + Power *proxy, + GAsyncResult *res, + GError **error); + +gboolean power_call_transfer_int_value_sync ( + Power *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + + + +/* ---- */ + +#define TYPE_POWER_PROXY (power_proxy_get_type ()) +#define POWER_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_POWER_PROXY, PowerProxy)) +#define POWER_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_POWER_PROXY, PowerProxyClass)) +#define POWER_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_POWER_PROXY, PowerProxyClass)) +#define IS_POWER_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_POWER_PROXY)) +#define IS_POWER_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_POWER_PROXY)) + +typedef struct _PowerProxy PowerProxy; +typedef struct _PowerProxyClass PowerProxyClass; +typedef struct _PowerProxyPrivate PowerProxyPrivate; + +struct _PowerProxy +{ + /*< private >*/ + GDBusProxy parent_instance; + PowerProxyPrivate *priv; +}; + +struct _PowerProxyClass +{ + GDBusProxyClass parent_class; +}; + +GType power_proxy_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (PowerProxy, g_object_unref) +#endif + +void power_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Power *power_proxy_new_finish ( + GAsyncResult *res, + GError **error); +Power *power_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + +void power_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Power *power_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error); +Power *power_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + + +/* ---- */ + +#define TYPE_POWER_SKELETON (power_skeleton_get_type ()) +#define POWER_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_POWER_SKELETON, PowerSkeleton)) +#define POWER_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_POWER_SKELETON, PowerSkeletonClass)) +#define POWER_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_POWER_SKELETON, PowerSkeletonClass)) +#define IS_POWER_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_POWER_SKELETON)) +#define IS_POWER_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_POWER_SKELETON)) + +typedef struct _PowerSkeleton PowerSkeleton; +typedef struct _PowerSkeletonClass PowerSkeletonClass; +typedef struct _PowerSkeletonPrivate PowerSkeletonPrivate; + +struct _PowerSkeleton +{ + /*< private >*/ + GDBusInterfaceSkeleton parent_instance; + PowerSkeletonPrivate *priv; +}; + +struct _PowerSkeletonClass +{ + GDBusInterfaceSkeletonClass parent_class; +}; + +GType power_skeleton_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (PowerSkeleton, g_object_unref) +#endif + +Power *power_skeleton_new (void); + + +G_END_DECLS + +#endif /* __POWER_GENERATED_H__ */ diff --git a/src/hardware/power/screensaver-dbus.h b/src/hardware/power/screensaver-dbus.h new file mode 100644 index 0000000..1c515fb --- /dev/null +++ b/src/hardware/power/screensaver-dbus.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 /* Bus define */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define SCREENSAVER_BUS G_BUS_TYPE_SESSION +#define SCREENSAVER_BUS_NAME "cn.kylinos.screensaver" +#define SCREENSAVER_OBJECT_PATH "/cn/kylinos/screensaver" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/hardware/power/screensaver-generated.c b/src/hardware/power/screensaver-generated.c new file mode 100644 index 0000000..7d5f980 --- /dev/null +++ b/src/hardware/power/screensaver-generated.c @@ -0,0 +1,1050 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#ifdef G_OS_UNIX +# include +#endif + +typedef struct +{ + GDBusArgInfo parent_struct; + gboolean use_gvariant; +} _ExtendedGDBusArgInfo; + +typedef struct +{ + GDBusMethodInfo parent_struct; + const gchar *signal_name; + gboolean pass_fdlist; +} _ExtendedGDBusMethodInfo; + +typedef struct +{ + GDBusSignalInfo parent_struct; + const gchar *signal_name; +} _ExtendedGDBusSignalInfo; + +typedef struct +{ + GDBusPropertyInfo parent_struct; + const gchar *hyphen_name; + guint use_gvariant : 1; + guint emits_changed_signal : 1; +} _ExtendedGDBusPropertyInfo; + +typedef struct +{ + GDBusInterfaceInfo parent_struct; + const gchar *hyphen_name; +} _ExtendedGDBusInterfaceInfo; + +typedef struct +{ + const _ExtendedGDBusPropertyInfo *info; + guint prop_id; + GValue orig_value; /* the value before the change */ +} ChangedProperty; + +static void +_changed_property_free (ChangedProperty *data) +{ + g_value_unset (&data->orig_value); + g_free (data); +} + +static gboolean +_g_strv_equal0 (gchar **a, gchar **b) +{ + gboolean ret = FALSE; + guint n; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + if (g_strv_length (a) != g_strv_length (b)) + goto out; + for (n = 0; a[n] != NULL; n++) + if (g_strcmp0 (a[n], b[n]) != 0) + goto out; + ret = TRUE; +out: + return ret; +} + +static gboolean +_g_variant_equal0 (GVariant *a, GVariant *b) +{ + gboolean ret = FALSE; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + ret = g_variant_equal (a, b); +out: + return ret; +} + +G_GNUC_UNUSED static gboolean +_g_value_equal (const GValue *a, const GValue *b) +{ + gboolean ret = FALSE; + g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); + switch (G_VALUE_TYPE (a)) + { + case G_TYPE_BOOLEAN: + ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); + break; + case G_TYPE_UCHAR: + ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); + break; + case G_TYPE_INT: + ret = (g_value_get_int (a) == g_value_get_int (b)); + break; + case G_TYPE_UINT: + ret = (g_value_get_uint (a) == g_value_get_uint (b)); + break; + case G_TYPE_INT64: + ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); + break; + case G_TYPE_UINT64: + ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); + break; + case G_TYPE_DOUBLE: + { + /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ + gdouble da = g_value_get_double (a); + gdouble db = g_value_get_double (b); + ret = memcmp (&da, &db, sizeof (gdouble)) == 0; + } + break; + case G_TYPE_STRING: + ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); + break; + case G_TYPE_VARIANT: + ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); + break; + default: + if (G_VALUE_TYPE (a) == G_TYPE_STRV) + ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); + else + g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); + break; + } + return ret; +} + +/* ------------------------------------------------------------------------ + * Code for interface cn.kylinos.screensaver + * ------------------------------------------------------------------------ + */ + +/** + * SECTION:Screensaver + * @title: Screensaver + * @short_description: Generated C code for the cn.kylinos.screensaver D-Bus interface + * + * This section contains code for working with the cn.kylinos.screensaver D-Bus interface in C. + */ + +/* ---- Introspection data for cn.kylinos.screensaver ---- */ + +static const _ExtendedGDBusArgInfo _screensaver_method_info_transfer_bool_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(sb)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _screensaver_method_info_transfer_bool_value_IN_ARG_pointers[] = +{ + &_screensaver_method_info_transfer_bool_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _screensaver_method_info_transfer_bool_value = +{ + { + -1, + (gchar *) "TransferBoolValue", + (GDBusArgInfo **) &_screensaver_method_info_transfer_bool_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-bool-value", + FALSE +}; + +static const GDBusMethodInfo * const _screensaver_method_info_pointers[] = +{ + &_screensaver_method_info_transfer_bool_value.parent_struct, + NULL +}; + +static const _ExtendedGDBusInterfaceInfo _screensaver_interface_info = +{ + { + -1, + (gchar *) "cn.kylinos.screensaver", + (GDBusMethodInfo **) &_screensaver_method_info_pointers, + NULL, + NULL, + NULL + }, + "screensaver", +}; + + +/** + * screensaver_interface_info: + * + * Gets a machine-readable description of the cn.kylinos.screensaver D-Bus interface. + * + * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. + */ +GDBusInterfaceInfo * +screensaver_interface_info (void) +{ + return (GDBusInterfaceInfo *) &_screensaver_interface_info.parent_struct; +} + +/** + * screensaver_override_properties: + * @klass: The class structure for a #GObject derived class. + * @property_id_begin: The property id to assign to the first overridden property. + * + * Overrides all #GObject properties in the #Screensaver interface for a concrete class. + * The properties are overridden in the order they are defined. + * + * Returns: The last property id. + */ +guint +screensaver_override_properties (GObjectClass *klass, guint property_id_begin) +{ + return property_id_begin - 1; +} + + + +/** + * Screensaver: + * + * Abstract interface type for the D-Bus interface cn.kylinos.screensaver. + */ + +/** + * ScreensaverIface: + * @parent_iface: The parent interface. + * @handle_transfer_bool_value: Handler for the #Screensaver::handle-transfer-bool-value signal. + * + * Virtual table for the D-Bus interface cn.kylinos.screensaver. + */ + +typedef ScreensaverIface ScreensaverInterface; +G_DEFINE_INTERFACE (Screensaver, screensaver, G_TYPE_OBJECT) + +static void +screensaver_default_init (ScreensaverIface *iface) +{ + /* GObject signals for incoming D-Bus method calls: */ + /** + * Screensaver::handle-transfer-bool-value: + * @object: A #Screensaver. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferBoolValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call screensaver_complete_transfer_bool_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-bool-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (ScreensaverIface, handle_transfer_bool_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + +} + +/** + * screensaver_call_transfer_bool_value: + * @proxy: A #ScreensaverProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferBoolValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call screensaver_call_transfer_bool_value_finish() to get the result of the operation. + * + * See screensaver_call_transfer_bool_value_sync() for the synchronous, blocking version of this method. + */ +void +screensaver_call_transfer_bool_value ( + Screensaver *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * screensaver_call_transfer_bool_value_finish: + * @proxy: A #ScreensaverProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to screensaver_call_transfer_bool_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with screensaver_call_transfer_bool_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +screensaver_call_transfer_bool_value_finish ( + Screensaver *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * screensaver_call_transfer_bool_value_sync: + * @proxy: A #ScreensaverProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferBoolValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See screensaver_call_transfer_bool_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +screensaver_call_transfer_bool_value_sync ( + Screensaver *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * screensaver_complete_transfer_bool_value: + * @object: A #Screensaver. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferBoolValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +screensaver_complete_transfer_bool_value ( + Screensaver *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/* ------------------------------------------------------------------------ */ + +/** + * ScreensaverProxy: + * + * The #ScreensaverProxy structure contains only private data and should only be accessed using the provided API. + */ + +/** + * ScreensaverProxyClass: + * @parent_class: The parent class. + * + * Class structure for #ScreensaverProxy. + */ + +struct _ScreensaverProxyPrivate +{ + GData *qdata; +}; + +static void screensaver_proxy_iface_init (ScreensaverIface *iface); + +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (ScreensaverProxy, screensaver_proxy, G_TYPE_DBUS_PROXY, + G_ADD_PRIVATE (ScreensaverProxy) + G_IMPLEMENT_INTERFACE (TYPE_SCREENSAVER, screensaver_proxy_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (ScreensaverProxy, screensaver_proxy, G_TYPE_DBUS_PROXY, + G_IMPLEMENT_INTERFACE (TYPE_SCREENSAVER, screensaver_proxy_iface_init)) + +#endif +static void +screensaver_proxy_finalize (GObject *object) +{ + ScreensaverProxy *proxy = SCREENSAVER_PROXY (object); + g_datalist_clear (&proxy->priv->qdata); + G_OBJECT_CLASS (screensaver_proxy_parent_class)->finalize (object); +} + +static void +screensaver_proxy_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +screensaver_proxy_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +screensaver_proxy_g_signal (GDBusProxy *proxy, + const gchar *sender_name G_GNUC_UNUSED, + const gchar *signal_name, + GVariant *parameters) +{ + _ExtendedGDBusSignalInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + gsize n; + guint signal_id; + info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_screensaver_interface_info.parent_struct, signal_name); + if (info == NULL) + return; + num_params = g_variant_n_children (parameters); + paramv = g_new0 (GValue, num_params + 1); + g_value_init (¶mv[0], TYPE_SCREENSAVER); + g_value_set_object (¶mv[0], proxy); + g_variant_iter_init (&iter, parameters); + n = 1; + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_SCREENSAVER); + g_signal_emitv (paramv, signal_id, 0, NULL); + for (n = 0; n < num_params + 1; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static void +screensaver_proxy_g_properties_changed (GDBusProxy *_proxy, + GVariant *changed_properties, + const gchar *const *invalidated_properties) +{ + ScreensaverProxy *proxy = SCREENSAVER_PROXY (_proxy); + guint n; + const gchar *key; + GVariantIter *iter; + _ExtendedGDBusPropertyInfo *info; + g_variant_get (changed_properties, "a{sv}", &iter); + while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_screensaver_interface_info.parent_struct, key); + g_datalist_remove_data (&proxy->priv->qdata, key); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } + g_variant_iter_free (iter); + for (n = 0; invalidated_properties[n] != NULL; n++) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_screensaver_interface_info.parent_struct, invalidated_properties[n]); + g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } +} + +static void +screensaver_proxy_init (ScreensaverProxy *proxy) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + proxy->priv = screensaver_proxy_get_instance_private (proxy); +#else + proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, TYPE_SCREENSAVER_PROXY, ScreensaverProxyPrivate); +#endif + + g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), screensaver_interface_info ()); +} + +static void +screensaver_proxy_class_init (ScreensaverProxyClass *klass) +{ + GObjectClass *gobject_class; + GDBusProxyClass *proxy_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = screensaver_proxy_finalize; + gobject_class->get_property = screensaver_proxy_get_property; + gobject_class->set_property = screensaver_proxy_set_property; + + proxy_class = G_DBUS_PROXY_CLASS (klass); + proxy_class->g_signal = screensaver_proxy_g_signal; + proxy_class->g_properties_changed = screensaver_proxy_g_properties_changed; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (ScreensaverProxyPrivate)); +#endif +} + +static void +screensaver_proxy_iface_init (ScreensaverIface *iface) +{ +} + +/** + * screensaver_proxy_new: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Asynchronously creates a proxy for the D-Bus interface cn.kylinos.screensaver. See g_dbus_proxy_new() for more details. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call screensaver_proxy_new_finish() to get the result of the operation. + * + * See screensaver_proxy_new_sync() for the synchronous, blocking version of this constructor. + */ +void +screensaver_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_SCREENSAVER_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.screensaver", NULL); +} + +/** + * screensaver_proxy_new_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to screensaver_proxy_new(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with screensaver_proxy_new(). + * + * Returns: (transfer full) (type ScreensaverProxy): The constructed proxy object or %NULL if @error is set. + */ +Screensaver * +screensaver_proxy_new_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return SCREENSAVER (ret); + else + return NULL; +} + +/** + * screensaver_proxy_new_sync: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Synchronously creates a proxy for the D-Bus interface cn.kylinos.screensaver. See g_dbus_proxy_new_sync() for more details. + * + * The calling thread is blocked until a reply is received. + * + * See screensaver_proxy_new() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type ScreensaverProxy): The constructed proxy object or %NULL if @error is set. + */ +Screensaver * +screensaver_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_SCREENSAVER_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.screensaver", NULL); + if (ret != NULL) + return SCREENSAVER (ret); + else + return NULL; +} + + +/** + * screensaver_proxy_new_for_bus: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Like screensaver_proxy_new() but takes a #GBusType instead of a #GDBusConnection. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call screensaver_proxy_new_for_bus_finish() to get the result of the operation. + * + * See screensaver_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. + */ +void +screensaver_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_SCREENSAVER_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.screensaver", NULL); +} + +/** + * screensaver_proxy_new_for_bus_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to screensaver_proxy_new_for_bus(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with screensaver_proxy_new_for_bus(). + * + * Returns: (transfer full) (type ScreensaverProxy): The constructed proxy object or %NULL if @error is set. + */ +Screensaver * +screensaver_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return SCREENSAVER (ret); + else + return NULL; +} + +/** + * screensaver_proxy_new_for_bus_sync: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Like screensaver_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. + * + * The calling thread is blocked until a reply is received. + * + * See screensaver_proxy_new_for_bus() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type ScreensaverProxy): The constructed proxy object or %NULL if @error is set. + */ +Screensaver * +screensaver_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_SCREENSAVER_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.screensaver", NULL); + if (ret != NULL) + return SCREENSAVER (ret); + else + return NULL; +} + + +/* ------------------------------------------------------------------------ */ + +/** + * ScreensaverSkeleton: + * + * The #ScreensaverSkeleton structure contains only private data and should only be accessed using the provided API. + */ + +/** + * ScreensaverSkeletonClass: + * @parent_class: The parent class. + * + * Class structure for #ScreensaverSkeleton. + */ + +struct _ScreensaverSkeletonPrivate +{ + GValue *properties; + GList *changed_properties; + GSource *changed_properties_idle_source; + GMainContext *context; + GMutex lock; +}; + +static void +_screensaver_skeleton_handle_method_call ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name, + const gchar *method_name, + GVariant *parameters, + GDBusMethodInvocation *invocation, + gpointer user_data) +{ + ScreensaverSkeleton *skeleton = SCREENSAVER_SKELETON (user_data); + _ExtendedGDBusMethodInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + guint num_extra; + gsize n; + guint signal_id; + GValue return_value = G_VALUE_INIT; + info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); + g_assert (info != NULL); + num_params = g_variant_n_children (parameters); + num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); + n = 0; + g_value_init (¶mv[n], TYPE_SCREENSAVER); + g_value_set_object (¶mv[n++], skeleton); + g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); + g_value_set_object (¶mv[n++], invocation); + if (info->pass_fdlist) + { +#ifdef G_OS_UNIX + g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); + g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); +#else + g_assert_not_reached (); +#endif + } + g_variant_iter_init (&iter, parameters); + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_SCREENSAVER); + g_value_init (&return_value, G_TYPE_BOOLEAN); + g_signal_emitv (paramv, signal_id, 0, &return_value); + if (!g_value_get_boolean (&return_value)) + g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); + g_value_unset (&return_value); + for (n = 0; n < num_params + num_extra; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static GVariant * +_screensaver_skeleton_handle_get_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GError **error, + gpointer user_data) +{ + ScreensaverSkeleton *skeleton = SCREENSAVER_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + GVariant *ret; + ret = NULL; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_screensaver_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + g_value_init (&value, pspec->value_type); + g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); + ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); + g_value_unset (&value); + } + return ret; +} + +static gboolean +_screensaver_skeleton_handle_set_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GVariant *variant, + GError **error, + gpointer user_data) +{ + ScreensaverSkeleton *skeleton = SCREENSAVER_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + gboolean ret; + ret = FALSE; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_screensaver_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + if (info->use_gvariant) + g_value_set_variant (&value, variant); + else + g_dbus_gvariant_to_gvalue (variant, &value); + g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); + g_value_unset (&value); + ret = TRUE; + } + return ret; +} + +static const GDBusInterfaceVTable _screensaver_skeleton_vtable = +{ + _screensaver_skeleton_handle_method_call, + _screensaver_skeleton_handle_get_property, + _screensaver_skeleton_handle_set_property, + {NULL} +}; + +static GDBusInterfaceInfo * +screensaver_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return screensaver_interface_info (); +} + +static GDBusInterfaceVTable * +screensaver_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return (GDBusInterfaceVTable *) &_screensaver_skeleton_vtable; +} + +static GVariant * +screensaver_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) +{ + ScreensaverSkeleton *skeleton = SCREENSAVER_SKELETON (_skeleton); + + GVariantBuilder builder; + guint n; + g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); + if (_screensaver_interface_info.parent_struct.properties == NULL) + goto out; + for (n = 0; _screensaver_interface_info.parent_struct.properties[n] != NULL; n++) + { + GDBusPropertyInfo *info = _screensaver_interface_info.parent_struct.properties[n]; + if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) + { + GVariant *value; + value = _screensaver_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "cn.kylinos.screensaver", info->name, NULL, skeleton); + if (value != NULL) + { + g_variant_take_ref (value); + g_variant_builder_add (&builder, "{sv}", info->name, value); + g_variant_unref (value); + } + } + } +out: + return g_variant_builder_end (&builder); +} + +static void +screensaver_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) +{ +} + +static void screensaver_skeleton_iface_init (ScreensaverIface *iface); +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (ScreensaverSkeleton, screensaver_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_ADD_PRIVATE (ScreensaverSkeleton) + G_IMPLEMENT_INTERFACE (TYPE_SCREENSAVER, screensaver_skeleton_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (ScreensaverSkeleton, screensaver_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_IMPLEMENT_INTERFACE (TYPE_SCREENSAVER, screensaver_skeleton_iface_init)) + +#endif +static void +screensaver_skeleton_finalize (GObject *object) +{ + ScreensaverSkeleton *skeleton = SCREENSAVER_SKELETON (object); + g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); + if (skeleton->priv->changed_properties_idle_source != NULL) + g_source_destroy (skeleton->priv->changed_properties_idle_source); + g_main_context_unref (skeleton->priv->context); + g_mutex_clear (&skeleton->priv->lock); + G_OBJECT_CLASS (screensaver_skeleton_parent_class)->finalize (object); +} + +static void +screensaver_skeleton_init (ScreensaverSkeleton *skeleton) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + skeleton->priv = screensaver_skeleton_get_instance_private (skeleton); +#else + skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_SCREENSAVER_SKELETON, ScreensaverSkeletonPrivate); +#endif + + g_mutex_init (&skeleton->priv->lock); + skeleton->priv->context = g_main_context_ref_thread_default (); +} + +static void +screensaver_skeleton_class_init (ScreensaverSkeletonClass *klass) +{ + GObjectClass *gobject_class; + GDBusInterfaceSkeletonClass *skeleton_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = screensaver_skeleton_finalize; + + skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); + skeleton_class->get_info = screensaver_skeleton_dbus_interface_get_info; + skeleton_class->get_properties = screensaver_skeleton_dbus_interface_get_properties; + skeleton_class->flush = screensaver_skeleton_dbus_interface_flush; + skeleton_class->get_vtable = screensaver_skeleton_dbus_interface_get_vtable; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (ScreensaverSkeletonPrivate)); +#endif +} + +static void +screensaver_skeleton_iface_init (ScreensaverIface *iface) +{ +} + +/** + * screensaver_skeleton_new: + * + * Creates a skeleton object for the D-Bus interface cn.kylinos.screensaver. + * + * Returns: (transfer full) (type ScreensaverSkeleton): The skeleton object. + */ +Screensaver * +screensaver_skeleton_new (void) +{ + return SCREENSAVER (g_object_new (TYPE_SCREENSAVER_SKELETON, NULL)); +} + diff --git a/src/hardware/power/screensaver-generated.h b/src/hardware/power/screensaver-generated.h new file mode 100644 index 0000000..d369ce8 --- /dev/null +++ b/src/hardware/power/screensaver-generated.h @@ -0,0 +1,190 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +G_BEGIN_DECLS + + +/* ------------------------------------------------------------------------ */ +/* Declarations for cn.kylinos.screensaver */ + +#define TYPE_SCREENSAVER (screensaver_get_type ()) +#define SCREENSAVER(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_SCREENSAVER, Screensaver)) +#define IS_SCREENSAVER(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_SCREENSAVER)) +#define SCREENSAVER_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), TYPE_SCREENSAVER, ScreensaverIface)) + +struct _Screensaver; +typedef struct _Screensaver Screensaver; +typedef struct _ScreensaverIface ScreensaverIface; + +struct _ScreensaverIface +{ + GTypeInterface parent_iface; + + gboolean (*handle_transfer_bool_value) ( + Screensaver *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + +}; + +GType screensaver_get_type (void) G_GNUC_CONST; + +GDBusInterfaceInfo *screensaver_interface_info (void); +guint screensaver_override_properties (GObjectClass *klass, guint property_id_begin); + + +/* D-Bus method call completion functions: */ +void screensaver_complete_transfer_bool_value ( + Screensaver *object, + GDBusMethodInvocation *invocation); + + + +/* D-Bus method calls: */ +void screensaver_call_transfer_bool_value ( + Screensaver *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean screensaver_call_transfer_bool_value_finish ( + Screensaver *proxy, + GAsyncResult *res, + GError **error); + +gboolean screensaver_call_transfer_bool_value_sync ( + Screensaver *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + + + +/* ---- */ + +#define TYPE_SCREENSAVER_PROXY (screensaver_proxy_get_type ()) +#define SCREENSAVER_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_SCREENSAVER_PROXY, ScreensaverProxy)) +#define SCREENSAVER_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_SCREENSAVER_PROXY, ScreensaverProxyClass)) +#define SCREENSAVER_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_SCREENSAVER_PROXY, ScreensaverProxyClass)) +#define IS_SCREENSAVER_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_SCREENSAVER_PROXY)) +#define IS_SCREENSAVER_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_SCREENSAVER_PROXY)) + +typedef struct _ScreensaverProxy ScreensaverProxy; +typedef struct _ScreensaverProxyClass ScreensaverProxyClass; +typedef struct _ScreensaverProxyPrivate ScreensaverProxyPrivate; + +struct _ScreensaverProxy +{ + /*< private >*/ + GDBusProxy parent_instance; + ScreensaverProxyPrivate *priv; +}; + +struct _ScreensaverProxyClass +{ + GDBusProxyClass parent_class; +}; + +GType screensaver_proxy_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (ScreensaverProxy, g_object_unref) +#endif + +void screensaver_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Screensaver *screensaver_proxy_new_finish ( + GAsyncResult *res, + GError **error); +Screensaver *screensaver_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + +void screensaver_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Screensaver *screensaver_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error); +Screensaver *screensaver_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + + +/* ---- */ + +#define TYPE_SCREENSAVER_SKELETON (screensaver_skeleton_get_type ()) +#define SCREENSAVER_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_SCREENSAVER_SKELETON, ScreensaverSkeleton)) +#define SCREENSAVER_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_SCREENSAVER_SKELETON, ScreensaverSkeletonClass)) +#define SCREENSAVER_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_SCREENSAVER_SKELETON, ScreensaverSkeletonClass)) +#define IS_SCREENSAVER_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_SCREENSAVER_SKELETON)) +#define IS_SCREENSAVER_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_SCREENSAVER_SKELETON)) + +typedef struct _ScreensaverSkeleton ScreensaverSkeleton; +typedef struct _ScreensaverSkeletonClass ScreensaverSkeletonClass; +typedef struct _ScreensaverSkeletonPrivate ScreensaverSkeletonPrivate; + +struct _ScreensaverSkeleton +{ + /*< private >*/ + GDBusInterfaceSkeleton parent_instance; + ScreensaverSkeletonPrivate *priv; +}; + +struct _ScreensaverSkeletonClass +{ + GDBusInterfaceSkeletonClass parent_class; +}; + +GType screensaver_skeleton_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (ScreensaverSkeleton, g_object_unref) +#endif + +Screensaver *screensaver_skeleton_new (void); + + +G_END_DECLS + +#endif /* __SCREENSAVER_GENERATED_H__ */ diff --git a/src/hardware/power/session-dbus.h b/src/hardware/power/session-dbus.h new file mode 100644 index 0000000..b1b07bf --- /dev/null +++ b/src/hardware/power/session-dbus.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 /* Bus define */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define SESSION_BUS G_BUS_TYPE_SESSION +#define SESSION_BUS_NAME "cn.kylinos.session" +#define SESSION_OBJECT_PATH "/cn/kylinos/session" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/hardware/power/session-generated.c b/src/hardware/power/session-generated.c new file mode 100644 index 0000000..d2dccb1 --- /dev/null +++ b/src/hardware/power/session-generated.c @@ -0,0 +1,1050 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#ifdef G_OS_UNIX +# include +#endif + +typedef struct +{ + GDBusArgInfo parent_struct; + gboolean use_gvariant; +} _ExtendedGDBusArgInfo; + +typedef struct +{ + GDBusMethodInfo parent_struct; + const gchar *signal_name; + gboolean pass_fdlist; +} _ExtendedGDBusMethodInfo; + +typedef struct +{ + GDBusSignalInfo parent_struct; + const gchar *signal_name; +} _ExtendedGDBusSignalInfo; + +typedef struct +{ + GDBusPropertyInfo parent_struct; + const gchar *hyphen_name; + guint use_gvariant : 1; + guint emits_changed_signal : 1; +} _ExtendedGDBusPropertyInfo; + +typedef struct +{ + GDBusInterfaceInfo parent_struct; + const gchar *hyphen_name; +} _ExtendedGDBusInterfaceInfo; + +typedef struct +{ + const _ExtendedGDBusPropertyInfo *info; + guint prop_id; + GValue orig_value; /* the value before the change */ +} ChangedProperty; + +static void +_changed_property_free (ChangedProperty *data) +{ + g_value_unset (&data->orig_value); + g_free (data); +} + +static gboolean +_g_strv_equal0 (gchar **a, gchar **b) +{ + gboolean ret = FALSE; + guint n; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + if (g_strv_length (a) != g_strv_length (b)) + goto out; + for (n = 0; a[n] != NULL; n++) + if (g_strcmp0 (a[n], b[n]) != 0) + goto out; + ret = TRUE; +out: + return ret; +} + +static gboolean +_g_variant_equal0 (GVariant *a, GVariant *b) +{ + gboolean ret = FALSE; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + ret = g_variant_equal (a, b); +out: + return ret; +} + +G_GNUC_UNUSED static gboolean +_g_value_equal (const GValue *a, const GValue *b) +{ + gboolean ret = FALSE; + g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); + switch (G_VALUE_TYPE (a)) + { + case G_TYPE_BOOLEAN: + ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); + break; + case G_TYPE_UCHAR: + ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); + break; + case G_TYPE_INT: + ret = (g_value_get_int (a) == g_value_get_int (b)); + break; + case G_TYPE_UINT: + ret = (g_value_get_uint (a) == g_value_get_uint (b)); + break; + case G_TYPE_INT64: + ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); + break; + case G_TYPE_UINT64: + ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); + break; + case G_TYPE_DOUBLE: + { + /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ + gdouble da = g_value_get_double (a); + gdouble db = g_value_get_double (b); + ret = memcmp (&da, &db, sizeof (gdouble)) == 0; + } + break; + case G_TYPE_STRING: + ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); + break; + case G_TYPE_VARIANT: + ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); + break; + default: + if (G_VALUE_TYPE (a) == G_TYPE_STRV) + ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); + else + g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); + break; + } + return ret; +} + +/* ------------------------------------------------------------------------ + * Code for interface cn.kylinos.session + * ------------------------------------------------------------------------ + */ + +/** + * SECTION:Session + * @title: Session + * @short_description: Generated C code for the cn.kylinos.session D-Bus interface + * + * This section contains code for working with the cn.kylinos.session D-Bus interface in C. + */ + +/* ---- Introspection data for cn.kylinos.session ---- */ + +static const _ExtendedGDBusArgInfo _session_method_info_transfer_int_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(si)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _session_method_info_transfer_int_value_IN_ARG_pointers[] = +{ + &_session_method_info_transfer_int_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _session_method_info_transfer_int_value = +{ + { + -1, + (gchar *) "TransferIntValue", + (GDBusArgInfo **) &_session_method_info_transfer_int_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-int-value", + FALSE +}; + +static const GDBusMethodInfo * const _session_method_info_pointers[] = +{ + &_session_method_info_transfer_int_value.parent_struct, + NULL +}; + +static const _ExtendedGDBusInterfaceInfo _session_interface_info = +{ + { + -1, + (gchar *) "cn.kylinos.session", + (GDBusMethodInfo **) &_session_method_info_pointers, + NULL, + NULL, + NULL + }, + "session", +}; + + +/** + * session_interface_info: + * + * Gets a machine-readable description of the cn.kylinos.session D-Bus interface. + * + * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. + */ +GDBusInterfaceInfo * +session_interface_info (void) +{ + return (GDBusInterfaceInfo *) &_session_interface_info.parent_struct; +} + +/** + * session_override_properties: + * @klass: The class structure for a #GObject derived class. + * @property_id_begin: The property id to assign to the first overridden property. + * + * Overrides all #GObject properties in the #Session interface for a concrete class. + * The properties are overridden in the order they are defined. + * + * Returns: The last property id. + */ +guint +session_override_properties (GObjectClass *klass, guint property_id_begin) +{ + return property_id_begin - 1; +} + + + +/** + * Session: + * + * Abstract interface type for the D-Bus interface cn.kylinos.session. + */ + +/** + * SessionIface: + * @parent_iface: The parent interface. + * @handle_transfer_int_value: Handler for the #Session::handle-transfer-int-value signal. + * + * Virtual table for the D-Bus interface cn.kylinos.session. + */ + +typedef SessionIface SessionInterface; +G_DEFINE_INTERFACE (Session, session, G_TYPE_OBJECT) + +static void +session_default_init (SessionIface *iface) +{ + /* GObject signals for incoming D-Bus method calls: */ + /** + * Session::handle-transfer-int-value: + * @object: A #Session. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferIntValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call session_complete_transfer_int_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-int-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (SessionIface, handle_transfer_int_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + +} + +/** + * session_call_transfer_int_value: + * @proxy: A #SessionProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferIntValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call session_call_transfer_int_value_finish() to get the result of the operation. + * + * See session_call_transfer_int_value_sync() for the synchronous, blocking version of this method. + */ +void +session_call_transfer_int_value ( + Session *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * session_call_transfer_int_value_finish: + * @proxy: A #SessionProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to session_call_transfer_int_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with session_call_transfer_int_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +session_call_transfer_int_value_finish ( + Session *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * session_call_transfer_int_value_sync: + * @proxy: A #SessionProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferIntValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See session_call_transfer_int_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +session_call_transfer_int_value_sync ( + Session *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * session_complete_transfer_int_value: + * @object: A #Session. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferIntValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +session_complete_transfer_int_value ( + Session *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/* ------------------------------------------------------------------------ */ + +/** + * SessionProxy: + * + * The #SessionProxy structure contains only private data and should only be accessed using the provided API. + */ + +/** + * SessionProxyClass: + * @parent_class: The parent class. + * + * Class structure for #SessionProxy. + */ + +struct _SessionProxyPrivate +{ + GData *qdata; +}; + +static void session_proxy_iface_init (SessionIface *iface); + +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (SessionProxy, session_proxy, G_TYPE_DBUS_PROXY, + G_ADD_PRIVATE (SessionProxy) + G_IMPLEMENT_INTERFACE (TYPE_SESSION, session_proxy_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (SessionProxy, session_proxy, G_TYPE_DBUS_PROXY, + G_IMPLEMENT_INTERFACE (TYPE_SESSION, session_proxy_iface_init)) + +#endif +static void +session_proxy_finalize (GObject *object) +{ + SessionProxy *proxy = SESSION_PROXY (object); + g_datalist_clear (&proxy->priv->qdata); + G_OBJECT_CLASS (session_proxy_parent_class)->finalize (object); +} + +static void +session_proxy_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +session_proxy_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +session_proxy_g_signal (GDBusProxy *proxy, + const gchar *sender_name G_GNUC_UNUSED, + const gchar *signal_name, + GVariant *parameters) +{ + _ExtendedGDBusSignalInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + gsize n; + guint signal_id; + info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_session_interface_info.parent_struct, signal_name); + if (info == NULL) + return; + num_params = g_variant_n_children (parameters); + paramv = g_new0 (GValue, num_params + 1); + g_value_init (¶mv[0], TYPE_SESSION); + g_value_set_object (¶mv[0], proxy); + g_variant_iter_init (&iter, parameters); + n = 1; + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_SESSION); + g_signal_emitv (paramv, signal_id, 0, NULL); + for (n = 0; n < num_params + 1; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static void +session_proxy_g_properties_changed (GDBusProxy *_proxy, + GVariant *changed_properties, + const gchar *const *invalidated_properties) +{ + SessionProxy *proxy = SESSION_PROXY (_proxy); + guint n; + const gchar *key; + GVariantIter *iter; + _ExtendedGDBusPropertyInfo *info; + g_variant_get (changed_properties, "a{sv}", &iter); + while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_session_interface_info.parent_struct, key); + g_datalist_remove_data (&proxy->priv->qdata, key); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } + g_variant_iter_free (iter); + for (n = 0; invalidated_properties[n] != NULL; n++) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_session_interface_info.parent_struct, invalidated_properties[n]); + g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } +} + +static void +session_proxy_init (SessionProxy *proxy) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + proxy->priv = session_proxy_get_instance_private (proxy); +#else + proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, TYPE_SESSION_PROXY, SessionProxyPrivate); +#endif + + g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), session_interface_info ()); +} + +static void +session_proxy_class_init (SessionProxyClass *klass) +{ + GObjectClass *gobject_class; + GDBusProxyClass *proxy_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = session_proxy_finalize; + gobject_class->get_property = session_proxy_get_property; + gobject_class->set_property = session_proxy_set_property; + + proxy_class = G_DBUS_PROXY_CLASS (klass); + proxy_class->g_signal = session_proxy_g_signal; + proxy_class->g_properties_changed = session_proxy_g_properties_changed; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (SessionProxyPrivate)); +#endif +} + +static void +session_proxy_iface_init (SessionIface *iface) +{ +} + +/** + * session_proxy_new: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Asynchronously creates a proxy for the D-Bus interface cn.kylinos.session. See g_dbus_proxy_new() for more details. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call session_proxy_new_finish() to get the result of the operation. + * + * See session_proxy_new_sync() for the synchronous, blocking version of this constructor. + */ +void +session_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_SESSION_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.session", NULL); +} + +/** + * session_proxy_new_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to session_proxy_new(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with session_proxy_new(). + * + * Returns: (transfer full) (type SessionProxy): The constructed proxy object or %NULL if @error is set. + */ +Session * +session_proxy_new_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return SESSION (ret); + else + return NULL; +} + +/** + * session_proxy_new_sync: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Synchronously creates a proxy for the D-Bus interface cn.kylinos.session. See g_dbus_proxy_new_sync() for more details. + * + * The calling thread is blocked until a reply is received. + * + * See session_proxy_new() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type SessionProxy): The constructed proxy object or %NULL if @error is set. + */ +Session * +session_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_SESSION_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.session", NULL); + if (ret != NULL) + return SESSION (ret); + else + return NULL; +} + + +/** + * session_proxy_new_for_bus: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Like session_proxy_new() but takes a #GBusType instead of a #GDBusConnection. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call session_proxy_new_for_bus_finish() to get the result of the operation. + * + * See session_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. + */ +void +session_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_SESSION_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.session", NULL); +} + +/** + * session_proxy_new_for_bus_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to session_proxy_new_for_bus(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with session_proxy_new_for_bus(). + * + * Returns: (transfer full) (type SessionProxy): The constructed proxy object or %NULL if @error is set. + */ +Session * +session_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return SESSION (ret); + else + return NULL; +} + +/** + * session_proxy_new_for_bus_sync: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Like session_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. + * + * The calling thread is blocked until a reply is received. + * + * See session_proxy_new_for_bus() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type SessionProxy): The constructed proxy object or %NULL if @error is set. + */ +Session * +session_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_SESSION_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.session", NULL); + if (ret != NULL) + return SESSION (ret); + else + return NULL; +} + + +/* ------------------------------------------------------------------------ */ + +/** + * SessionSkeleton: + * + * The #SessionSkeleton structure contains only private data and should only be accessed using the provided API. + */ + +/** + * SessionSkeletonClass: + * @parent_class: The parent class. + * + * Class structure for #SessionSkeleton. + */ + +struct _SessionSkeletonPrivate +{ + GValue *properties; + GList *changed_properties; + GSource *changed_properties_idle_source; + GMainContext *context; + GMutex lock; +}; + +static void +_session_skeleton_handle_method_call ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name, + const gchar *method_name, + GVariant *parameters, + GDBusMethodInvocation *invocation, + gpointer user_data) +{ + SessionSkeleton *skeleton = SESSION_SKELETON (user_data); + _ExtendedGDBusMethodInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + guint num_extra; + gsize n; + guint signal_id; + GValue return_value = G_VALUE_INIT; + info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); + g_assert (info != NULL); + num_params = g_variant_n_children (parameters); + num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); + n = 0; + g_value_init (¶mv[n], TYPE_SESSION); + g_value_set_object (¶mv[n++], skeleton); + g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); + g_value_set_object (¶mv[n++], invocation); + if (info->pass_fdlist) + { +#ifdef G_OS_UNIX + g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); + g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); +#else + g_assert_not_reached (); +#endif + } + g_variant_iter_init (&iter, parameters); + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_SESSION); + g_value_init (&return_value, G_TYPE_BOOLEAN); + g_signal_emitv (paramv, signal_id, 0, &return_value); + if (!g_value_get_boolean (&return_value)) + g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); + g_value_unset (&return_value); + for (n = 0; n < num_params + num_extra; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static GVariant * +_session_skeleton_handle_get_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GError **error, + gpointer user_data) +{ + SessionSkeleton *skeleton = SESSION_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + GVariant *ret; + ret = NULL; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_session_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + g_value_init (&value, pspec->value_type); + g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); + ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); + g_value_unset (&value); + } + return ret; +} + +static gboolean +_session_skeleton_handle_set_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GVariant *variant, + GError **error, + gpointer user_data) +{ + SessionSkeleton *skeleton = SESSION_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + gboolean ret; + ret = FALSE; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_session_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + if (info->use_gvariant) + g_value_set_variant (&value, variant); + else + g_dbus_gvariant_to_gvalue (variant, &value); + g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); + g_value_unset (&value); + ret = TRUE; + } + return ret; +} + +static const GDBusInterfaceVTable _session_skeleton_vtable = +{ + _session_skeleton_handle_method_call, + _session_skeleton_handle_get_property, + _session_skeleton_handle_set_property, + {NULL} +}; + +static GDBusInterfaceInfo * +session_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return session_interface_info (); +} + +static GDBusInterfaceVTable * +session_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return (GDBusInterfaceVTable *) &_session_skeleton_vtable; +} + +static GVariant * +session_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) +{ + SessionSkeleton *skeleton = SESSION_SKELETON (_skeleton); + + GVariantBuilder builder; + guint n; + g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); + if (_session_interface_info.parent_struct.properties == NULL) + goto out; + for (n = 0; _session_interface_info.parent_struct.properties[n] != NULL; n++) + { + GDBusPropertyInfo *info = _session_interface_info.parent_struct.properties[n]; + if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) + { + GVariant *value; + value = _session_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "cn.kylinos.session", info->name, NULL, skeleton); + if (value != NULL) + { + g_variant_take_ref (value); + g_variant_builder_add (&builder, "{sv}", info->name, value); + g_variant_unref (value); + } + } + } +out: + return g_variant_builder_end (&builder); +} + +static void +session_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) +{ +} + +static void session_skeleton_iface_init (SessionIface *iface); +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (SessionSkeleton, session_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_ADD_PRIVATE (SessionSkeleton) + G_IMPLEMENT_INTERFACE (TYPE_SESSION, session_skeleton_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (SessionSkeleton, session_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_IMPLEMENT_INTERFACE (TYPE_SESSION, session_skeleton_iface_init)) + +#endif +static void +session_skeleton_finalize (GObject *object) +{ + SessionSkeleton *skeleton = SESSION_SKELETON (object); + g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); + if (skeleton->priv->changed_properties_idle_source != NULL) + g_source_destroy (skeleton->priv->changed_properties_idle_source); + g_main_context_unref (skeleton->priv->context); + g_mutex_clear (&skeleton->priv->lock); + G_OBJECT_CLASS (session_skeleton_parent_class)->finalize (object); +} + +static void +session_skeleton_init (SessionSkeleton *skeleton) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + skeleton->priv = session_skeleton_get_instance_private (skeleton); +#else + skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_SESSION_SKELETON, SessionSkeletonPrivate); +#endif + + g_mutex_init (&skeleton->priv->lock); + skeleton->priv->context = g_main_context_ref_thread_default (); +} + +static void +session_skeleton_class_init (SessionSkeletonClass *klass) +{ + GObjectClass *gobject_class; + GDBusInterfaceSkeletonClass *skeleton_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = session_skeleton_finalize; + + skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); + skeleton_class->get_info = session_skeleton_dbus_interface_get_info; + skeleton_class->get_properties = session_skeleton_dbus_interface_get_properties; + skeleton_class->flush = session_skeleton_dbus_interface_flush; + skeleton_class->get_vtable = session_skeleton_dbus_interface_get_vtable; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (SessionSkeletonPrivate)); +#endif +} + +static void +session_skeleton_iface_init (SessionIface *iface) +{ +} + +/** + * session_skeleton_new: + * + * Creates a skeleton object for the D-Bus interface cn.kylinos.session. + * + * Returns: (transfer full) (type SessionSkeleton): The skeleton object. + */ +Session * +session_skeleton_new (void) +{ + return SESSION (g_object_new (TYPE_SESSION_SKELETON, NULL)); +} + diff --git a/src/hardware/power/session-generated.h b/src/hardware/power/session-generated.h new file mode 100644 index 0000000..9ae74c4 --- /dev/null +++ b/src/hardware/power/session-generated.h @@ -0,0 +1,190 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +G_BEGIN_DECLS + + +/* ------------------------------------------------------------------------ */ +/* Declarations for cn.kylinos.session */ + +#define TYPE_SESSION (session_get_type ()) +#define SESSION(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_SESSION, Session)) +#define IS_SESSION(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_SESSION)) +#define SESSION_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), TYPE_SESSION, SessionIface)) + +struct _Session; +typedef struct _Session Session; +typedef struct _SessionIface SessionIface; + +struct _SessionIface +{ + GTypeInterface parent_iface; + + gboolean (*handle_transfer_int_value) ( + Session *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + +}; + +GType session_get_type (void) G_GNUC_CONST; + +GDBusInterfaceInfo *session_interface_info (void); +guint session_override_properties (GObjectClass *klass, guint property_id_begin); + + +/* D-Bus method call completion functions: */ +void session_complete_transfer_int_value ( + Session *object, + GDBusMethodInvocation *invocation); + + + +/* D-Bus method calls: */ +void session_call_transfer_int_value ( + Session *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean session_call_transfer_int_value_finish ( + Session *proxy, + GAsyncResult *res, + GError **error); + +gboolean session_call_transfer_int_value_sync ( + Session *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + + + +/* ---- */ + +#define TYPE_SESSION_PROXY (session_proxy_get_type ()) +#define SESSION_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_SESSION_PROXY, SessionProxy)) +#define SESSION_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_SESSION_PROXY, SessionProxyClass)) +#define SESSION_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_SESSION_PROXY, SessionProxyClass)) +#define IS_SESSION_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_SESSION_PROXY)) +#define IS_SESSION_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_SESSION_PROXY)) + +typedef struct _SessionProxy SessionProxy; +typedef struct _SessionProxyClass SessionProxyClass; +typedef struct _SessionProxyPrivate SessionProxyPrivate; + +struct _SessionProxy +{ + /*< private >*/ + GDBusProxy parent_instance; + SessionProxyPrivate *priv; +}; + +struct _SessionProxyClass +{ + GDBusProxyClass parent_class; +}; + +GType session_proxy_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (SessionProxy, g_object_unref) +#endif + +void session_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Session *session_proxy_new_finish ( + GAsyncResult *res, + GError **error); +Session *session_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + +void session_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Session *session_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error); +Session *session_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + + +/* ---- */ + +#define TYPE_SESSION_SKELETON (session_skeleton_get_type ()) +#define SESSION_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_SESSION_SKELETON, SessionSkeleton)) +#define SESSION_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_SESSION_SKELETON, SessionSkeletonClass)) +#define SESSION_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_SESSION_SKELETON, SessionSkeletonClass)) +#define IS_SESSION_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_SESSION_SKELETON)) +#define IS_SESSION_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_SESSION_SKELETON)) + +typedef struct _SessionSkeleton SessionSkeleton; +typedef struct _SessionSkeletonClass SessionSkeletonClass; +typedef struct _SessionSkeletonPrivate SessionSkeletonPrivate; + +struct _SessionSkeleton +{ + /*< private >*/ + GDBusInterfaceSkeleton parent_instance; + SessionSkeletonPrivate *priv; +}; + +struct _SessionSkeletonClass +{ + GDBusInterfaceSkeletonClass parent_class; +}; + +GType session_skeleton_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (SessionSkeleton, g_object_unref) +#endif + +Session *session_skeleton_new (void); + + +G_END_DECLS + +#endif /* __SESSION_GENERATED_H__ */ diff --git a/src/hardware/touchpad/Makefile.am b/src/hardware/touchpad/Makefile.am new file mode 100644 index 0000000..81ef336 --- /dev/null +++ b/src/hardware/touchpad/Makefile.am @@ -0,0 +1,55 @@ +COMM_PRINT= -L$(top_srcdir)/src/common -lukui-print +COMM_GSETTINGS= -L$(top_srcdir)/src/common -lukui-gsettings + +#generate the .c and .h file which used by client and server side by XML file +#$(top_srcdir) represents the top-level directory of the project +DESC_XML = $(top_srcdir)/data/cn.kylinos.touchpad.xml +GENERATED_CH = touchpad-generated + +touchpad-generated.h touchpad-generated.c: $(DESC_XML) + gdbus-codegen --interface-prefix cn.kylinos. --generate-c-code $(GENERATED_CH) $(DESC_XML) + +#Generata binary file +lib_LTLIBRARIES = libukui-touchpadclient.la + +#gcc -wall: displays all the errors and warning information when compiling +#gcc -g: add the debugging code when compiling +COMM_CFS = -Wall -g + +#Add the dependent source file for libtouchpadclient.la +#touchpad-generated.c must be front of kylin-touchpad-interface.c +libukui_touchpadclient_la_SOURCES = touchpad-generated.c kylin-touchpad-interface.c \ + $(NULL) + +#The header files that need to be installed +include_HEADERS= kylin-touchpad-interface.h \ + $(NULL) + +#Additional C compiler flags +libukui_touchpadclient_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_touchpadclient_la_LDFLAGS= $(COMM_PRINT) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Generata binary file +bin_PROGRAMS = ukui-touchpadserver + +#Add the dependent source file for touchpadserver +ukui_touchpadserver_SOURCES = \ + touchpad-generated.h touchpad-generated.c \ + kylin-touchpad-server.c \ + $(NULL) + +#Additional C compiler flags +ukui_touchpadserver_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +ukui_touchpadserver_LDFLAGS= $(COMM_PRINT) $(COMM_GSETTINGS) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) diff --git a/src/hardware/touchpad/kylin-touchpad-interface.c b/src/hardware/touchpad/kylin-touchpad-interface.c new file mode 100644 index 0000000..d4ce1cc --- /dev/null +++ b/src/hardware/touchpad/kylin-touchpad-interface.c @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#define TE "touchpad-enabled" +#define TTC "tap-to-click" +#define SM "scroll-method" +#define NS "natural-scroll" + +static GMainLoop *pLoop = NULL; +static GDBusConnection *pConnection = NULL; +static Touchpad *pProxy = NULL; + +void kylin_hardware_touchpad_touchpadenabled(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=TE; + arg=g_variant_new("(sb)", key, in_arg); + touchpad_call_transfer_bool_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_touchpad_touchpadenabled. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_hardware_touchpad_taptoclick(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=TTC; + arg=g_variant_new("(sb)", key, in_arg); + touchpad_call_transfer_bool_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_touchpad_taptoclick. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_hardware_touchpad_scrollmethod(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=SM; + arg=g_variant_new("(si)",key,in_arg); + touchpad_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_touchpad_scrollmethod. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; + +} + +void kylin_hardware_touchpad_naturalscroll(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=NS; + arg=g_variant_new("(sb)", key, in_arg); + touchpad_call_transfer_bool_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_hardware_touchpad_naturalscroll. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void *run(void* arg) +{ + /** start the main event loop which manages all available sources of events */ + g_main_loop_run(pLoop); + + return ((void*)0); +} + +int thread_create(void) + { + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if(0 != err){ + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; + } + +bool InitDBusTouchpad(void) + { + bool bRet = TRUE; + GError *pConnError = NULL; + GError *pProxyError = NULL; + + do{ + bRet = TRUE; + pLoop = g_main_loop_new(NULL, FALSE); /** create main loop, but do not start it.*/ + + /** First step: get a connection */ + pConnection = g_bus_get_sync(TOUCHPAD_BUS, NULL, &pConnError); + + if (NULL == pConnError){ + /** Second step: try to get a connection to the given bus.*/ + pProxy = touchpad_proxy_new_sync(pConnection, + G_DBUS_PROXY_FLAGS_NONE, + TOUCHPAD_BUS_NAME, + TOUCHPAD_OBJECT_PATH, + NULL, + &pProxyError); + if (0 == pProxy){ + print_error("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message); + g_error_free(pProxyError); + bRet = FALSE; + } + + + } + else{ + print_error("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message); + g_error_free(pConnError); + bRet = FALSE; + } + }while(FALSE == bRet); + + thread_create(); + + return bRet; + } + +bool DeInitDBusTouchpad(void) +{ + bool bRet = FALSE; + + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} diff --git a/src/hardware/touchpad/kylin-touchpad-interface.h b/src/hardware/touchpad/kylin-touchpad-interface.h new file mode 100644 index 0000000..1dcf080 --- /dev/null +++ b/src/hardware/touchpad/kylin-touchpad-interface.h @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +//Initialize the DBus Communication +bool InitDBusTouchpad(void); + +//Delete the DBus Communication +bool DeInitDBusTouchpad(void); + +/* + * Set this to TRUE to enable all touchpads. + * + */ +void kylin_hardware_touchpad_touchpadenabled(const bool in_arg); + +/* + * Enable mouse clicks with touchpad. + * + */ +void kylin_hardware_touchpad_taptoclick(const bool in_arg); + +/* + * Select the touchpad scroll method. + * Supported values are: + * @in_arg is equal to 0: disabled; + * @in_arg is equal to 1: edge scrolling; + * @in_arg is equal to 2: two-finger scrolling. + * + */ +void kylin_hardware_touchpad_scrollmethod(const int in_arg); + +/* + * Set this to true to enable natural (reverse) scrolling for touchpads. + * + */ +void kylin_hardware_touchpad_naturalscroll(const bool in_arg); + +#ifdef __cplusplus +} +#endif + +#endif + + + + + + + + + + + + + diff --git a/src/hardware/touchpad/kylin-touchpad-server.c b/src/hardware/touchpad/kylin-touchpad-server.c new file mode 100644 index 0000000..f25893c --- /dev/null +++ b/src/hardware/touchpad/kylin-touchpad-server.c @@ -0,0 +1,199 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include "touchpad-dbus.h" +#include "src/common/kylin-gsettings-set.h" +#include "src/common/kylin-print.h" +#include "touchpad-generated.h" +#include + +#define schemaID "org.mate.peripherals-touchpad" + +static GMainLoop *pLoop = NULL; +static Touchpad *pSkeleton = NULL; + +static gboolean kylin_set_bool(Touchpad* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gboolean value; + gint i; + g_variant_get(in_arg, "(sb)", &key, &value); + if(value==false)i=0; + else i=1; + + touchpad_complete_transfer_bool_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + gsettings_set_boolean(setting, key, value); + Dec_ref(setting); + + print_info("(%s, %d)\n", key, i); + + return TRUE; +} + +static gboolean kylin_set_int(Touchpad* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gint value; + g_variant_get(in_arg, "(si)", &key, &value); + + touchpad_complete_transfer_int_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + gsettings_set_int(setting, key, value); + Dec_ref(setting); + + print_info("(%s, %d)\n", key, value); + + return TRUE; +} + +static void bus_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + + GError *pError = NULL; + + /** Second step: Try to get a connection to the given bus. */ + pSkeleton = touchpad_skeleton_new(); + + /** Third step: Attach to dbus signals. */ + (void) g_signal_connect(pSkeleton, "handle-transfer-bool-value", G_CALLBACK(kylin_set_bool), NULL); + (void) g_signal_connect(pSkeleton, "handle-transfer-int-value", G_CALLBACK(kylin_set_int), NULL); + + /** Fourth step: Export interface skeleton. */ + (void)g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(pSkeleton), + connection, + TOUCHPAD_OBJECT_PATH, + &pError); + + if(pError != NULL){ + print_error("Error: Failed to export object. Reason: %s.\n", pError->message); + g_error_free(pError); + g_main_loop_quit(pLoop); + } +} + +static void name_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + print_info("name_acquired_cb call, Acquired bus name: %s.\n", TOUCHPAD_BUS_NAME); +} + +static void name_lost_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + if(connection == NULL) + { + print_error("name_lost_cb call, Error: Failed to connect to dbus.\n"); + } + else + { + print_error("name_lost_cb call, Error: Failed to obtain bus name: %s.\n", TOUCHPAD_BUS_NAME); + } + + g_main_loop_quit(pLoop); +} + +void* run(void* para) +{ + /** Start the Main Event Loop which manages all available sources of events */ + g_main_loop_run( pLoop ); + + return ((void*)0); +} + +int thread_create(void) +{ + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if (err != 0) + { + + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; +} + +bool InitDBusCommunicationServer(void) +{ + bool bRet = TRUE; + + g_print("InitDBusCommunicationServer: Server started.\n"); + + /** create main loop, but do not start it. */ + pLoop = g_main_loop_new(NULL, FALSE); + + /** first step: connect to dbus */ + (void)g_bus_own_name(TOUCHPAD_BUS, + TOUCHPAD_BUS_NAME, + G_BUS_NAME_OWNER_FLAGS_NONE, + &bus_acquired_cb, + &name_acquired_cb, + &name_lost_cb, + NULL, + NULL); + + thread_create(); + + return bRet; +} + +bool DeinitDBusCommunicationServer(void) +{ + bool bRet = FALSE; + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} + +int main(void) +{ + InitDBusCommunicationServer(); + + sleep(100); + + DeinitDBusCommunicationServer(); + return 0; +} diff --git a/src/hardware/touchpad/touchpad-dbus.h b/src/hardware/touchpad/touchpad-dbus.h new file mode 100644 index 0000000..3fd8bf3 --- /dev/null +++ b/src/hardware/touchpad/touchpad-dbus.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 /* Bus define */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define TOUCHPAD_BUS G_BUS_TYPE_SESSION +#define TOUCHPAD_BUS_NAME "cn.kylinos.touchpad" +#define TOUCHPAD_OBJECT_PATH "/cn/kylinos/touchpad" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/hardware/touchpad/touchpad-generated.c b/src/hardware/touchpad/touchpad-generated.c new file mode 100644 index 0000000..19de81b --- /dev/null +++ b/src/hardware/touchpad/touchpad-generated.c @@ -0,0 +1,1221 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#ifdef G_OS_UNIX +# include +#endif + +typedef struct +{ + GDBusArgInfo parent_struct; + gboolean use_gvariant; +} _ExtendedGDBusArgInfo; + +typedef struct +{ + GDBusMethodInfo parent_struct; + const gchar *signal_name; + gboolean pass_fdlist; +} _ExtendedGDBusMethodInfo; + +typedef struct +{ + GDBusSignalInfo parent_struct; + const gchar *signal_name; +} _ExtendedGDBusSignalInfo; + +typedef struct +{ + GDBusPropertyInfo parent_struct; + const gchar *hyphen_name; + guint use_gvariant : 1; + guint emits_changed_signal : 1; +} _ExtendedGDBusPropertyInfo; + +typedef struct +{ + GDBusInterfaceInfo parent_struct; + const gchar *hyphen_name; +} _ExtendedGDBusInterfaceInfo; + +typedef struct +{ + const _ExtendedGDBusPropertyInfo *info; + guint prop_id; + GValue orig_value; /* the value before the change */ +} ChangedProperty; + +static void +_changed_property_free (ChangedProperty *data) +{ + g_value_unset (&data->orig_value); + g_free (data); +} + +static gboolean +_g_strv_equal0 (gchar **a, gchar **b) +{ + gboolean ret = FALSE; + guint n; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + if (g_strv_length (a) != g_strv_length (b)) + goto out; + for (n = 0; a[n] != NULL; n++) + if (g_strcmp0 (a[n], b[n]) != 0) + goto out; + ret = TRUE; +out: + return ret; +} + +static gboolean +_g_variant_equal0 (GVariant *a, GVariant *b) +{ + gboolean ret = FALSE; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + ret = g_variant_equal (a, b); +out: + return ret; +} + +G_GNUC_UNUSED static gboolean +_g_value_equal (const GValue *a, const GValue *b) +{ + gboolean ret = FALSE; + g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); + switch (G_VALUE_TYPE (a)) + { + case G_TYPE_BOOLEAN: + ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); + break; + case G_TYPE_UCHAR: + ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); + break; + case G_TYPE_INT: + ret = (g_value_get_int (a) == g_value_get_int (b)); + break; + case G_TYPE_UINT: + ret = (g_value_get_uint (a) == g_value_get_uint (b)); + break; + case G_TYPE_INT64: + ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); + break; + case G_TYPE_UINT64: + ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); + break; + case G_TYPE_DOUBLE: + { + /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ + gdouble da = g_value_get_double (a); + gdouble db = g_value_get_double (b); + ret = memcmp (&da, &db, sizeof (gdouble)) == 0; + } + break; + case G_TYPE_STRING: + ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); + break; + case G_TYPE_VARIANT: + ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); + break; + default: + if (G_VALUE_TYPE (a) == G_TYPE_STRV) + ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); + else + g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); + break; + } + return ret; +} + +/* ------------------------------------------------------------------------ + * Code for interface cn.kylinos.touchpad + * ------------------------------------------------------------------------ + */ + +/** + * SECTION:Touchpad + * @title: Touchpad + * @short_description: Generated C code for the cn.kylinos.touchpad D-Bus interface + * + * This section contains code for working with the cn.kylinos.touchpad D-Bus interface in C. + */ + +/* ---- Introspection data for cn.kylinos.touchpad ---- */ + +static const _ExtendedGDBusArgInfo _touchpad_method_info_transfer_bool_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(sb)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _touchpad_method_info_transfer_bool_value_IN_ARG_pointers[] = +{ + &_touchpad_method_info_transfer_bool_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _touchpad_method_info_transfer_bool_value = +{ + { + -1, + (gchar *) "TransferBoolValue", + (GDBusArgInfo **) &_touchpad_method_info_transfer_bool_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-bool-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _touchpad_method_info_transfer_int_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(si)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _touchpad_method_info_transfer_int_value_IN_ARG_pointers[] = +{ + &_touchpad_method_info_transfer_int_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _touchpad_method_info_transfer_int_value = +{ + { + -1, + (gchar *) "TransferIntValue", + (GDBusArgInfo **) &_touchpad_method_info_transfer_int_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-int-value", + FALSE +}; + +static const GDBusMethodInfo * const _touchpad_method_info_pointers[] = +{ + &_touchpad_method_info_transfer_bool_value.parent_struct, + &_touchpad_method_info_transfer_int_value.parent_struct, + NULL +}; + +static const _ExtendedGDBusInterfaceInfo _touchpad_interface_info = +{ + { + -1, + (gchar *) "cn.kylinos.touchpad", + (GDBusMethodInfo **) &_touchpad_method_info_pointers, + NULL, + NULL, + NULL + }, + "touchpad", +}; + + +/** + * touchpad_interface_info: + * + * Gets a machine-readable description of the cn.kylinos.touchpad D-Bus interface. + * + * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. + */ +GDBusInterfaceInfo * +touchpad_interface_info (void) +{ + return (GDBusInterfaceInfo *) &_touchpad_interface_info.parent_struct; +} + +/** + * touchpad_override_properties: + * @klass: The class structure for a #GObject derived class. + * @property_id_begin: The property id to assign to the first overridden property. + * + * Overrides all #GObject properties in the #Touchpad interface for a concrete class. + * The properties are overridden in the order they are defined. + * + * Returns: The last property id. + */ +guint +touchpad_override_properties (GObjectClass *klass, guint property_id_begin) +{ + return property_id_begin - 1; +} + + + +/** + * Touchpad: + * + * Abstract interface type for the D-Bus interface cn.kylinos.touchpad. + */ + +/** + * TouchpadIface: + * @parent_iface: The parent interface. + * @handle_transfer_bool_value: Handler for the #Touchpad::handle-transfer-bool-value signal. + * @handle_transfer_int_value: Handler for the #Touchpad::handle-transfer-int-value signal. + * + * Virtual table for the D-Bus interface cn.kylinos.touchpad. + */ + +typedef TouchpadIface TouchpadInterface; +G_DEFINE_INTERFACE (Touchpad, touchpad, G_TYPE_OBJECT) + +static void +touchpad_default_init (TouchpadIface *iface) +{ + /* GObject signals for incoming D-Bus method calls: */ + /** + * Touchpad::handle-transfer-bool-value: + * @object: A #Touchpad. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferBoolValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call touchpad_complete_transfer_bool_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-bool-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (TouchpadIface, handle_transfer_bool_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Touchpad::handle-transfer-int-value: + * @object: A #Touchpad. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferIntValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call touchpad_complete_transfer_int_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-int-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (TouchpadIface, handle_transfer_int_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + +} + +/** + * touchpad_call_transfer_bool_value: + * @proxy: A #TouchpadProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferBoolValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call touchpad_call_transfer_bool_value_finish() to get the result of the operation. + * + * See touchpad_call_transfer_bool_value_sync() for the synchronous, blocking version of this method. + */ +void +touchpad_call_transfer_bool_value ( + Touchpad *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * touchpad_call_transfer_bool_value_finish: + * @proxy: A #TouchpadProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to touchpad_call_transfer_bool_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with touchpad_call_transfer_bool_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +touchpad_call_transfer_bool_value_finish ( + Touchpad *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * touchpad_call_transfer_bool_value_sync: + * @proxy: A #TouchpadProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferBoolValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See touchpad_call_transfer_bool_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +touchpad_call_transfer_bool_value_sync ( + Touchpad *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * touchpad_call_transfer_int_value: + * @proxy: A #TouchpadProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferIntValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call touchpad_call_transfer_int_value_finish() to get the result of the operation. + * + * See touchpad_call_transfer_int_value_sync() for the synchronous, blocking version of this method. + */ +void +touchpad_call_transfer_int_value ( + Touchpad *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * touchpad_call_transfer_int_value_finish: + * @proxy: A #TouchpadProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to touchpad_call_transfer_int_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with touchpad_call_transfer_int_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +touchpad_call_transfer_int_value_finish ( + Touchpad *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * touchpad_call_transfer_int_value_sync: + * @proxy: A #TouchpadProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferIntValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See touchpad_call_transfer_int_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +touchpad_call_transfer_int_value_sync ( + Touchpad *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * touchpad_complete_transfer_bool_value: + * @object: A #Touchpad. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferBoolValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +touchpad_complete_transfer_bool_value ( + Touchpad *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/** + * touchpad_complete_transfer_int_value: + * @object: A #Touchpad. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferIntValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +touchpad_complete_transfer_int_value ( + Touchpad *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/* ------------------------------------------------------------------------ */ + +/** + * TouchpadProxy: + * + * The #TouchpadProxy structure contains only private data and should only be accessed using the provided API. + */ + +/** + * TouchpadProxyClass: + * @parent_class: The parent class. + * + * Class structure for #TouchpadProxy. + */ + +struct _TouchpadProxyPrivate +{ + GData *qdata; +}; + +static void touchpad_proxy_iface_init (TouchpadIface *iface); + +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (TouchpadProxy, touchpad_proxy, G_TYPE_DBUS_PROXY, + G_ADD_PRIVATE (TouchpadProxy) + G_IMPLEMENT_INTERFACE (TYPE_TOUCHPAD, touchpad_proxy_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (TouchpadProxy, touchpad_proxy, G_TYPE_DBUS_PROXY, + G_IMPLEMENT_INTERFACE (TYPE_TOUCHPAD, touchpad_proxy_iface_init)) + +#endif +static void +touchpad_proxy_finalize (GObject *object) +{ + TouchpadProxy *proxy = TOUCHPAD_PROXY (object); + g_datalist_clear (&proxy->priv->qdata); + G_OBJECT_CLASS (touchpad_proxy_parent_class)->finalize (object); +} + +static void +touchpad_proxy_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +touchpad_proxy_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +touchpad_proxy_g_signal (GDBusProxy *proxy, + const gchar *sender_name G_GNUC_UNUSED, + const gchar *signal_name, + GVariant *parameters) +{ + _ExtendedGDBusSignalInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + gsize n; + guint signal_id; + info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_touchpad_interface_info.parent_struct, signal_name); + if (info == NULL) + return; + num_params = g_variant_n_children (parameters); + paramv = g_new0 (GValue, num_params + 1); + g_value_init (¶mv[0], TYPE_TOUCHPAD); + g_value_set_object (¶mv[0], proxy); + g_variant_iter_init (&iter, parameters); + n = 1; + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_TOUCHPAD); + g_signal_emitv (paramv, signal_id, 0, NULL); + for (n = 0; n < num_params + 1; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static void +touchpad_proxy_g_properties_changed (GDBusProxy *_proxy, + GVariant *changed_properties, + const gchar *const *invalidated_properties) +{ + TouchpadProxy *proxy = TOUCHPAD_PROXY (_proxy); + guint n; + const gchar *key; + GVariantIter *iter; + _ExtendedGDBusPropertyInfo *info; + g_variant_get (changed_properties, "a{sv}", &iter); + while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_touchpad_interface_info.parent_struct, key); + g_datalist_remove_data (&proxy->priv->qdata, key); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } + g_variant_iter_free (iter); + for (n = 0; invalidated_properties[n] != NULL; n++) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_touchpad_interface_info.parent_struct, invalidated_properties[n]); + g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } +} + +static void +touchpad_proxy_init (TouchpadProxy *proxy) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + proxy->priv = touchpad_proxy_get_instance_private (proxy); +#else + proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, TYPE_TOUCHPAD_PROXY, TouchpadProxyPrivate); +#endif + + g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), touchpad_interface_info ()); +} + +static void +touchpad_proxy_class_init (TouchpadProxyClass *klass) +{ + GObjectClass *gobject_class; + GDBusProxyClass *proxy_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = touchpad_proxy_finalize; + gobject_class->get_property = touchpad_proxy_get_property; + gobject_class->set_property = touchpad_proxy_set_property; + + proxy_class = G_DBUS_PROXY_CLASS (klass); + proxy_class->g_signal = touchpad_proxy_g_signal; + proxy_class->g_properties_changed = touchpad_proxy_g_properties_changed; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (TouchpadProxyPrivate)); +#endif +} + +static void +touchpad_proxy_iface_init (TouchpadIface *iface) +{ +} + +/** + * touchpad_proxy_new: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Asynchronously creates a proxy for the D-Bus interface cn.kylinos.touchpad. See g_dbus_proxy_new() for more details. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call touchpad_proxy_new_finish() to get the result of the operation. + * + * See touchpad_proxy_new_sync() for the synchronous, blocking version of this constructor. + */ +void +touchpad_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_TOUCHPAD_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.touchpad", NULL); +} + +/** + * touchpad_proxy_new_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to touchpad_proxy_new(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with touchpad_proxy_new(). + * + * Returns: (transfer full) (type TouchpadProxy): The constructed proxy object or %NULL if @error is set. + */ +Touchpad * +touchpad_proxy_new_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return TOUCHPAD (ret); + else + return NULL; +} + +/** + * touchpad_proxy_new_sync: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Synchronously creates a proxy for the D-Bus interface cn.kylinos.touchpad. See g_dbus_proxy_new_sync() for more details. + * + * The calling thread is blocked until a reply is received. + * + * See touchpad_proxy_new() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type TouchpadProxy): The constructed proxy object or %NULL if @error is set. + */ +Touchpad * +touchpad_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_TOUCHPAD_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.touchpad", NULL); + if (ret != NULL) + return TOUCHPAD (ret); + else + return NULL; +} + + +/** + * touchpad_proxy_new_for_bus: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Like touchpad_proxy_new() but takes a #GBusType instead of a #GDBusConnection. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call touchpad_proxy_new_for_bus_finish() to get the result of the operation. + * + * See touchpad_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. + */ +void +touchpad_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_TOUCHPAD_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.touchpad", NULL); +} + +/** + * touchpad_proxy_new_for_bus_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to touchpad_proxy_new_for_bus(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with touchpad_proxy_new_for_bus(). + * + * Returns: (transfer full) (type TouchpadProxy): The constructed proxy object or %NULL if @error is set. + */ +Touchpad * +touchpad_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return TOUCHPAD (ret); + else + return NULL; +} + +/** + * touchpad_proxy_new_for_bus_sync: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Like touchpad_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. + * + * The calling thread is blocked until a reply is received. + * + * See touchpad_proxy_new_for_bus() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type TouchpadProxy): The constructed proxy object or %NULL if @error is set. + */ +Touchpad * +touchpad_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_TOUCHPAD_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.touchpad", NULL); + if (ret != NULL) + return TOUCHPAD (ret); + else + return NULL; +} + + +/* ------------------------------------------------------------------------ */ + +/** + * TouchpadSkeleton: + * + * The #TouchpadSkeleton structure contains only private data and should only be accessed using the provided API. + */ + +/** + * TouchpadSkeletonClass: + * @parent_class: The parent class. + * + * Class structure for #TouchpadSkeleton. + */ + +struct _TouchpadSkeletonPrivate +{ + GValue *properties; + GList *changed_properties; + GSource *changed_properties_idle_source; + GMainContext *context; + GMutex lock; +}; + +static void +_touchpad_skeleton_handle_method_call ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name, + const gchar *method_name, + GVariant *parameters, + GDBusMethodInvocation *invocation, + gpointer user_data) +{ + TouchpadSkeleton *skeleton = TOUCHPAD_SKELETON (user_data); + _ExtendedGDBusMethodInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + guint num_extra; + gsize n; + guint signal_id; + GValue return_value = G_VALUE_INIT; + info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); + g_assert (info != NULL); + num_params = g_variant_n_children (parameters); + num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); + n = 0; + g_value_init (¶mv[n], TYPE_TOUCHPAD); + g_value_set_object (¶mv[n++], skeleton); + g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); + g_value_set_object (¶mv[n++], invocation); + if (info->pass_fdlist) + { +#ifdef G_OS_UNIX + g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); + g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); +#else + g_assert_not_reached (); +#endif + } + g_variant_iter_init (&iter, parameters); + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_TOUCHPAD); + g_value_init (&return_value, G_TYPE_BOOLEAN); + g_signal_emitv (paramv, signal_id, 0, &return_value); + if (!g_value_get_boolean (&return_value)) + g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); + g_value_unset (&return_value); + for (n = 0; n < num_params + num_extra; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static GVariant * +_touchpad_skeleton_handle_get_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GError **error, + gpointer user_data) +{ + TouchpadSkeleton *skeleton = TOUCHPAD_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + GVariant *ret; + ret = NULL; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_touchpad_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + g_value_init (&value, pspec->value_type); + g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); + ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); + g_value_unset (&value); + } + return ret; +} + +static gboolean +_touchpad_skeleton_handle_set_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GVariant *variant, + GError **error, + gpointer user_data) +{ + TouchpadSkeleton *skeleton = TOUCHPAD_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + gboolean ret; + ret = FALSE; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_touchpad_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + if (info->use_gvariant) + g_value_set_variant (&value, variant); + else + g_dbus_gvariant_to_gvalue (variant, &value); + g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); + g_value_unset (&value); + ret = TRUE; + } + return ret; +} + +static const GDBusInterfaceVTable _touchpad_skeleton_vtable = +{ + _touchpad_skeleton_handle_method_call, + _touchpad_skeleton_handle_get_property, + _touchpad_skeleton_handle_set_property, + {NULL} +}; + +static GDBusInterfaceInfo * +touchpad_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return touchpad_interface_info (); +} + +static GDBusInterfaceVTable * +touchpad_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return (GDBusInterfaceVTable *) &_touchpad_skeleton_vtable; +} + +static GVariant * +touchpad_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) +{ + TouchpadSkeleton *skeleton = TOUCHPAD_SKELETON (_skeleton); + + GVariantBuilder builder; + guint n; + g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); + if (_touchpad_interface_info.parent_struct.properties == NULL) + goto out; + for (n = 0; _touchpad_interface_info.parent_struct.properties[n] != NULL; n++) + { + GDBusPropertyInfo *info = _touchpad_interface_info.parent_struct.properties[n]; + if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) + { + GVariant *value; + value = _touchpad_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "cn.kylinos.touchpad", info->name, NULL, skeleton); + if (value != NULL) + { + g_variant_take_ref (value); + g_variant_builder_add (&builder, "{sv}", info->name, value); + g_variant_unref (value); + } + } + } +out: + return g_variant_builder_end (&builder); +} + +static void +touchpad_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) +{ +} + +static void touchpad_skeleton_iface_init (TouchpadIface *iface); +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (TouchpadSkeleton, touchpad_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_ADD_PRIVATE (TouchpadSkeleton) + G_IMPLEMENT_INTERFACE (TYPE_TOUCHPAD, touchpad_skeleton_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (TouchpadSkeleton, touchpad_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_IMPLEMENT_INTERFACE (TYPE_TOUCHPAD, touchpad_skeleton_iface_init)) + +#endif +static void +touchpad_skeleton_finalize (GObject *object) +{ + TouchpadSkeleton *skeleton = TOUCHPAD_SKELETON (object); + g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); + if (skeleton->priv->changed_properties_idle_source != NULL) + g_source_destroy (skeleton->priv->changed_properties_idle_source); + g_main_context_unref (skeleton->priv->context); + g_mutex_clear (&skeleton->priv->lock); + G_OBJECT_CLASS (touchpad_skeleton_parent_class)->finalize (object); +} + +static void +touchpad_skeleton_init (TouchpadSkeleton *skeleton) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + skeleton->priv = touchpad_skeleton_get_instance_private (skeleton); +#else + skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_TOUCHPAD_SKELETON, TouchpadSkeletonPrivate); +#endif + + g_mutex_init (&skeleton->priv->lock); + skeleton->priv->context = g_main_context_ref_thread_default (); +} + +static void +touchpad_skeleton_class_init (TouchpadSkeletonClass *klass) +{ + GObjectClass *gobject_class; + GDBusInterfaceSkeletonClass *skeleton_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = touchpad_skeleton_finalize; + + skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); + skeleton_class->get_info = touchpad_skeleton_dbus_interface_get_info; + skeleton_class->get_properties = touchpad_skeleton_dbus_interface_get_properties; + skeleton_class->flush = touchpad_skeleton_dbus_interface_flush; + skeleton_class->get_vtable = touchpad_skeleton_dbus_interface_get_vtable; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (TouchpadSkeletonPrivate)); +#endif +} + +static void +touchpad_skeleton_iface_init (TouchpadIface *iface) +{ +} + +/** + * touchpad_skeleton_new: + * + * Creates a skeleton object for the D-Bus interface cn.kylinos.touchpad. + * + * Returns: (transfer full) (type TouchpadSkeleton): The skeleton object. + */ +Touchpad * +touchpad_skeleton_new (void) +{ + return TOUCHPAD (g_object_new (TYPE_TOUCHPAD_SKELETON, NULL)); +} + diff --git a/src/hardware/touchpad/touchpad-generated.h b/src/hardware/touchpad/touchpad-generated.h new file mode 100644 index 0000000..44d45ad --- /dev/null +++ b/src/hardware/touchpad/touchpad-generated.h @@ -0,0 +1,217 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +G_BEGIN_DECLS + + +/* ------------------------------------------------------------------------ */ +/* Declarations for cn.kylinos.touchpad */ + +#define TYPE_TOUCHPAD (touchpad_get_type ()) +#define TOUCHPAD(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_TOUCHPAD, Touchpad)) +#define IS_TOUCHPAD(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_TOUCHPAD)) +#define TOUCHPAD_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), TYPE_TOUCHPAD, TouchpadIface)) + +struct _Touchpad; +typedef struct _Touchpad Touchpad; +typedef struct _TouchpadIface TouchpadIface; + +struct _TouchpadIface +{ + GTypeInterface parent_iface; + + gboolean (*handle_transfer_bool_value) ( + Touchpad *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + + gboolean (*handle_transfer_int_value) ( + Touchpad *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + +}; + +GType touchpad_get_type (void) G_GNUC_CONST; + +GDBusInterfaceInfo *touchpad_interface_info (void); +guint touchpad_override_properties (GObjectClass *klass, guint property_id_begin); + + +/* D-Bus method call completion functions: */ +void touchpad_complete_transfer_bool_value ( + Touchpad *object, + GDBusMethodInvocation *invocation); + +void touchpad_complete_transfer_int_value ( + Touchpad *object, + GDBusMethodInvocation *invocation); + + + +/* D-Bus method calls: */ +void touchpad_call_transfer_bool_value ( + Touchpad *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean touchpad_call_transfer_bool_value_finish ( + Touchpad *proxy, + GAsyncResult *res, + GError **error); + +gboolean touchpad_call_transfer_bool_value_sync ( + Touchpad *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + +void touchpad_call_transfer_int_value ( + Touchpad *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean touchpad_call_transfer_int_value_finish ( + Touchpad *proxy, + GAsyncResult *res, + GError **error); + +gboolean touchpad_call_transfer_int_value_sync ( + Touchpad *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + + + +/* ---- */ + +#define TYPE_TOUCHPAD_PROXY (touchpad_proxy_get_type ()) +#define TOUCHPAD_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_TOUCHPAD_PROXY, TouchpadProxy)) +#define TOUCHPAD_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_TOUCHPAD_PROXY, TouchpadProxyClass)) +#define TOUCHPAD_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_TOUCHPAD_PROXY, TouchpadProxyClass)) +#define IS_TOUCHPAD_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_TOUCHPAD_PROXY)) +#define IS_TOUCHPAD_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_TOUCHPAD_PROXY)) + +typedef struct _TouchpadProxy TouchpadProxy; +typedef struct _TouchpadProxyClass TouchpadProxyClass; +typedef struct _TouchpadProxyPrivate TouchpadProxyPrivate; + +struct _TouchpadProxy +{ + /*< private >*/ + GDBusProxy parent_instance; + TouchpadProxyPrivate *priv; +}; + +struct _TouchpadProxyClass +{ + GDBusProxyClass parent_class; +}; + +GType touchpad_proxy_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (TouchpadProxy, g_object_unref) +#endif + +void touchpad_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Touchpad *touchpad_proxy_new_finish ( + GAsyncResult *res, + GError **error); +Touchpad *touchpad_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + +void touchpad_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Touchpad *touchpad_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error); +Touchpad *touchpad_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + + +/* ---- */ + +#define TYPE_TOUCHPAD_SKELETON (touchpad_skeleton_get_type ()) +#define TOUCHPAD_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_TOUCHPAD_SKELETON, TouchpadSkeleton)) +#define TOUCHPAD_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_TOUCHPAD_SKELETON, TouchpadSkeletonClass)) +#define TOUCHPAD_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_TOUCHPAD_SKELETON, TouchpadSkeletonClass)) +#define IS_TOUCHPAD_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_TOUCHPAD_SKELETON)) +#define IS_TOUCHPAD_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_TOUCHPAD_SKELETON)) + +typedef struct _TouchpadSkeleton TouchpadSkeleton; +typedef struct _TouchpadSkeletonClass TouchpadSkeletonClass; +typedef struct _TouchpadSkeletonPrivate TouchpadSkeletonPrivate; + +struct _TouchpadSkeleton +{ + /*< private >*/ + GDBusInterfaceSkeleton parent_instance; + TouchpadSkeletonPrivate *priv; +}; + +struct _TouchpadSkeletonClass +{ + GDBusInterfaceSkeletonClass parent_class; +}; + +GType touchpad_skeleton_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (TouchpadSkeleton, g_object_unref) +#endif + +Touchpad *touchpad_skeleton_new (void); + + +G_END_DECLS + +#endif /* __TOUCHPAD_GENERATED_H__ */ diff --git a/src/language/Makefile.am b/src/language/Makefile.am new file mode 100644 index 0000000..e69de29 diff --git a/src/log4qt/Doxyfile b/src/log4qt/Doxyfile new file mode 100644 index 0000000..218bfe1 --- /dev/null +++ b/src/log4qt/Doxyfile @@ -0,0 +1,236 @@ +# Doxyfile 1.5.3 + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- +DOXYFILE_ENCODING = UTF-8 +PROJECT_NAME = Log4Qt +PROJECT_NUMBER = +OUTPUT_DIRECTORY = doc +CREATE_SUBDIRS = NO +OUTPUT_LANGUAGE = English +BRIEF_MEMBER_DESC = YES +REPEAT_BRIEF = YES +ABBREVIATE_BRIEF = +ALWAYS_DETAILED_SEC = NO +INLINE_INHERITED_MEMB = NO +FULL_PATH_NAMES = YES +STRIP_FROM_PATH = +STRIP_FROM_INC_PATH = +SHORT_NAMES = NO +JAVADOC_AUTOBRIEF = NO +QT_AUTOBRIEF = NO +MULTILINE_CPP_IS_BRIEF = NO +DETAILS_AT_TOP = NO +INHERIT_DOCS = YES +SEPARATE_MEMBER_PAGES = NO +TAB_SIZE = 4 +ALIASES = +OPTIMIZE_OUTPUT_FOR_C = NO +OPTIMIZE_OUTPUT_JAVA = NO +BUILTIN_STL_SUPPORT = NO +CPP_CLI_SUPPORT = NO +DISTRIBUTE_GROUP_DOC = NO +SUBGROUPING = YES +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- +EXTRACT_ALL = YES +EXTRACT_PRIVATE = NO +EXTRACT_STATIC = NO +EXTRACT_LOCAL_CLASSES = NO +EXTRACT_LOCAL_METHODS = NO +EXTRACT_ANON_NSPACES = NO +HIDE_UNDOC_MEMBERS = NO +HIDE_UNDOC_CLASSES = NO +HIDE_FRIEND_COMPOUNDS = NO +HIDE_IN_BODY_DOCS = NO +INTERNAL_DOCS = NO +CASE_SENSE_NAMES = NO +HIDE_SCOPE_NAMES = NO +SHOW_INCLUDE_FILES = YES +INLINE_INFO = YES +SORT_MEMBER_DOCS = YES +SORT_BRIEF_DOCS = NO +SORT_BY_SCOPE_NAME = NO +GENERATE_TODOLIST = YES +GENERATE_TESTLIST = YES +GENERATE_BUGLIST = YES +GENERATE_DEPRECATEDLIST= YES +ENABLED_SECTIONS = +MAX_INITIALIZER_LINES = 30 +SHOW_USED_FILES = YES +SHOW_DIRECTORIES = NO +FILE_VERSION_FILTER = +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- +QUIET = NO +WARNINGS = YES +WARN_IF_UNDOCUMENTED = YES +WARN_IF_DOC_ERROR = YES +WARN_NO_PARAMDOC = NO +WARN_FORMAT = "$file:$line: $text " +WARN_LOGFILE = +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- +INPUT = +INPUT_ENCODING = UTF-8 +FILE_PATTERNS = +RECURSIVE = YES +EXCLUDE = +EXCLUDE_SYMLINKS = NO +EXCLUDE_PATTERNS = *_p.h \ + *.cpp +EXCLUDE_SYMBOLS = +EXAMPLE_PATH = +EXAMPLE_PATTERNS = +EXAMPLE_RECURSIVE = NO +IMAGE_PATH = +INPUT_FILTER = +FILTER_PATTERNS = +FILTER_SOURCE_FILES = NO +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- +SOURCE_BROWSER = NO +INLINE_SOURCES = NO +STRIP_CODE_COMMENTS = YES +REFERENCED_BY_RELATION = YES +REFERENCES_RELATION = YES +REFERENCES_LINK_SOURCE = YES +USE_HTAGS = NO +VERBATIM_HEADERS = YES +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- +ALPHABETICAL_INDEX = NO +COLS_IN_ALPHA_INDEX = 5 +IGNORE_PREFIX = +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- +GENERATE_HTML = YES +HTML_OUTPUT = html +HTML_FILE_EXTENSION = .html +HTML_HEADER = +HTML_FOOTER = +HTML_STYLESHEET = +HTML_ALIGN_MEMBERS = YES +GENERATE_HTMLHELP = NO +HTML_DYNAMIC_SECTIONS = NO +CHM_FILE = +HHC_LOCATION = +GENERATE_CHI = NO +BINARY_TOC = NO +TOC_EXPAND = NO +DISABLE_INDEX = NO +ENUM_VALUES_PER_LINE = 4 +GENERATE_TREEVIEW = NO +TREEVIEW_WIDTH = 250 +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- +GENERATE_LATEX = NO +LATEX_OUTPUT = latex +LATEX_CMD_NAME = latex +MAKEINDEX_CMD_NAME = makeindex +COMPACT_LATEX = NO +PAPER_TYPE = a4wide +EXTRA_PACKAGES = +LATEX_HEADER = +PDF_HYPERLINKS = NO +USE_PDFLATEX = NO +LATEX_BATCHMODE = NO +LATEX_HIDE_INDICES = NO +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- +GENERATE_RTF = NO +RTF_OUTPUT = rtf +COMPACT_RTF = NO +RTF_HYPERLINKS = NO +RTF_STYLESHEET_FILE = +RTF_EXTENSIONS_FILE = +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- +GENERATE_MAN = NO +MAN_OUTPUT = man +MAN_EXTENSION = .3 +MAN_LINKS = NO +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- +GENERATE_XML = NO +XML_OUTPUT = xml +XML_SCHEMA = +XML_DTD = +XML_PROGRAMLISTING = YES +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- +GENERATE_AUTOGEN_DEF = NO +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- +GENERATE_PERLMOD = NO +PERLMOD_LATEX = NO +PERLMOD_PRETTY = YES +PERLMOD_MAKEVAR_PREFIX = +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- +ENABLE_PREPROCESSING = YES +MACRO_EXPANSION = YES +EXPAND_ONLY_PREDEF = YES +SEARCH_INCLUDES = YES +INCLUDE_PATH = +INCLUDE_FILE_PATTERNS = +PREDEFINED = Q_CORE_EXPORT=\ \ + "Q_DECLARE_FLAGS(Flags, Enum)=typedef QFlags Flags; " \ + Q_WS_WIN=1 \ + Q_WS_MAC=1 \ + Q_WS_X11=1 +EXPAND_AS_DEFINED = +SKIP_FUNCTION_MACROS = YES +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- +TAGFILES = +GENERATE_TAGFILE = +ALLEXTERNALS = NO +EXTERNAL_GROUPS = YES +PERL_PATH = +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- +CLASS_DIAGRAMS = YES +MSCGEN_PATH = +HIDE_UNDOC_RELATIONS = YES +HAVE_DOT = NO +CLASS_GRAPH = YES +COLLABORATION_GRAPH = YES +GROUP_GRAPHS = YES +UML_LOOK = NO +TEMPLATE_RELATIONS = NO +INCLUDE_GRAPH = YES +INCLUDED_BY_GRAPH = YES +CALL_GRAPH = NO +CALLER_GRAPH = NO +GRAPHICAL_HIERARCHY = YES +DIRECTORY_GRAPH = YES +DOT_IMAGE_FORMAT = png +DOT_PATH = +DOTFILE_DIRS = +DOT_GRAPH_MAX_NODES = 50 +MAX_DOT_GRAPH_DEPTH = 0 +DOT_TRANSPARENT = NO +DOT_MULTI_TARGETS = NO +GENERATE_LEGEND = YES +DOT_CLEANUP = YES +#--------------------------------------------------------------------------- +# Configuration::additions related to the search engine +#--------------------------------------------------------------------------- +SEARCHENGINE = NO diff --git a/src/log4qt/LICENSE-2.0.txt b/src/log4qt/LICENSE-2.0.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/src/log4qt/LICENSE-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/log4qt/README.txt b/src/log4qt/README.txt new file mode 100644 index 0000000..1fbddd7 --- /dev/null +++ b/src/log4qt/README.txt @@ -0,0 +1 @@ +See HTML documentation under doc/index.html \ No newline at end of file diff --git a/src/log4qt/doc/default.css b/src/log4qt/doc/default.css new file mode 100644 index 0000000..d619f8d --- /dev/null +++ b/src/log4qt/doc/default.css @@ -0,0 +1,44 @@ +BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV { + font-family: Geneva, Arial, Helvetica, sans-serif; +} +BODY,TD { + font-size: 90%; +} +H1 { + text-align: center; + font-size: 160%; +} +H2 { + font-size: 120%; +} +H3 { + font-size: 100%; +} +H2 { + background-color: #e8eef2; + color: #1a419d; + font-weight: bold; + padding-right : 10px; + padding-top : 2px; + padding-left : 10px; + padding-bottom : 2px; + margin-left : 0px; + margin-right : 0px; + margin-top : 2px; + margin-bottom : 2px; + border: 1px solid #cccccc; +} +A { + text-decoration: none; + font-weight: bold; + color: #1A419D; +} +A:visited { + text-decoration: none; + font-weight: bold; + color: #1A419D +} +A:hover { + text-decoration: none; + background-color: #ddddff; +} diff --git a/src/log4qt/doc/index.html b/src/log4qt/doc/index.html new file mode 100644 index 0000000..7b79fbc --- /dev/null +++ b/src/log4qt/doc/index.html @@ -0,0 +1,155 @@ + + + + Log4Qt + + + + +

Log4Qt

+

Introduction

+

+Log4Qt is a C++ port of the Apache Software Foundation Log4j package using the +Trolltech Qt Framework. It is intended to be used by open source and commercial +Qt projects. +

+ +

Documentation

+

+The documentation describes classes and methods that have been added or changed +compared to Log4j. The documentation was generated from the source code using +Doxygen. It can be accessed here. +

+ +

How to use

+

+To use Log4Qt within your software project include the Log4Qt source into your project +

    +
  1. + Download the package from the + SourceForge project page +
  2. + Unpack the Log4Qt package +
  3. + Add the log4qt source to the Qt project file by adding the following line
    + include(<unpackdir>/src/log4qt/log4qt.pri) +
  4. + Include the Logger class, a layout and an appender class to configure Log4Qt to generate output. The example uses the ConsoleAppender with a TTCCLayout
    + include "log4qt/consoleappender.h"
    + include "log4qt/logger.h"
    + include "log4qt/ttcclayout.h" +
  5. + Configure a logger to generate output. The example uses the root logger
    + // Create a layout
    + Log4Qt::LogManager::rootLogger();
    + TTCCLayout *p_layout = new TTCCLayout();
    + p_layout->setName(QLatin1String("My Layout"));
    + p_layout->activateOptions();
    + // Create an appender
    + ConsoleAppender *p_appender = new ConsoleAppender(p_layout, ConsoleAppender::STDOUT_TARGET);
    + p_appender->setName(QLatin1String("My Appender"));
    + p_appender->activateOptions();
    + // Set appender on root logger
    + Log4Qt::Logger::rootLogger()->setAppender(p_appender); +
  6. + Request a logger by either calling Log4Qt::Logger::logger or using LOG4QT_DECLARE_QCLASS_LOGGER
    + // Request a logger and output "Hello World!"
    + Log4Qt::Logger::logger(QLatin1String("My Logger"))->info("Hello World!");
    +
  7. +
+

+ +

Releases

+

+

    +
  • + 0.3 - 01 March 2009
    + Bug fixes, compatibility with VS 2008 and Qt 4.5 RC1 +
      +
    • + Fixed a problem where the pParent parameter of the constructor was not passed on to the QObject constructor (logobject.h) +
    • +
    • + Fixed a problem were OptionConverter::toBoolean would not return the default value, if the conversion fails (optionconverter.cpp) +
    • +
    • + Fixed a compile error on VS 2008 by using Q_UNUSED(&rEvent) instead of Q_UNUSED(rEvent) (varia/denyallfilter.h.h) +
    • +
    • + Fixed VS 2008 unreferenced formal parameter warning by using Q_UNUSED (logmanager.cpp, mdc.cpp, ndc.cpp, propertyconfigurator.cpp, helpers/initialisationhelper.cpp, helpers/patternformatter.cpp) +
    • +
    +
  • +
  • + 0.2 - 30 January 2009
    + Bug fixes and compatibility with Qt 4.4 +
      +
    • + Added a compile time version check for the Qt version (log4qt.h) +
    • +
    • + Replaced usage of q_atomic_increment and q_atomic_decrement with QAtomicInt for compilation with Qt 4.4 (helpers/logobject.h) +
    • +
    • + Replaced usage of q_atomic_test_and_set_ptr with QAtomicPointer for compilation with Qt 4.4 (logger.h, helpers/classlogger.cpp, helpers/classlogger.h, helpers/initialisationhelper.h) +
    • +
    • + Fixed a problem with Qt 4.4 where QReadWriteLock is by default non-recursive (hierarchy.cpp, logger.cpp) +
    • +
    • + Resolved compilation problem with Microsoft Visual Studio 2005 (logmanager.cpp, helpers/datetime.cpp) +
    • +
    +
  • +
  • + 0.1 - 29 December 2007
    + Initial Version +
  • +
+

+ +

Known Problems

+

+

    +
  • + The Eclipse CDT console does not display the log output of a correctly + when using a ConsoleAppender with a TTCCLayout and relative time format. + The millisecond count is stripped from the output. +
  • +
+

+ +

License

+

+Log4Qt is licensed under the +Apache License Version 2.0. +

+

+Log4Qt requires the Qt framework that is available under several licensing options +(Qt licensing). +The package is intended to be used under the +Nokia Corporation Qt GPL Exception. +

+ +

Links

+

+

+

+ +

+
+ + + + + +
SourceForge.net LogoXX February 2009, Martin Heinrich
+

+ + diff --git a/src/log4qt/log4qt.conf b/src/log4qt/log4qt.conf new file mode 100644 index 0000000..bb9c8e3 --- /dev/null +++ b/src/log4qt/log4qt.conf @@ -0,0 +1,66 @@ +#设置储存log文件的根目录 +logpath=. + +#全局设置 +#是否重置所有配置,恢复全局设置默认值 +log4j.reset=true +#设置Log4Qt记录器输入级别 +log4j.Debug=INFO +#日志记录器存储库的阈值 +log4j.threshold=NULL +#设置是否监听QDebug输出的字符串 +log4j.handleQtMessages=true + +#设置根Logger的输出log等级为INFO +#设置Log输出的几种输出源(appender):console, daily +log4j.rootLogger=DEBUG,console,daily + +#设置终端打印记录器 +#记录器类别 --控制台输出 +log4j.appender.console=org.apache.log4j.ConsoleAppender +#记录器输出目标 +log4j.appender.console.target=STDOUT_TARGET +#记录器输出布局 (包含日志产生的时间、线程、类别等信息) +log4j.appender.console.layout=org.apache.log4j.TTCCLayout +#记录器布局日期格式 (年-月-日 时:分:秒.毫秒) +log4j.appender.console.layout.dateFormat=yyy-MM-dd hh:mm:ss.zzz +#记录器布局包含上下文 +log4j.appender.console.layout.contextPrinting=false +#记录器布局包含线程信息 +#log4j.appender.console.layout.ThreadPrinting=false + +#设置一个每日储存一个log文件的记录器 +#记录器类别 --一天一个文件输出 +log4j.appender.daily=org.apache.log4j.DailyRollingFileAppender +#记录器输出文件路径 +log4j.appender.daily.file=${logpath}/log4qt.log +#记录器追加文件内容 +log4j.appender.daily.appendFile=true +#记录器是否直接写入文件 +#log4j.appender.daily.immediateFlush=true +#记录器文件名日期后缀 按天 +log4j.appender.daily.datePattern=.yyyy-MM-dd +#记录器布局分隔符 (根据patten符号格式化输出数据,类似printf的格式化方式) +log4j.appender.daily.layout=org.apache.log4j.PatternLayout +log4j.appender.daily.layout.conversionPattern=%-5p|%d{yyyy-MM-dd HH:mm:ss,zzz}(%-4r)|%m%n +#记录器输出格式 +#日志信息格式中几个符号所代表的含义: +# -X号: X信息输出时左对齐; +# %p: 输出日志信息优先级,即DEBUG,INFO,WARN,ERROR,FATAL, +# %d: 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss,SSS},输出类似:2002年10月18日 22:10:28,921 +# %r: 输出自应用启动到输出该log信息耗费的毫秒数 +# %c: 输出日志信息所属的类目,通常就是所在类的全名 (无效) +# %t: 输出产生该日志事件的线程名 (无效) +# %l: 输出日志事件的发生位置,相当于%C.%M(%F:%L)的组合,包括类目名、发生的线程,以及在代码中的行数(无效)。举例:Testlog4.main (TestLog4.java:10) +# %x: 输出和当前线程相关联的NDC(嵌套诊断环境),尤其用到像java servlets这样的多客户多线程的应用中。 +# %%: 输出一个"%"字符 +# %F: 输出日志消息产生时所在的文件名称(无效) +# %L: 输出代码中的行号(无效) +# %m: 输出代码中指定的消息,产生的日志具体信息(默认在消息内容前追加了文件名,行号,函数名) +# %n: 输出一个回车换行符,Windows平台为"\r\n",Unix平台为"\n"输出日志信息换行 +# 可以在%与模式字符之间加上修饰符来控制其最小宽度、最大宽度、和文本的对齐方式。如: +# 1) c:指定输出category的名称,最小的宽度是20,如果category的名称小于20的话,默认的情况下右对齐。 +# 2)%-20c:指定输出category的名称,最小的宽度是20,如果category的名称小于20的话,"-"号指定左对齐。 +# 3)%.30c:指定输出category的名称,最大的宽度是30,如果category的名称大于30的话,就会将左边多出的字符截掉,但小于30的话也不会有空格。 +# 4) .30c:如果category的名称小于20就补空格,并且右对齐,如果其名称长于30字符,就从左边较远输出的字符截掉。 + diff --git a/src/log4qt/log4qt/appender.h b/src/log4qt/log4qt/appender.h new file mode 100644 index 0000000..cb7a217 --- /dev/null +++ b/src/log4qt/log4qt/appender.h @@ -0,0 +1,137 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: appender.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ********************************************************************************/ + +#ifndef LOG4QT_APPENDER_H +#define LOG4QT_APPENDER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/helpers/logobject.h" + +#include "log4qt/helpers/logobjectptr.h" + +#include "log4qt/logger.h" + +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + class Filter; + class Layout; + class LoggingEvent; + + /*! + * \brief The class Appender is the base class for all Appenders. + * + * To allow the whole hirarchy to be an ascendant of QObject Appender is + * not an interface. + * + * \note All the functions declared in this class are thread-safe. + * + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT Appender : public LogObject + { + Q_OBJECT + + /*! + * The property holds the Layout used by the Appender. + * + * \sa layout(), setLayout() + */ + Q_PROPERTY(Layout* layout READ layout WRITE setLayout) + + /*! + * The property holds the name of the Appender. + * + * \sa name(), setName() + */ + Q_PROPERTY(QString name READ name WRITE setName) + + /*! + * The property holds if the Appender requires a Layout or not. + * + * \sa requiresLayout(), setRequiresLayout() + */ + Q_PROPERTY(bool requiresLayout READ requiresLayout) + + public: + Appender(QObject *pParent = 0); + virtual ~Appender(); + private: + Appender(const Appender &rOther); // Not implemented + Appender &operator=(const Appender &rOther); // Not implemented + + public: + // JAVA: ErrorHandler* errorHandler(); + virtual Filter *filter() const = 0; + virtual QString name() const = 0; + virtual Layout *layout() const = 0; + virtual bool requiresLayout() const = 0; + // JAVA: void setErrorHandler(ErrorHandler *pErrorHandler); + virtual void setLayout(Layout *pLayout) = 0; + virtual void setName(const QString &rName) = 0; + + virtual void addFilter(Filter *pFilter) = 0; + virtual void clearFilters() = 0; + virtual void close() = 0; + virtual void doAppend(const LoggingEvent &rEvent) = 0; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline Appender::Appender(QObject *pParent) : + LogObject(pParent) + {} + + inline Appender::~Appender() + {} + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::Appender, Q_COMPLEX_TYPE); // Use default +Q_DECLARE_TYPEINFO(Log4Qt::LogObjectPtr, Q_MOVABLE_TYPE); + + +#endif // LOG4QT_APPENDER_H diff --git a/src/log4qt/log4qt/appenderskeleton.cpp b/src/log4qt/log4qt/appenderskeleton.cpp new file mode 100644 index 0000000..d9f784b --- /dev/null +++ b/src/log4qt/log4qt/appenderskeleton.cpp @@ -0,0 +1,261 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: appenderskeleton.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/appenderskeleton.h" + +#include +#include "log4qt/layout.h" +#include "log4qt/loggingevent.h" +#include "log4qt/logmanager.h" +#include "log4qt/spi/filter.h" + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + ***************************************************************************/ + + + /*! + * \brief The class RecursionGuardLocker controls a boolean flag. + * + * It is a helper class to control a boolean flag. The class sets the flag + * on creation and resets it on destruction. + */ + class RecursionGuardLocker + { + public: + RecursionGuardLocker(bool *pGuard); + ~RecursionGuardLocker(); + private: + RecursionGuardLocker(const RecursionGuardLocker &rOther); // Not implemented + RecursionGuardLocker &operator=(const RecursionGuardLocker &rOther); // Not implemented + private: + bool *mpGuard; + }; + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: RecursionGuardLocker + ***************************************************************************/ + + + inline RecursionGuardLocker::RecursionGuardLocker(bool *pGuard) + { + Q_ASSERT_X(pGuard != 0, "RecursionGuardLocker::RecursionGuardLocker()", "Pointer to guard bool must not be null"); + + mpGuard = pGuard; + *mpGuard = true; + } + + + inline RecursionGuardLocker::~RecursionGuardLocker() + { + *mpGuard = false; + }; + + + + /************************************************************************** + * Class implementation: AppenderSkeleton + **************************************************************************/ + + + AppenderSkeleton::AppenderSkeleton(QObject *pParent) : + Appender(pParent), + mObjectGuard(QMutex::Recursive), // Recursive for doAppend() + mAppendRecursionGuard(false), + mIsActive(true), + mIsClosed(false), + mpLayout(0), + mThreshold(Level::NULL_INT), + mpHeadFilter(0), + mpTailFilter(0) + { + } + + + AppenderSkeleton::AppenderSkeleton(const bool isActive, + QObject *pParent) : + Appender(pParent), + mObjectGuard(QMutex::Recursive), // Recursive for doAppend() + mAppendRecursionGuard(false), + mIsActive(isActive), + mIsClosed(false), + mpLayout(0), + mThreshold(Level::NULL_INT), + mpHeadFilter(0), + mpTailFilter(0) + { + } + + + void AppenderSkeleton::activateOptions() + { + QMutexLocker locker(&mObjectGuard); + + if (requiresLayout() && !layout()) + { + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Activation of appender '%1' that requires layout and has no layout set"), + APPENDER_ACTIVATE_MISSING_LAYOUT_ERROR); + e << name(); + logger()->error(e); + return; + } + mIsActive = true; + } + + + void AppenderSkeleton::addFilter(Filter *pFilter) + { + if(!pFilter) + { + logger()->warn("Adding null Filter to Appender '%1'", name()); + return; + } + + QMutexLocker locker(&mObjectGuard); + + mpTailFilter = pFilter; + if (mpHeadFilter) + mpHeadFilter->setNext(pFilter); + else + mpHeadFilter = pFilter; + } + + + void AppenderSkeleton::clearFilters() + { + QMutexLocker locker(&mObjectGuard); + + mpTailFilter = 0; + mpHeadFilter = 0; + } + + + void AppenderSkeleton::close() + { + QMutexLocker locker(&mObjectGuard); + + mIsClosed = true; + mIsActive = false; + } + + + void AppenderSkeleton::doAppend(const LoggingEvent &rEvent) + { + // The mutex serialises concurrent access from multiple threads. + // - e.g. two threads using the same logger + // - e.g. two threads using different logger with the same appender + // + // A call from the same thread will pass the mutex (QMutex::Recursive) + // and get to the recursion guard. The recursion guard blocks recursive + // invocation and prevents a possible endless loop. + // - e.g. an appender logs an error with a logger that uses it + + QMutexLocker locker(&mObjectGuard); + + if (mAppendRecursionGuard) + return; + + RecursionGuardLocker recursion_locker(&mAppendRecursionGuard); + + if (!checkEntryConditions()) + return; + if (!isAsSevereAsThreshold(rEvent.level())) + return; + + Filter *p_filter = mpHeadFilter; + while(p_filter) + { + Filter::Decision decision = p_filter->decide(rEvent); + if (decision == Filter::ACCEPT) + break; + else if (decision == Filter::DENY) + return; + else + p_filter = p_filter->next(); + } + + append(rEvent); + } + + + bool AppenderSkeleton::checkEntryConditions() const + { + // Q_ASSERT_X(, "WriterAppender::checkEntryConditions()", "Lock must be held by caller") + + if (!isActive()) + { + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of non activated appender '%1'"), + APPENDER_NOT_ACTIVATED_ERROR); + e << name(); + logger()->error(e); + return false; + } + if (isClosed()) + { + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of closed appender '%1'"), + APPENDER_CLOSED_ERROR); + e << name(); + logger()->error(e); + return false; + } + if (requiresLayout() && !layout()) + { + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of appender '%1' that requires layout and has no layout set"), + APPENDER_USE_MISSING_LAYOUT_ERROR); + e << name(); + logger()->error(e); + return false; + } + + return true; + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/appenderskeleton.h b/src/log4qt/log4qt/appenderskeleton.h new file mode 100644 index 0000000..8438ac1 --- /dev/null +++ b/src/log4qt/log4qt/appenderskeleton.h @@ -0,0 +1,229 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: appenderskeleton.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_APPENDERSKELETON_H +#define LOG4QT_APPENDERSKELETON_H + + +/****************************************************************************** + * Dependencies +******************************************************************************/ + +#include "log4qt/appender.h" + +#include +#include "log4qt/helpers/logobjectptr.h" +#include "ukui-logmacros.h" + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + class Filter; + class Layout; + class Logger; + class LoggingEvent; + + /*! + * \brief The class AppenderSkeleton implements general Appender functionality. + * + * \note All the functions declared in this class are thread-safe. + * + * \note The ownership and lifetime of objects of this class are managed. See + * \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT AppenderSkeleton : public Appender + { + Q_OBJECT + + /*! + * The property holds if the Appender has been activated. + * + * \sa isActive() + */ + Q_PROPERTY(bool isActive READ isActive) + + /*! + * The property holds if the Appender has been closed. + * + * \sa isClosed() + */ + Q_PROPERTY(bool isClosed READ isClosed) + + /*! + * The property holds the threshold level used by the Appender. + * + * \sa threshold(), setThreshold() + */ + Q_PROPERTY(Level threshold READ threshold WRITE setThreshold) + + public: + AppenderSkeleton(QObject *pParent = 0); + protected: + AppenderSkeleton(const bool isActive, + QObject *pParent = 0); + public: + // virtual ~AppenderSkeleton(); Use compiler default + private: + AppenderSkeleton(const AppenderSkeleton &rOther); // Not implemented + AppenderSkeleton &operator=(const AppenderSkeleton &rOther); // Not implemented + + public: + // JAVA: ErrorHandler* errorHandler(); + virtual Filter *filter() const; + virtual Layout *layout() const; + bool isActive() const; + bool isClosed() const; + virtual QString name() const; + Level threshold() const; + // JAVA: void setErrorHandler(ErrorHandler *pErrorHandler); + virtual void setLayout(Layout *pLayout); + virtual void setName(const QString &rName); + void setThreshold(Level level); + + virtual void activateOptions(); + virtual void addFilter(Filter *pFilter); + virtual void clearFilters(); + virtual void close(); + + /*! + * Performs checks and delegates the actuall appending to the subclass + * specific append() function. + * + * \sa append(), checkEntryConditions(), isAsSevereAsThreshold(), Filter + */ + virtual void doAppend(const LoggingEvent &rEvent); + + // JAVA: void finalize(); + Filter* firstFilter() const; + bool isAsSevereAsThreshold(Level level) const; + + protected: + virtual void append(const LoggingEvent &rEvent) = 0; + virtual void asyncAppend(const LoggingEvent &rEvent) = 0; + + /*! + * Tests if all entry conditions for using append() in this class are + * met. + * + * If a conditions is not met, an error is logged and the function + * returns false. + * + * The checked conditions are: + * - That the appender has been activated (APPENDER_NOT_ACTIVATED_ERROR) + * - That the appender was not closed (APPENDER_CLOSED_ERROR) + * - That the appender has a layout set, if it requires one + * (logging_error(APPENDER_USE_MISSING_LAYOUT_ERROR) + * + * The function is called as part of the checkEntryConditions() chain + * started by doAppend(). The doAppend() function calls the subclass + * specific checkEntryConditions() function. The function checks the + * class specific conditions and calls checkEntryConditions() of + * it's parent class. The last function called is + * AppenderSkeleton::checkEntryConditions(). + * + * \sa doAppend() + */ + virtual bool checkEntryConditions() const; + + protected: + mutable QMutex mObjectGuard; + private: + bool mAppendRecursionGuard; + volatile bool mIsActive; + volatile bool mIsClosed; + LogObjectPtr mpLayout; + Level mThreshold; + LogObjectPtr mpHeadFilter; + LogObjectPtr mpTailFilter; + + // need AsyncDispatcher to call asyncAppend method + friend class AsyncDispatcher; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline Filter *AppenderSkeleton::filter() const + { QMutexLocker locker(&mObjectGuard); + return mpHeadFilter; } + + inline Layout *AppenderSkeleton::layout() const + { QMutexLocker locker(&mObjectGuard); + return mpLayout; } + + inline QString AppenderSkeleton::name() const + { QMutexLocker locker(&mObjectGuard); + return objectName(); } + + inline Level AppenderSkeleton::threshold() const + { // QMutexLocker locker(&mObjectGuard); // Level is threadsafe + return mThreshold; } + + inline void AppenderSkeleton::setLayout(Layout *pLayout) + { QMutexLocker locker(&mObjectGuard); + mpLayout = pLayout; } + + inline void AppenderSkeleton::setName(const QString &rName) + { QMutexLocker locker(&mObjectGuard); + setObjectName(rName); } + + inline void AppenderSkeleton::setThreshold(Level level) + { // QMutexLocker locker(&mObjectGuard); // Level is threadsafe + mThreshold = level; } + + inline bool AppenderSkeleton::isActive() const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mIsActive; } + + inline bool AppenderSkeleton::isClosed() const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mIsClosed; } + + inline Filter *AppenderSkeleton::firstFilter() const + { QMutexLocker locker(&mObjectGuard); + return filter(); } + + inline bool AppenderSkeleton::isAsSevereAsThreshold(Level level) const + { // QMutexLocker locker(&mObjectGuard); // Level is threadsafe + return (mThreshold <= level); } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::AppenderSkeleton, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_APPENDERSKELETON_H diff --git a/src/log4qt/log4qt/basicconfigurator.cpp b/src/log4qt/log4qt/basicconfigurator.cpp new file mode 100644 index 0000000..280b88d --- /dev/null +++ b/src/log4qt/log4qt/basicconfigurator.cpp @@ -0,0 +1,107 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: basicconfigurator.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/basicconfigurator.h" + +#include +#include +#include +#include "log4qt/consoleappender.h" +#include "log4qt/helpers/configuratorhelper.h" +#include "log4qt/helpers/logobjectptr.h" +#include "log4qt/logmanager.h" +#include "log4qt/patternlayout.h" +#include "log4qt/varia/listappender.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: BasicConfigurator + **************************************************************************/ + + + bool BasicConfigurator::configure() + { + LogObjectPtr list = new ListAppender; + list->setName(QLatin1String("BasicConfigurator")); + list->setConfiguratorList(true); + list->setThreshold(Level::ERROR_INT); + LogManager::logLogger()->addAppender(list); + + PatternLayout *p_layout = new PatternLayout(PatternLayout::TTCC_CONVERSION_PATTERN); + p_layout->setName(QLatin1String("BasicConfigurator TTCC")); + p_layout->activateOptions(); + ConsoleAppender *p_appender = new ConsoleAppender(p_layout, ConsoleAppender::STDOUT_TARGET); + p_appender->setName(QLatin1String("BasicConfigurator stdout")); + p_appender->activateOptions(); + LogManager::rootLogger()->addAppender(p_appender); + + LogManager::logLogger()->removeAppender(list); + ConfiguratorHelper::setConfigureError(list->list()); + return (list->list().count() == 0); + } + + + void BasicConfigurator::configure(Appender *pAppender) + { + LogManager::rootLogger()->addAppender(pAppender); + } + + + void BasicConfigurator::resetConfiguration() + { + LogManager::resetConfiguration(); + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/basicconfigurator.h b/src/log4qt/log4qt/basicconfigurator.h new file mode 100644 index 0000000..5dfa62f --- /dev/null +++ b/src/log4qt/log4qt/basicconfigurator.h @@ -0,0 +1,85 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: basicconfigurator.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_BASICCONFIGURATOR_H +#define LOG4QT_BASICCONFIGURATOR_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include +#include "log4qt/log4qt.h" +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + class Appender; + + /*! + * \brief The class BasicConfigurator provides a simple package + * configuration. + * + * \note All the functions declared in this class are thread-safe. + */ + class LIBUKUILOG4QT_EXPORT BasicConfigurator + { + private: + BasicConfigurator(); // Not implemented + // BasicConfigurator(const BasicConfigurator &rOther); // Use compiler default + // virtual ~BasicConfigurator(); // Use compiler default + // BasicConfigurator &operator=(const BasicConfigurator &rOther); // Use compiler default + + public: + static bool configure(); + static void configure(Appender *pAppender); + static void resetConfiguration(); + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + +} // namspace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::BasicConfigurator, Q_MOVABLE_TYPE); // Use default + + +#endif // LOG4QT_BASICCONFIGURATOR_H diff --git a/src/log4qt/log4qt/consoleappender.cpp b/src/log4qt/log4qt/consoleappender.cpp new file mode 100644 index 0000000..1b4fe03 --- /dev/null +++ b/src/log4qt/log4qt/consoleappender.cpp @@ -0,0 +1,198 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: consoleappender.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/consoleappender.h" + +#include +#include +#include "log4qt/helpers/optionconverter.h" +#include "log4qt/layout.h" +#include "log4qt/loggingevent.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: ConsoleAppender + **************************************************************************/ + + + ConsoleAppender::ConsoleAppender(QObject *pParent) : + WriterAppender(pParent), + mTarget(STDOUT_TARGET), + mpTextStream(0) + { + } + + + ConsoleAppender::ConsoleAppender(Layout *pLayout, + QObject *pParent) : + WriterAppender(pLayout, pParent), + mTarget(STDOUT_TARGET), + mpTextStream(0) + { + } + + + ConsoleAppender::ConsoleAppender(Layout *pLayout, + const QString &rTarget, + QObject *pParent) : + WriterAppender(pLayout, pParent), + mTarget(STDOUT_TARGET), + mpTextStream(0) + { + setTarget(rTarget); + } + + + ConsoleAppender::ConsoleAppender(Layout *pLayout, + Target target, + QObject *pParent) : + WriterAppender(pLayout, pParent), + mTarget(target), + mpTextStream(0) + { + } + + + ConsoleAppender::~ConsoleAppender() + { + close(); + } + + + QString ConsoleAppender::target() const + { + // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + + if (mTarget == STDOUT_TARGET) + return QLatin1String("STDOUT_TARGET"); + else + return QLatin1String("STDERR_TARGET"); + } + + + void ConsoleAppender::setTarget(const QString &rTarget) + { + bool ok; + Target target = (Target)OptionConverter::toTarget(rTarget, &ok); + if (ok) + setTarget(target); + } + + + void ConsoleAppender::activateOptions() + { + QMutexLocker locker(&mObjectGuard); + + closeStream(); + + if (mTarget == STDOUT_TARGET) + mpTextStream = new QTextStream(stdout); + else + mpTextStream = new QTextStream(stderr); + setWriter(mpTextStream); + + WriterAppender::activateOptions(); + } + + + void ConsoleAppender::close() + { + QMutexLocker locker(&mObjectGuard); + + if (isClosed()) + return; + + WriterAppender::close(); + closeStream(); + } + + + void ConsoleAppender::closeStream() + { + // Q_ASSERT_X(, "ConsoleAppender::closeStream()", "Lock must be held by caller") + + setWriter(0); + delete mpTextStream; + mpTextStream = 0; + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug ConsoleAppender::debug(QDebug &rDebug) const + { + QString layout_name; + if (layout()) + layout_name = layout()->name(); + QString target; + if (mTarget == STDOUT_TARGET) + target = QLatin1String("STDOUT"); + else + target = QLatin1String("STDERR"); + + rDebug.nospace() << "ConsoleAppender(" + << "name:" << name() << " " + << "filter:" << firstFilter() << " " + << "isactive:" << isActive() << " " + << "isclosed:" << isClosed() << " " + << "layout:" << layout_name << " " + << "target:" << target << " " + << "referencecount:" << referenceCount() << " " + << "threshold:" << threshold().toString() + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + + /****************************************************************************** + * Implementation: Operators, Helper + ******************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/consoleappender.h b/src/log4qt/log4qt/consoleappender.h new file mode 100644 index 0000000..17fd969 --- /dev/null +++ b/src/log4qt/log4qt/consoleappender.h @@ -0,0 +1,160 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: consoleappender.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_CONSOLEAPPENDER_H +#define LOG4QT_CONSOLEAPPENDER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/writerappender.h" +#include "ukui-logmacros.h" + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +class QFile; +class QTextStream; + +namespace Log4Qt +{ + + /*! + * \brief The class ConsoleAppender appends to stdout or stderr. + * + * \note All the functions declared in this class are thread-safe. + * + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT ConsoleAppender : public WriterAppender + { + Q_OBJECT + + /*! + * The property holds the target used by the appender. + * + * The default is STDOUT_TARGET for the standard output. + * + * \sa Target, target(), setTarget() + */ + Q_PROPERTY(QString target READ target WRITE setTarget) + + public: + /*! + * The enum defines the possible output targets + * + * \sa target(), setTarget() + */ + enum Target { + /*! The output target is standard out. */ + STDOUT_TARGET, + /*! The output target is standard error. */ + STDERR_TARGET + }; + Q_ENUMS(Target) + + ConsoleAppender(QObject *pParent = 0); + ConsoleAppender(Layout *pLayout, + QObject *pParent = 0); + ConsoleAppender(Layout *pLayout, + const QString &rTarget, + QObject *pParent = 0); + + /*! + * Creates a ConsoleAppender with the layout \a pLayout, the target + * value specified by the \a target constant and the parent + * \a pParent. + */ + ConsoleAppender(Layout *pLayout, + Target target, + QObject *pParent = 0); + + virtual ~ConsoleAppender(); + private: + ConsoleAppender(const ConsoleAppender &rOther); // Not implemented + ConsoleAppender &operator=(const ConsoleAppender &rOther); // Not implemented + + public: + // JAVA: bool follow() const; + QString target() const; + // JAVA: void setFollow(bool follow); + void setTarget(const QString &rTarget); + + /*! + * Sets the target to the value specified by the \a target constant. + */ + void setTarget(Target target); + + virtual void activateOptions(); + virtual void close(); + + protected: + void closeStream(); + + #ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream + * \a rDebug and returns the stream. + * + * + * %ConsoleAppender(name:"CA" filter:0x0 isactive:true isclosed:false + * layout:"PL" target:"STDERR" referenceCount:1 + * threshold:"WARN_SET") + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; + #endif // QT_NO_DEBUG_STREAM + + private: + volatile Target mTarget; + QTextStream *mpTextStream; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline void ConsoleAppender::setTarget(Target target) + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + mTarget = target; } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::ConsoleAppender, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_CONSOLEAPPENDER_H diff --git a/src/log4qt/log4qt/dailyrollingfileappender.cpp b/src/log4qt/log4qt/dailyrollingfileappender.cpp new file mode 100644 index 0000000..682f8d5 --- /dev/null +++ b/src/log4qt/log4qt/dailyrollingfileappender.cpp @@ -0,0 +1,457 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: dailyrollingfileappender.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/dailyrollingfileappender.h" + +#include +#include +#include +#include +#include +#include "log4qt/helpers/datetime.h" +#include "log4qt/layout.h" +#include "log4qt/loggingevent.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: DailyRollingFileAppender + **************************************************************************/ + + + DailyRollingFileAppender::DailyRollingFileAppender(QObject *pParent) : + FileAppender(pParent), + mDatePattern() + { + setDatePattern(DAILY_ROLLOVER); + } + + + DailyRollingFileAppender::DailyRollingFileAppender(Layout *pLayout, + const QString &rFileName, + const QString &rDatePattern, + QObject *pParent) : + FileAppender(pLayout, rFileName, pParent), + mDatePattern() + { + setDatePattern(rDatePattern); + } + + + DailyRollingFileAppender::~DailyRollingFileAppender() + { + close(); + } + + + void DailyRollingFileAppender::setDatePattern(DatePattern datePattern) + { + switch (datePattern) + { + case MINUTELY_ROLLOVER: + setDatePattern(QLatin1String("'.'yyyy-MM-dd-hh-mm")); + break; + case HOURLY_ROLLOVER: + setDatePattern(QLatin1String("'.'yyyy-MM-dd-hh")); + break; + case HALFDAILY_ROLLOVER: + setDatePattern(QLatin1String("'.'yyyy-MM-dd-a")); + break; + case DAILY_ROLLOVER: + setDatePattern(QLatin1String("'.'yyyy-MM-dd")); + break; + case WEEKLY_ROLLOVER: + setDatePattern(QLatin1String("'.'yyyy-ww")); + break; + case MONTHLY_ROLLOVER: + setDatePattern(QLatin1String("'.'yyyy-MM")); + break; + default: + Q_ASSERT_X(false, "DailyRollingFileAppender::setDatePattern()", "Invalid datePattern constant"); + setDatePattern(DAILY_ROLLOVER); + }; + } + + + void DailyRollingFileAppender::activateOptions() + { + QMutexLocker locker(&mObjectGuard); + + computeFrequency(); + if (!mActiveDatePattern.isEmpty()) + { + #ifdef UKUILOG4QT_EXTRA_ENABLE + QFileInfo fileInfo(file()); + if (!fileInfo.exists()) { + computeRollOverTime(); + } else { + computeRollOverTime(fileInfo.birthTime().isNull()?fileInfo.lastModified():fileInfo.birthTime()); + } + #else + computeRollOverTime(); + #endif + FileAppender::activateOptions(); + } + } + + + void DailyRollingFileAppender::append(const LoggingEvent &rEvent) + { + // Q_ASSERT_X(, "DailyRollingFileAppender::append()", "Lock must be held by caller") + #ifndef UKUILOG4QT_EXTRA_ENABLE + if (QDateTime::currentDateTime() > mRollOverTime) + rollOver(); + #endif + FileAppender::append(rEvent); + } + + void DailyRollingFileAppender::asyncAppend(const LoggingEvent &rEvent) + { + // Q_ASSERT_X(, "DailyRollingFileAppender::asyncAppend()", "Lock must be held by caller") + + if (QDateTime::currentDateTime() > mRollOverTime) + rollOver(); + FileAppender::asyncAppend(rEvent); + } + + + bool DailyRollingFileAppender::checkEntryConditions() const + { + // Q_ASSERT_X(, "DailyRollingFileAppender::checkEntryConditions()", "Lock must be held by caller") + + if (mActiveDatePattern.isEmpty()) + { + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of appender '%1' without having a valid date pattern set"), + APPENDER_USE_INVALID_PATTERN_ERROR); + e << name(); + logger()->error(e); + return false; + } + + return FileAppender::checkEntryConditions(); + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug DailyRollingFileAppender::debug(QDebug &rDebug) const + { + QString layout_name; + if (layout()) + layout_name = layout()->name(); + QString codec_name; + if (encoding()) + codec_name = QLatin1String(encoding()->name()); + + rDebug.nospace() << "DailyRollingFileAppender(" + << "name:" << name() << " " + << "activedatepattern:" << mActiveDatePattern << " " + << "appendfile:" << appendFile() << " " + << "bufferedio:" << bufferedIo() << " " + << "datepattern:" << datePattern() << " " + << "encoding:" << codec_name << " " + << "frequency:" << frequencyToString() << " " + << "file:" << file() << " " + << "filter:" << firstFilter() << " " + << "immediateflush:" << immediateFlush() << " " + << "isactive:" << isActive() << " " + << "isclosed:" << isClosed() << " " + << "layout:" << layout_name << " " + << "referencecount:" << referenceCount() << " " + << "rollovertime:" << mRollOverTime + << "threshold:" << threshold().toString() + << "writer:" << writer() + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + void DailyRollingFileAppender::computeFrequency() + { + // Q_ASSERT_X(, "DailyRollingFileAppender::computeFrequency()", "Lock must be held by caller") + + const DateTime start_time(QDate(1999, 1, 1), QTime(0, 0)); + const QString start_string = start_time.toString(mDatePattern); + mActiveDatePattern.clear(); + + if (start_string != static_cast(start_time.addSecs(60)).toString(mDatePattern)) + mFrequency = MINUTELY_ROLLOVER; + else if (start_string != static_cast(start_time.addSecs(60 * 60)).toString(mDatePattern)) + mFrequency = HOURLY_ROLLOVER; + else if (start_string != static_cast(start_time.addSecs(60 * 60 * 12)).toString(mDatePattern)) + mFrequency = HALFDAILY_ROLLOVER; + else if (start_string != static_cast(start_time.addDays(1)).toString(mDatePattern)) + mFrequency = DAILY_ROLLOVER; + else if (start_string != static_cast(start_time.addDays(7)).toString(mDatePattern)) + mFrequency = WEEKLY_ROLLOVER; + else if (start_string != static_cast(start_time.addMonths(1)).toString(mDatePattern)) + mFrequency = MONTHLY_ROLLOVER; + else + { + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("The pattern '%1' does not specify a frequency for appender '%2'"), + APPENDER_INVALID_PATTERN_ERROR); + e << mDatePattern << name(); + logger()->error(e); + return; + } + + mActiveDatePattern = mDatePattern; + logger()->trace("Frequency set to %2 using date pattern %1", + mActiveDatePattern, + frequencyToString()); + } + + void DailyRollingFileAppender::computeRollOverTime(QDateTime startTime) + { + // Q_ASSERT_X(, "DailyRollingFileAppender::computeRollOverTime()", "Lock must be held by caller") + Q_ASSERT_X(!mActiveDatePattern.isEmpty(), "DailyRollingFileAppender::computeRollOverTime()", "No active date pattern"); + + QDateTime now = startTime; + QDate now_date = now.date(); + QTime now_time = now.time(); + QDateTime start; + + switch (mFrequency) + { + case MINUTELY_ROLLOVER: + { + start = QDateTime(now_date, + QTime(now_time.hour(), + now_time.minute(), + 0, 0)); + mRollOverTime = start.addSecs(60); + } + break; + case HOURLY_ROLLOVER: + { + start = QDateTime(now_date, + QTime(now_time.hour(), + 0, 0, 0)); + mRollOverTime = start.addSecs(60*60); + } + break; + case HALFDAILY_ROLLOVER: + { + int hour = now_time.hour(); + if (hour >= 12) + hour = 12; + else + hour = 0; + start = QDateTime(now_date, + QTime(hour, 0, 0, 0)); + mRollOverTime = start.addSecs(60*60*12); + } + break; + case DAILY_ROLLOVER: + { + start = QDateTime(now_date, + QTime(0, 0, 0, 0)); + mRollOverTime = start.addDays(1); + } + break; + case WEEKLY_ROLLOVER: + { + // QT numbers the week days 1..7. The week starts on Monday. + // Change it to being numbered 0..6, starting with Sunday. + int day = now_date.dayOfWeek(); + if (day == Qt::Sunday) + day = 0; + start = QDateTime(now_date, + QTime(0, 0, 0, 0)).addDays(-1 * day); + mRollOverTime = start.addDays(7); + } + break; + case MONTHLY_ROLLOVER: + { + start = QDateTime(QDate(now_date.year(), + now_date.month(), + 1), + QTime(0, 0, 0, 0)); + mRollOverTime = start.addMonths(1); + } + break; + default: + Q_ASSERT_X(false, "DailyRollingFileAppender::computeInterval()", "Invalid datePattern constant"); + mRollOverTime = QDateTime::fromTime_t(0); + } + + mRollOverSuffix = static_cast(start).toString(mActiveDatePattern); + Q_ASSERT_X(static_cast(now).toString(mActiveDatePattern) == mRollOverSuffix, + "DailyRollingFileAppender::computeRollOverTime()", "File name changes within interval"); + Q_ASSERT_X(mRollOverSuffix != static_cast(mRollOverTime).toString(mActiveDatePattern), + "DailyRollingFileAppender::computeRollOverTime()", "File name does not change with rollover"); + + logger()->trace("Computing roll over time from %1: The interval start time is %2. The roll over time is %3", + now, + start, + mRollOverTime); + } + + void DailyRollingFileAppender::computeRollOverTime() + { + // Q_ASSERT_X(, "DailyRollingFileAppender::computeRollOverTime()", "Lock must be held by caller") + Q_ASSERT_X(!mActiveDatePattern.isEmpty(), "DailyRollingFileAppender::computeRollOverTime()", "No active date pattern"); + + QDateTime now = QDateTime::currentDateTime(); + QDate now_date = now.date(); + QTime now_time = now.time(); + QDateTime start; + + switch (mFrequency) + { + case MINUTELY_ROLLOVER: + { + start = QDateTime(now_date, + QTime(now_time.hour(), + now_time.minute(), + 0, 0)); + mRollOverTime = start.addSecs(60); + } + break; + case HOURLY_ROLLOVER: + { + start = QDateTime(now_date, + QTime(now_time.hour(), + 0, 0, 0)); + mRollOverTime = start.addSecs(60*60); + } + break; + case HALFDAILY_ROLLOVER: + { + int hour = now_time.hour(); + if (hour >= 12) + hour = 12; + else + hour = 0; + start = QDateTime(now_date, + QTime(hour, 0, 0, 0)); + mRollOverTime = start.addSecs(60*60*12); + } + break; + case DAILY_ROLLOVER: + { + start = QDateTime(now_date, + QTime(0, 0, 0, 0)); + mRollOverTime = start.addDays(1); + } + break; + case WEEKLY_ROLLOVER: + { + // QT numbers the week days 1..7. The week starts on Monday. + // Change it to being numbered 0..6, starting with Sunday. + int day = now_date.dayOfWeek(); + if (day == Qt::Sunday) + day = 0; + start = QDateTime(now_date, + QTime(0, 0, 0, 0)).addDays(-1 * day); + mRollOverTime = start.addDays(7); + } + break; + case MONTHLY_ROLLOVER: + { + start = QDateTime(QDate(now_date.year(), + now_date.month(), + 1), + QTime(0, 0, 0, 0)); + mRollOverTime = start.addMonths(1); + } + break; + default: + Q_ASSERT_X(false, "DailyRollingFileAppender::computeInterval()", "Invalid datePattern constant"); + mRollOverTime = QDateTime::fromTime_t(0); + } + + mRollOverSuffix = static_cast(start).toString(mActiveDatePattern); + Q_ASSERT_X(static_cast(now).toString(mActiveDatePattern) == mRollOverSuffix, + "DailyRollingFileAppender::computeRollOverTime()", "File name changes within interval"); + Q_ASSERT_X(mRollOverSuffix != static_cast(mRollOverTime).toString(mActiveDatePattern), + "DailyRollingFileAppender::computeRollOverTime()", "File name does not change with rollover"); + + logger()->trace("Computing roll over time from %1: The interval start time is %2. The roll over time is %3", + now, + start, + mRollOverTime); + } + + + QString DailyRollingFileAppender::frequencyToString() const + { + QMetaEnum meta_enum = metaObject()->enumerator(metaObject()->indexOfEnumerator("DatePattern")); + return QLatin1String(meta_enum.valueToKey(mFrequency)); + } + + + void DailyRollingFileAppender::rollOver() + { + // Q_ASSERT_X(, "DailyRollingFileAppender::rollOver()", "Lock must be held by caller") + Q_ASSERT_X(!mActiveDatePattern.isEmpty(), "DailyRollingFileAppender::rollOver()", "No active date pattern"); + + QString roll_over_suffix = mRollOverSuffix; + computeRollOverTime(); + if (roll_over_suffix == mRollOverSuffix) + return; + + closeFile(); + + QString target_file_name = file() + roll_over_suffix; + QFile f(target_file_name); + if (f.exists() && !removeFile(f)) + return; + f.setFileName(file()); + if (!renameFile(f, target_file_name)) + return; + openFile(); + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/dailyrollingfileappender.h b/src/log4qt/log4qt/dailyrollingfileappender.h new file mode 100644 index 0000000..3228c4f --- /dev/null +++ b/src/log4qt/log4qt/dailyrollingfileappender.h @@ -0,0 +1,199 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: dailyrollingfileappender.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_DAILYROLLINGFILEAPPENDER_H +#define LOG4QT_DAILYROLLINGFILEAPPENDER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/fileappender.h" +#include "ukui-logmacros.h" + +#include + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + /*! + * \brief The class DailyRollingFileAppender extends FileAppender so that the + * underlying file is rolled over at a specified frequency. + * + * \note All the functions declared in this class are thread-safe. + * + * \note The ownership and lifetime of objects of this class are managed. See + * \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT DailyRollingFileAppender : public FileAppender + { + Q_OBJECT + + /*! + * The property holds the date pattern used by the appender. + * + * The default is DAILY_ROLLOVER for rollover at midnight each day. + * + * \sa datePattern(), setDatePattern() + */ + Q_PROPERTY(QString datePattern READ datePattern WRITE setDatePattern) + + public: + /*! + * The enum DatePattern defines constants for date patterns. + * + * \sa setDatePattern(DatePattern) + */ + enum DatePattern + { + /*! The minutely date pattern string is "'.'yyyy-MM-dd-hh-mm". */ + MINUTELY_ROLLOVER = 0, + /*! The hourly date pattern string is "'.'yyyy-MM-dd-hh". */ + HOURLY_ROLLOVER, + /*! The half-daily date pattern string is "'.'yyyy-MM-dd-a". */ + HALFDAILY_ROLLOVER, + /*! The daily date pattern string is "'.'yyyy-MM-dd". */ + DAILY_ROLLOVER, + /*! The weekly date pattern string is "'.'yyyy-ww". */ + WEEKLY_ROLLOVER, + /*! The monthly date pattern string is "'.'yyyy-MM". */ + MONTHLY_ROLLOVER + }; + Q_ENUMS(DatePattern) + + DailyRollingFileAppender(QObject *pParent = 0); + DailyRollingFileAppender(Layout *pLayout, + const QString &rFileName, + const QString &rDatePattern, + QObject *pParent = 0); + virtual ~DailyRollingFileAppender(); + private: + DailyRollingFileAppender(const DailyRollingFileAppender &rOther); // Not implemented + DailyRollingFileAppender &operator=(const DailyRollingFileAppender &rOther); // Not implemented + + public: + QString datePattern() const; + + /*! + * Sets the datePattern to the value specified by the \a datePattern + * constant. + */ + void setDatePattern(DatePattern datePattern); + + void setDatePattern(const QString &rDatePattern); + + virtual void activateOptions(); + + protected: + virtual void append(const LoggingEvent &rEvent); + virtual void asyncAppend(const LoggingEvent &rEvent); + + /*! + * Tests if all entry conditions for using append() in this class are + * met. + * + * If a conditions is not met, an error is logged and the function + * returns false. Otherwise the result of + * FileAppender::checkEntryConditions() is returned. + * + * The checked conditions are: + * - A valid pattern has been set (APPENDER_USE_INVALID_PATTERN_ERROR) + * + * The function is called as part of the checkEntryConditions() chain + * started by AppenderSkeleton::doAppend(). + * + * \sa AppenderSkeleton::doAppend(), + * AppenderSkeleton::checkEntryConditions() + */ + virtual bool checkEntryConditions() const; + + protected: +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream + * \a rDebug and returns the stream. + * + * + * %DailyRollingFileAppender(name:"DRFA" activedatepattern:"'.'yyyy-MM-dd-hh-mm" + * appendfile:false bufferedio:true + * datepattern:"'.'yyyy-MM-dd-hh-mm" + * encoding:"" frequency:"MINUTELY_ROLLOVER" + * file:"/log.txt" filter:0x0 immediateflush:true + * isactive:true isclosed:false layout:"TTCC" + * referencecount:1 + * rollovertime:QDateTime("Mon Oct 22 05:23:00 2007") + * threshold: "NULL" writer: 0x0 ) + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; +#endif // QT_NO_DEBUG_STREAM + + private: + void computeFrequency(); + void computeRollOverTime(); + void computeRollOverTime(QDateTime startTime); + QString frequencyToString() const; + void rollOver(); + + private: + QString mDatePattern; + DatePattern mFrequency; + QString mActiveDatePattern; + QDateTime mRollOverTime; + QString mRollOverSuffix; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline QString DailyRollingFileAppender::datePattern() const + { QMutexLocker locker(&mObjectGuard); + return mDatePattern; } + + inline void DailyRollingFileAppender::setDatePattern(const QString &rDatePattern) + { QMutexLocker locker(&mObjectGuard); + mDatePattern = rDatePattern; } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::DailyRollingFileAppender, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_DAILYROLLINGFILEAPPENDER_H diff --git a/src/log4qt/log4qt/fileappender.cpp b/src/log4qt/log4qt/fileappender.cpp new file mode 100644 index 0000000..77db664 --- /dev/null +++ b/src/log4qt/log4qt/fileappender.cpp @@ -0,0 +1,310 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: fileappender.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/fileappender.h" + +#include +#include +#include +#include +#include +#include +#include "log4qt/layout.h" +#include "log4qt/loggingevent.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: FileAppender + **************************************************************************/ + + + FileAppender::FileAppender(QObject *pParent) : + WriterAppender(pParent), + mAppendFile(false), + mBufferedIo(true), + mFileName(), + mpFile(0), + mpTextStream(0) + { + } + + + FileAppender::FileAppender(Layout *pLayout, + const QString &rFileName, + QObject *pParent) : + WriterAppender(pLayout, pParent), + mAppendFile(false), + mBufferedIo(true), + mFileName(rFileName), + mpFile(0), + mpTextStream(0) + { + } + + + FileAppender::FileAppender(Layout *pLayout, + const QString &rFileName, + bool append, + QObject *pParent) : + WriterAppender(pLayout, pParent), + mAppendFile(append), + mBufferedIo(true), + mFileName(rFileName), + mpFile(0), + mpTextStream(0) + { + } + + + FileAppender::FileAppender(Layout *pLayout, + const QString &rFileName, + bool append, + bool buffered, + QObject *pParent) : + WriterAppender(pLayout, pParent), + mAppendFile(append), + mBufferedIo(buffered), + mFileName(rFileName), + mpFile(0), + mpTextStream(0) + { + } + + + FileAppender::~FileAppender() + { + close(); + } + + + void FileAppender::activateOptions() + { + QMutexLocker locker(&mObjectGuard); + + if (mFileName.isEmpty()) + { + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Activation of Appender '%1' that requires file and has no file set"), + APPENDER_ACTIVATE_MISSING_FILE_ERROR); + e << name(); + logger()->error(e); + return; + } + closeFile(); + openFile(); + WriterAppender::activateOptions(); + } + + + void FileAppender::close() + { + QMutexLocker locker(&mObjectGuard); + + if (isClosed()) + return; + + WriterAppender::close(); + closeFile(); + } + + + bool FileAppender::checkEntryConditions() const + { + // Q_ASSERT_X(, "FileAppender::checkEntryConditions()", "Lock must be held by caller") + + if (!mpFile || !mpTextStream) + { + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of appender '%1' without open file"), + APPENDER_NO_OPEN_FILE_ERROR); + e << name(); + logger()->error(e); + return false; + } + + return WriterAppender::checkEntryConditions(); + } + + + void FileAppender::closeFile() + { + // Q_ASSERT_X(, "FileAppender::closeFile()", "Lock must be held by caller") + + if (mpFile) + logger()->debug("Closing file '%1' for appender '%2'", mpFile->fileName(), name()); + + setWriter(0); + delete mpTextStream; + mpTextStream = 0; + delete mpFile; + mpFile = 0; + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug FileAppender::debug(QDebug &rDebug) const + { + QString layout_name; + if (layout()) + layout_name = layout()->name(); + QString codec_name; + if (encoding()) + codec_name = QLatin1String(encoding()->name()); + + rDebug.nospace() << "FileAppender(" + << "name:" << name() << " " + << "appendfile:" << appendFile() << " " + << "bufferedio:" << bufferedIo() << " " + << "encoding:" << codec_name << " " + << "file:" << file() << " " + << "filter:" << firstFilter() << " " + << "immediateflush:" << immediateFlush() << " " + << "isactive:" << isActive() << " " + << "isclosed:" << isClosed() << " " + << "layout:" << layout_name << " " + << "referencecount:" << referenceCount() << " " + << "threshold:" << threshold().toString() << " " + << "writer:" << writer() + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + bool FileAppender::handleIoErrors() const + { + // Q_ASSERT_X(, "FileAppender::handleIoErrors()", "Lock must be held by caller") + + if (mpFile->error() == QFile::NoError) + return false; + + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to write to file '%1' for appender '%2'"), + APPENDER_WRITING_FILE_ERROR); + e << mFileName << name(); + e.addCausingError(LogError(mpFile->errorString(), mpFile->error())); + logger()->error(e); + return true; + } + + + void FileAppender::openFile() + { + Q_ASSERT_X(mpFile == 0 && mpTextStream == 0, "FileAppender::openFile()", "Opening file without closing previous file"); + + QFileInfo file_info(mFileName); + QDir parent_dir = file_info.dir(); + if (!parent_dir.exists()) + { + logger()->trace("Creating missing parent directory for file %1", mFileName); + QString name = parent_dir.dirName(); + parent_dir.cdUp(); + parent_dir.mkdir(name); + } + + + mpFile = new QFile(mFileName); + QFile::OpenMode mode = QIODevice::WriteOnly | QIODevice::Text; + if (mAppendFile) + mode |= QIODevice::Append; + else + mode |= QIODevice::Truncate; + if (!mBufferedIo) + mode |= QIODevice::Unbuffered; + if (!mpFile->open(mode)) + { + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to open file '%1' for appender '%2'"), + APPENDER_OPENING_FILE_ERROR); + e << mFileName << name(); + e.addCausingError(LogError(mpFile->errorString(), mpFile->error())); + logger()->error(e); + return; + } + mpTextStream = new QTextStream(mpFile); + setWriter(mpTextStream); + logger()->debug("Opened file '%1' for appender '%2'", mpFile->fileName(), name()); + } + + + bool FileAppender::removeFile(QFile &rFile) const + { + if (rFile.remove()) + return true; + + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to remove file '%1' for appender '%2'"), + APPENDER_REMOVE_FILE_ERROR); + e << rFile.fileName() << name(); + e.addCausingError(LogError(rFile.errorString(), rFile.error())); + logger()->error(e); + return false; + } + + + bool FileAppender::renameFile(QFile &rFile, + const QString &rFileName) const + { + logger()->debug("Renaming file '%1' to '%2'", rFile.fileName(), rFileName); + if (!rFileName.compare(rFile.fileName())) + return true; + + if (rFile.rename(rFileName)) + return true; + + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to rename file '%1' to '%2' for appender '%3'"), + APPENDER_RENAMING_FILE_ERROR); + e << rFile.fileName() << rFileName << name(); + e.addCausingError(LogError(rFile.errorString(), rFile.error())); + logger()->error(e); + return false; + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/fileappender.h b/src/log4qt/log4qt/fileappender.h new file mode 100644 index 0000000..29181ab --- /dev/null +++ b/src/log4qt/log4qt/fileappender.h @@ -0,0 +1,233 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: fileappender.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_FILEAPPENDER_H +#define LOG4QT_FILEAPPENDER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/writerappender.h" +#include "ukui-logmacros.h" + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +class QFile; +class QTextStream; + +namespace Log4Qt +{ + + /*! + * \brief The class FileAppender appends log events to a file. + * + * \note All the functions declared in this class are thread-safe. + * + * \note The ownership and lifetime of objects of this class are managed. See + * \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT FileAppender : public WriterAppender + { + Q_OBJECT + + /*! + * The property holds, if the output is appended to the file. + * + * The default is false for not appending. + * + * \sa appendFile(), setAppendFile() + */ + Q_PROPERTY(bool appendFile READ appendFile WRITE setAppendFile) + + /*! + * The property holds, if the output is buffered. + * + * The default is true for buffering. + * + * \sa bufferedIo(), setBufferedIo() + */ + Q_PROPERTY(bool bufferedIo READ bufferedIo WRITE setBufferedIo) + + /*! + * The property holds the name of the file. + * + * \sa file(), setFile() + */ + Q_PROPERTY(QString file READ file WRITE setFile) + + public: + FileAppender(QObject *pParent = 0); + FileAppender(Layout *pLayout, + const QString &rFileName, + QObject *pParent = 0); + FileAppender(Layout *pLayout, + const QString &rFileName, + bool append, + QObject *pParent = 0); + FileAppender(Layout *pLayout, + const QString &rFileName, + bool append, + bool buffered, + QObject *pParent = 0); + virtual ~FileAppender(); + private: + FileAppender(const FileAppender &rOther); // Not implemented + FileAppender &operator=(const FileAppender &rOther); // Not implemented + + public: + bool appendFile() const; + QString file() const; + bool bufferedIo() const; + // JAVA: int bufferSize() const; + void setAppendFile(bool append); + void setBufferedIo(bool buffered); + // JAVA: void setBufferSize(int bufferSize); + void setFile(const QString &rFileName); + + virtual void activateOptions(); + virtual void close(); + + protected: + /*! + * Tests if all entry conditions for using append() in this class are met. + * + * If a conditions is not met, an error is logged and the function returns + * false. Otherwise the result of WriterAppender::checkEntryConditions() + * is returned. + * + * The checked conditions are: + * - That a file is set and open (APPENDER_NO_OPEN_FILE_ERROR) + * + * The function is called as part of the checkEntryConditions() chain + * started by AppenderSkeleton::doAppend(). + * + * \sa AppenderSkeleton::doAppend(), AppenderSkeleton::checkEntryConditions() + */ + virtual bool checkEntryConditions() const; + + void closeFile(); + +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream \a rDebug + * and returns the stream. + * + * + * %FileAppender(name:"FA" appendfile:false bufferedio:true encoding:"" + * file:"/log.txt" filter: 0x0 immediateflush:true isactive:false + * isclosed:false layout:"TTCC" referencecount:2 + * threshold:"NULL" writer:0x0) + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; +#endif // QT_NO_DEBUG_STREAM + + /*! + * Checks for file I/O errrors. If an error is found it is logged and the + * function returns true. Otherwise false is returned. + */ + virtual bool handleIoErrors() const; + + /*! + * Opens the file for the appender based on the specified file name and + * mode. A text stream is created and passed on to the super class + * WriterAppender. + * + * If the parent directory of the specified file does not exists, + * it is created. + */ + void openFile(); + + /*! + * Removes the file \a rFile. If the operation is successful, true is + * returned. Otherwise an APPENDER_REMOVE_FILE_ERROR error is logged + * and false is returned. + */ + bool removeFile(QFile &rFile) const; + + /*! + * Renames the file \a rFile to \a rFileName. If the operation is + * successful, true is returned. Otherwise an + * APPENDER_RENAMING_FILE_ERROR error is logged and false is returned. + */ + bool renameFile(QFile &rFile, + const QString &rFileName) const; + + // JAVA: void setQWForFiles(Writer writer); + + private: + volatile bool mAppendFile; + volatile bool mBufferedIo; + QString mFileName; + QFile *mpFile; + QTextStream *mpTextStream; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline bool FileAppender::appendFile() const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mAppendFile; } + + inline QString FileAppender::file() const + { QMutexLocker locker(&mObjectGuard); + return mFileName; } + + inline bool FileAppender::bufferedIo() const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mBufferedIo; } + + inline void FileAppender::setAppendFile(bool append) + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + mAppendFile = append; } + + inline void FileAppender::setBufferedIo(bool buffered) + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + mBufferedIo = buffered; } + + inline void FileAppender::setFile(const QString &rFileName) + { QMutexLocker locker(&mObjectGuard); + mFileName = rFileName; } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::FileAppender, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_FILEAPPENDER_H diff --git a/src/log4qt/log4qt/helpers/asyncdispatcher.cpp b/src/log4qt/log4qt/helpers/asyncdispatcher.cpp new file mode 100644 index 0000000..b0b3e83 --- /dev/null +++ b/src/log4qt/log4qt/helpers/asyncdispatcher.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 + +namespace Log4Qt +{ + +AsyncDispatcher::AsyncDispatcher(QObject *parent) : QObject(parent) + , mAsyncAppender(nullptr) +{} + +void AsyncDispatcher::customEvent(QEvent *event) +{ + if (event->type() == LoggingEvent::eventId) + { + auto *logEvent = static_cast(event); + if (mAsyncAppender != nullptr) + mAsyncAppender->asyncAppend(*logEvent); + } + QObject::customEvent(event); +} + +void AsyncDispatcher::setAsyncAppender(AppenderSkeleton *asyncAppender) +{ + mAsyncAppender = asyncAppender; +} + +} // namespace Log4Qt \ No newline at end of file diff --git a/src/log4qt/log4qt/helpers/asyncdispatcher.h b/src/log4qt/log4qt/helpers/asyncdispatcher.h new file mode 100644 index 0000000..91c30ce --- /dev/null +++ b/src/log4qt/log4qt/helpers/asyncdispatcher.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include "ukui-logmacros.h" + +namespace Log4Qt +{ + +class AppenderSkeleton; + +/*! + * \brief The class AsyncDispatcher does the actual logging to the attached appanders. + * + * The Dispatcher is the worker object which class the attached apperders in the + * the context of the AsyncDispatcherThread. + * + * \note All the functions declared in this class are thread-safe. + */ +class LIBUKUILOG4QT_EXPORT AsyncDispatcher : public QObject +{ + Q_OBJECT +public: + explicit AsyncDispatcher(QObject *parent = nullptr); + + void setAsyncAppender(AppenderSkeleton *asyncAppender); + +protected: + void customEvent(QEvent *event) override; + +private: + AppenderSkeleton *mAsyncAppender; +}; + +} // namespace Log4Qt + +#endif // LOG4QT_ASYNCDISPATCHER_H diff --git a/src/log4qt/log4qt/helpers/classlogger.cpp b/src/log4qt/log4qt/helpers/classlogger.cpp new file mode 100644 index 0000000..50b6c7f --- /dev/null +++ b/src/log4qt/log4qt/helpers/classlogger.cpp @@ -0,0 +1,100 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: classlogger.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * changes: Sep 2008, Martin Heinrich: + * - Replaced usage of q_atomic_test_and_set_ptr with + * QAtomicPointer + * + * + * Copyright 2007 - 2008 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/helpers/classlogger.h" + +#include +#include "log4qt/logmanager.h" + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: ClassLogger + **************************************************************************/ + + + ClassLogger::ClassLogger() : + mpLogger(0) + { + } + + + Logger *ClassLogger::logger(const QObject *pObject) + { + Q_ASSERT_X(pObject, "ClassLogger::logger()", "pObject must not be null"); +#if QT_VERSION < QT_VERSION_CHECK(4, 4, 0) + if (!mpLogger) + q_atomic_test_and_set_ptr(&mpLogger, + 0, + LogManager::logger(QLatin1String(pObject->metaObject()->className()))); + return const_cast(mpLogger); +#elif QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + if (!static_cast(mpLogger)) + mpLogger.testAndSetOrdered(0, + LogManager::logger(QLatin1String(pObject->metaObject()->className()))); + return const_cast(static_cast(mpLogger)); +#else + if (!static_cast(mpLogger.loadAcquire())) + mpLogger.testAndSetOrdered(0, + LogManager::logger(QLatin1String(pObject->metaObject()->className()))); + return const_cast(static_cast(mpLogger.loadAcquire())); +#endif + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/helpers/classlogger.h b/src/log4qt/log4qt/helpers/classlogger.h new file mode 100644 index 0000000..9e10399 --- /dev/null +++ b/src/log4qt/log4qt/helpers/classlogger.h @@ -0,0 +1,117 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: classlogger.h + * created: September 2007 + * author: Martin Heinrich + * + * + * changes: Sep 2008, Martin Heinrich: + * - Replaced usage of q_atomic_test_and_set_ptr with + * QAtomicPointer + * + * + * Copyright 2007 - 2008 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_CLASSLOGGER_H +#define LOG4QT_CLASSLOGGER_H + +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#if QT_VERSION >= QT_VERSION_CHECK(4, 4, 0) +# include +# ifndef Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE +# warning "QAtomicPointer test and set is not native. The class Log4Qt::ClassLogger is not thread-safe." +# endif +#endif + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + class Logger; + + /*! + * \brief The class ClassLogger provides logging for a QObject derived + * class. + * + * The class ClassLogger provides a logger for a specified QObject derived + * object. It is used by \ref LOG4QT_DECLARE_QCLASS_LOGGER to implement the + * member functions provided by the macro. + * + * \note All the functions declared in this class are thread-safe. + * + * \sa LOG4QT_DECLARE_QCLASS_LOGGER + */ + class LIBUKUILOG4QT_EXPORT ClassLogger + { + public: + /*! + * Creates a ClassLogger object. + */ + ClassLogger(); + // ~ClassLogger(); // Use compiler default + // ClassLogger(const ClassLogger &rOther); // Use compiler default + // ClassLogger &operator=(const ClassLogger &rOther); // Use compiler default + + /*! + * Returns a pointer to a Logger named after the class of the object + * \a pObject. + * + * On the first invocation the Logger is requested by a call to + * LogManager::logger(const char *pName). The pointer is stored to be + * returned on subsequent invocations. + * + * \sa LogManager::logger(const char *pName) + */ + Logger *logger(const QObject *pObject); + + private: +#if QT_VERSION < QT_VERSION_CHECK(4, 4, 0) + volatile Logger *mpLogger; +#else + mutable QAtomicPointer mpLogger; +#endif + }; + + + /****************************************************************************** + * Operators, Helper + ******************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEinfo(Log4Qt::ClassLogger, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_CLASSLOGGER_H diff --git a/src/log4qt/log4qt/helpers/configuratorhelper.cpp b/src/log4qt/log4qt/helpers/configuratorhelper.cpp new file mode 100644 index 0000000..3b34f40 --- /dev/null +++ b/src/log4qt/log4qt/helpers/configuratorhelper.cpp @@ -0,0 +1,136 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: configuratorhelper.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/helpers/configuratorhelper.h" + +#include +#include +#include "log4qt/helpers/initialisationhelper.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: ConfiguratorHelper + **************************************************************************/ + + + ConfiguratorHelper::ConfiguratorHelper() : + mObjectGuard(), + mConfigurationFile(), + mpConfigureFunc(0), + mpConfigurationFileWatch(0), + mConfigureError() + { + } + + + ConfiguratorHelper::~ConfiguratorHelper() + { + delete mpConfigurationFileWatch; + } + + + LOG4QT_IMPLEMENT_INSTANCE(ConfiguratorHelper) + + + void ConfiguratorHelper::doConfigurationFileChanged(const QString &rFileName) + { + QMutexLocker locker(&mObjectGuard); + + if (!mpConfigureFunc) + return; + mpConfigureFunc(rFileName); + // Shall we hold the lock while emitting the signal? + emit configurationFileChanged(rFileName, mConfigureError.count() > 0); + } + + + + void ConfiguratorHelper::doSetConfigurationFile(const QString &rFileName, + ConfigureFunc pConfigureFunc) + { + QMutexLocker locker(&mObjectGuard); + + mConfigurationFile.clear(); + mpConfigureFunc = 0; + delete mpConfigurationFileWatch; + if (rFileName.isEmpty()) + return; + + mConfigurationFile = rFileName; + mpConfigureFunc = pConfigureFunc; + mpConfigurationFileWatch = new QFileSystemWatcher(); + mpConfigurationFileWatch->addPath(rFileName); + connect(mpConfigurationFileWatch, + SIGNAL(fileChanged(const QString &)), + SLOT(configurationFileChanged(const QString &))); + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, + const ConfiguratorHelper &rConfiguratorHelper) + { + debug.nospace() << "ConfiguratorHelper(" + << "configurationfile:" << ConfiguratorHelper::configurationFile() + << "configurefunc:" << rConfiguratorHelper.mpConfigureFunc + << "filesystemwatcher:" << rConfiguratorHelper.mpConfigurationFileWatch + << ")"; + return debug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + +} // namespace Log4Qt + diff --git a/src/log4qt/log4qt/helpers/configuratorhelper.h b/src/log4qt/log4qt/helpers/configuratorhelper.h new file mode 100644 index 0000000..fd55252 --- /dev/null +++ b/src/log4qt/log4qt/helpers/configuratorhelper.h @@ -0,0 +1,211 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: configuratorhelper.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_HELPERS_CONFIGURATORHELPER_H +#define LOG4QT_HELPERS_CONFIGURATORHELPER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include + +#include +#include +#include "log4qt/loggingevent.h" +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +class QFileSystemWatcher; + + +namespace Log4Qt +{ + + /*! + * \brief The class ConfiguratorHelper provides a confiuration file watch + * and last error for configurator classes. + * + * A configuration file can be set using setConfigurationFile(). The file + * is watched for changes. If a change occurs the configuration is reloaded + * and the ConfigurationFileChanged() signal is emitted. Error information + * for the last call to a configure function or the last configuration file + * change can be accessed using configureError(). + * + * \note All the functions declared in this class are thread-safe. + */ + class LIBUKUILOG4QT_EXPORT ConfiguratorHelper : public QObject + { + Q_OBJECT + + public: + /*! + * Prototype for a configure callback function. The function is called + * when then configuration file is changed and takes the + * configuration file as a parameter. + * + * \sa setConfigurationFile(), + * PropertyConfigurator::configure(const QString &) + */ + typedef bool (*ConfigureFunc)(const QString &rFileName); + + private: + ConfiguratorHelper(); + ConfiguratorHelper(const ConfiguratorHelper &rOther); // Not implemented + virtual ~ConfiguratorHelper(); + ConfiguratorHelper &operator=(const ConfiguratorHelper &rOther); // Not implemented + + public: + + /*! + * Returns the error information for the last configuration operation + * that took place. The configuration operation could be the result of + * a call to one of the configure methods or through a change + * to the configuration file. + * + * \sa setConfigureError(), PropertyConfigurator::configure(), + * setConfigurationFile() + */ + static QList configureError(); + + /*! + * Returns the current configuration file. + * + * \sa setConfigurationFile() + */ + static QString configurationFile(); + + /*! + * Returns the ConfiguratorHelper instance. + */ + static ConfiguratorHelper *instance(); + + /*! + * Sets the configuration error information for the last configuration + * operation. + * + * \sa configureError() + */ + static void setConfigureError(const QList &rConfigureError); + + /*! + * Sets the configuration file to \a rFileName. The file is watched for + * changes. On a file change the function \a pConfigureFunc will be called + * and the signal configurationFileChange() will be emitted. + * + * Setting the configuration file to an empty string stops the file watch. + * + * \sa configurationFile(), PropertyConfigurator::configureAndWatch(), + * configureError() + */ + static void setConfigurationFile(const QString &rFileName = QString(), + ConfigureFunc pConfigureFunc = 0); + + signals: + /*! + * The signal is emitted after a change to the file \a rFileName + * was processed. If an error occured during the configuration, the + * flag \a error will be true and error information is available + * over configureError(). + */ + void configurationFileChanged(const QString &rFileName, + bool error); + + private slots: + void doConfigurationFileChanged(const QString &rFileName); + + private: + void doSetConfigurationFile(const QString &rFileName, + ConfigureFunc pConfigureFunc); + + private: + mutable QMutex mObjectGuard; + QString mConfigurationFile; + ConfigureFunc mpConfigureFunc; + QFileSystemWatcher *mpConfigurationFileWatch; + QList mConfigureError; + +#ifndef QT_NO_DEBUG_STREAM + // Needs to be friend to access details + friend QDebug operator<<(QDebug debug, + const ConfiguratorHelper &rConfiguratorHelper); +#endif // QT_NO_DEBUG_STREAM + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + +#ifndef QT_NO_DEBUG_STREAM + /*! + * \relates ConfiguratorHelper + * + * Writes all object member variables to the given debug stream \a rDebug and + * returns the stream. + * + * + * %ConfiguratorHelper(configurationfile: "" configurefunc: false + * filesystemwatcher: QObject(0x0) ) + * + * \sa QDebug, ConfiguratorHelper::logManager() + */ + QDebug operator<<(QDebug debug, + const ConfiguratorHelper &rConfiguratorHelper); +#endif // QT_NO_DEBUG_STREAM + + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline QList ConfiguratorHelper::configureError() + { QMutexLocker locker(&instance()->mObjectGuard); + return instance()->mConfigureError; } + + inline QString ConfiguratorHelper::configurationFile() + { QMutexLocker locker(&instance()->mObjectGuard); + return instance()->mConfigurationFile; } + + inline void ConfiguratorHelper::setConfigureError(const QList &rConfigureError) + { QMutexLocker locker(&instance()->mObjectGuard); + instance()->mConfigureError = rConfigureError; } + + inline void ConfiguratorHelper::setConfigurationFile(const QString &rFileName, + ConfigureFunc pConfigureFunc) + { instance()->doSetConfigurationFile(rFileName, pConfigureFunc); } + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::ConfiguratorHelper, Q_COMPLEX_TYPE); // use default + + +#endif // LOG4QT_HELPERS_CONFIGURATORHELPER_H diff --git a/src/log4qt/log4qt/helpers/datetime.cpp b/src/log4qt/log4qt/helpers/datetime.cpp new file mode 100644 index 0000000..1fb7d87 --- /dev/null +++ b/src/log4qt/log4qt/helpers/datetime.cpp @@ -0,0 +1,326 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: datetime.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/helpers/datetime.h" + +#include +#include "log4qt/helpers/initialisationhelper.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + *Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: DateTime + **************************************************************************/ + + + QString DateTime::toString(const QString &rFormat) const + { + QString format(rFormat); + + if (format.isEmpty()) + return QString(); + if (!isValid()) + return QString(); + if (format == QLatin1String("NONE")) + return QString(); + + if (format == QLatin1String("TIME_RELATIVE")) + return QString::number(toMilliSeconds() - InitialisationHelper::startTime()); + + if (format == QLatin1String("ISO8601")) + format = QLatin1String("yyyy-MM-dd hh:mm:ss.zzz"); + if (format == QLatin1String("TIME_ABSOLUTE")) + format = QLatin1String("HH:mm:ss.zzz"); + if (format == QLatin1String("DATE")) + format = QLatin1String("dd MMM YYYY HH:mm:ss.zzzz"); + + return formatDateTime(format); + } + + + QString DateTime::formatDateTime(const QString &rFormat) const + { + if (rFormat.isEmpty()) + return QString(); + if (!isValid()) + return QString(); + + const QLatin1Char null('0'); + const QLatin1Char quote('\''); + const QString tokens = QLatin1String("\'dMyhHmszAPapw"); + const bool am_pm = hasAMPM(rFormat); + + QString result; + QString token; + QChar expected = null; + + QChar c; + int i; + for (i = 0; i < rFormat.length(); i++) + { + c = rFormat.at(i); + + // Handle literal text + if (expected == quote) + { + if (c == quote) + { + Q_ASSERT_X(i > 0, "DateTime::toString()", "Found quote with status quote at i = 0"); + if (i > 0 && rFormat.at(i - 1) == quote) + // Second of two quotes + result += quote; + expected = null; + } + else + // Next literal character + result += c; + } + else if (c == expected) + { + // Extend token + token += c; + } + else + { + // Close last token + result += formatToken(token, am_pm); + token.clear(); + expected = null; + + // Test for valid character + if (tokens.indexOf(c) >= 0) + { + if (c == QLatin1Char('a')) + expected = QLatin1Char('p'); + else if (c == QLatin1Char('A')) + expected = QLatin1Char('P'); + else if (c.toLower() == QLatin1Char('p')) + expected = null; + else + expected = c; + if (c != quote) + token += c; + } else + result += c; + } + } + + result += formatToken(token, am_pm); + return result; + } + + + QString DateTime::formatToken(const QString &rToken, bool am_pm) const + { + if (rToken.isEmpty()) + return QString(); + + const QChar c = rToken.at(0); + QString result; + int used = 0; + + // Qt data format strings + if (rToken.startsWith(QLatin1String("dddd"))) + { + result = QDate::longDayName(date().dayOfWeek()); + used = 4; + } + else if (rToken.startsWith(QLatin1String("ddd"))) + { + result = QDate::shortDayName(date().dayOfWeek()); + used = 3; + } + else if (rToken.startsWith(QLatin1String("dd"))) + { + result = QString::number(date().day()).rightJustified(2, QLatin1Char('0'), true); + used = 2; + } + else if (c == QLatin1Char('d')) + { + result = QString::number(date().day()); + used = 1; + } + else if (rToken.startsWith(QLatin1String("MMMM"))) + { + result = QDate::longMonthName(date().month()); + used = 4; + } + else if (rToken.startsWith(QLatin1String("MMM"))) + { + result = QDate::shortMonthName(date().month()); + used = 3; + } + else if (rToken.startsWith(QLatin1String("MM"))) + { + result = QString::number(date().month()).rightJustified(2, QLatin1Char('0'), true); + used = 2; + } + else if (c == QLatin1Char('M')) + { + result = QString::number(date().month()); + used = 1; + } + else if (rToken.startsWith(QLatin1String("yyyy"))) + { + result = QString::number(date().year()); + used = 4; + } + else if (rToken.startsWith(QLatin1String("yy"))) + { + result = QString::number(date().year() % 100).rightJustified(2, QLatin1Char('0'), true); + used = 2; + } + + // Qt time format strings + else if (rToken.startsWith(QLatin1String("hh")) || rToken.startsWith(QLatin1String("HH"))) + { + int hour = time().hour(); + if (am_pm && c == QLatin1Char('h') && hour > 12) + hour -= 12; + result = QString::number(hour).rightJustified(2, QLatin1Char('0'), true); + used = 2; + } + else if (c == QLatin1Char('h') || c == QLatin1Char('H')) + { + int hour = time().hour(); + if (am_pm && c == QLatin1Char('h') && hour > 12) + hour -= 12; + result = QString::number(hour); + used = 2; + } + else if (rToken.startsWith(QLatin1String("mm"))) + { + result = QString::number(time().minute()).rightJustified(2, QLatin1Char('0'), true); + used = 2; + } + else if (c == (QLatin1Char('m'))) + { + result = QString::number(time().minute()); + used = 1; + } + else if (rToken.startsWith(QLatin1String("ss"))) + { + result = QString::number(time().second()).rightJustified(2, QLatin1Char('0'), true); + used = 2; + } + else if (c == QLatin1Char('s')) + { + result = QString::number(time().second()); + used = 1; + } + else if (rToken.startsWith(QLatin1String("zzz"))) + { + result = QString::number(time().msec()).rightJustified(3, QLatin1Char('0'), true); + used = 3; + } + else if (c == QLatin1Char('z')) + { + result = QString::number(time().msec()); + used = 1; + } + else if (c.toLower() == QLatin1Char('a')) + { + bool is_lower = c == QLatin1Char('a'); + if (time().hour() < 12) + result = QLatin1String("AM"); + else + result = QLatin1String("PM"); + if (is_lower) + result = result.toLower(); + if (rToken.size() > 1 && + ((is_lower && rToken.at(1) == QLatin1Char('p')) || + (!is_lower && rToken.at(1) == QLatin1Char('P'))) + ) + used = 2; + else + used = 1; + } + + // Extension for week number + else if (rToken.startsWith(QLatin1String("ww"))) + { + result = QString::number(date().weekNumber()).rightJustified(2, QLatin1Char('0'), true); + used = 2; + } + else if (c == QLatin1Char('w')) + { + result = QString::number(date().weekNumber()); + used = 1; + } + + if (used) + return result + formatToken(rToken.mid(used), am_pm); + else + return result; + } + + + bool DateTime::hasAMPM(const QString &rToken) + { + bool in_literal = false; + QChar c; + int i; + for (i = 0; i < rToken.length(); i++) + { + c = rToken.at(i); + if (c == QLatin1Char('\'')) + in_literal = !in_literal; + else if (!in_literal && c.toLower() == QLatin1Char('a')) + return true; + } + return false; + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/helpers/datetime.h b/src/log4qt/log4qt/helpers/datetime.h new file mode 100644 index 0000000..e9c79ce --- /dev/null +++ b/src/log4qt/log4qt/helpers/datetime.h @@ -0,0 +1,213 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: datetime.h + * created: September 2007 + * author: Martin Heinrich + * + * + * changes: Sep 2008, Martin Heinrich: + * - Resolved compilation problem with Microsoft Visual Studio 2005 + * + * + * Copyright 2007 - 2008 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_HELPERS_DATETIME_H +#define LOG4QT_HELPERS_DATETIME_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + + +namespace Log4Qt +{ + + /*! + * \brief The class DateTime provides extended functionality for QDateTime. + * + * The class DateTime implements additional formatting options for + * toString() and provides conversion functions from and to milliseconds. + */ + class LIBUKUILOG4QT_EXPORT DateTime : public QDateTime + { + public: + /*! + * Constructs a null date time. + * + * \sa QDateTime::QDateTime() + */ + DateTime(); + + // DateTime(const DateTime &rOther); // Use compiler default + + /*! + * Constructs a copy of another QDateTime. + * + * \sa QDateTime::QDateTime(const QDateTime &rOther) + */ + DateTime(const QDateTime &rOther); + + /*! + * Constructs a datetime with the given \a rDate and \a rTime, using + * the time specification defined by \a timeSpec. + * + * \sa QDateTime::QDateTime(const QDate &rDate, const QTime &rTime, + * Qt::TimeSpec timeSpec = Qt::LocalTime) + */ + DateTime(const QDate &rDate, + const QTime &rTime, + Qt::TimeSpec timeSpec = Qt::LocalTime); + + // virtual ~DateTime(); // Use compiler default + + /*! + * Assigns \a rOther to this DateTime and returns a reference to it. + */ + DateTime &operator=(const DateTime &rOther); + + /*! + * Returns the datetime as the number of milliseconds that have passed + * since 1970-01-01T00:00:00,000, Coordinated Universal Time (Qt::UTC). + * + * \sa QDateTime::toTime_t() + */ + qint64 toMilliSeconds() const; + + /*! + * Returns the datetime as a string. The \a rFormat parameter + * determines the format of the result string. + * + * In addition to the expressions of QDateTime::toString(const QString + * &rFormat) the following expression can be used. + * + * + * + * + * + * + * + * + * + * + * + * + *
Expression Output
w the week of the year as number without a leading zero (1 to 53)
ww the week of the year as number with a leading zero (01 to 53)
+ * + * Alternatively the \a rFormat parameter can specify one of the + * following strings. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
String Format
TIME_ABSOLUTE uses the format HH:mm:ss.zzz
DATE uses the format dd MMM YYYY HH:mm:ss.zzzz
ISO8601 uses the format yyyy-MM-dd hh:mm:ss.zzz
NONE uses an empty string as format
TIME_RELATIVE returns the milliseconds since start of the program
+ * + * \sa QDateTime::toString(const QString &rFormat) + */ + QString toString(const QString &rFormat) const; + + /*! + * Returns the current datetime, as reported by the system clock, in + * the local time zone. + * + * \sa QDateTime::currentDateTime() + */ + static DateTime currentDateTime(); + + /*! + * Returns a datetime whose date and time are the number of + * milliseconds that have passed since 1970-01-01T00:00:00, + * Coordinated Universal Time (Qt::UTC). + * + * \sa QDateTime::fromTime_t(uint seconds) + */ + static DateTime fromMilliSeconds(qint64 milliSeconds); + + private: + QString formatDateTime(const QString &rFormat) const; + QString formatToken(const QString &rToken, bool am_pm) const; + static bool hasAMPM(const QString &rFormat); + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline DateTime::DateTime() : QDateTime() + {} + + inline DateTime::DateTime(const QDateTime &rOther) : QDateTime(rOther) + {} + + inline DateTime::DateTime(const QDate &rDate, + const QTime &rTime, + Qt::TimeSpec timeSpec) : + QDateTime(rDate, rTime, timeSpec) + {} + + inline DateTime &DateTime::operator=(const DateTime &rOther) + { QDateTime::operator=(rOther); return *this; } + + inline qint64 DateTime::toMilliSeconds() const + { return (qint64)1000 * toTime_t() + time().msec(); } + + inline DateTime DateTime::currentDateTime() + { return DateTime(QDateTime::currentDateTime()); } + + inline DateTime DateTime::fromMilliSeconds(qint64 milliSeconds) + { return DateTime(QDateTime::fromTime_t(milliSeconds / 1000).addMSecs(milliSeconds % 1000)); } + + +} // namespace Log4Qt + + +Q_DECLARE_TYPEINFO(Log4Qt::DateTime, Q_MOVABLE_TYPE); + + +#endif // LOG4QT_HELPERS_DATETIME_H diff --git a/src/log4qt/log4qt/helpers/factory.cpp b/src/log4qt/log4qt/helpers/factory.cpp new file mode 100644 index 0000000..bf2f449 --- /dev/null +++ b/src/log4qt/log4qt/helpers/factory.cpp @@ -0,0 +1,459 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: factory.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/helpers/factory.h" + +#include +#include +#include +#include "log4qt/consoleappender.h" +#include "log4qt/dailyrollingfileappender.h" +#include "log4qt/fileappender.h" +#include "log4qt/helpers/logerror.h" +#include "log4qt/helpers/initialisationhelper.h" +#include "log4qt/helpers/optionconverter.h" +#include "log4qt/patternlayout.h" +#include "log4qt/rollingfileappender.h" +#include "log4qt/simplelayout.h" +#include "log4qt/ttcclayout.h" +#include "log4qt/varia/debugappender.h" +#include "log4qt/varia/denyallfilter.h" +#include "log4qt/varia/levelmatchfilter.h" +#include "log4qt/varia/levelrangefilter.h" +#include "log4qt/varia/listappender.h" +#include "log4qt/varia/nullappender.h" +#include "log4qt/varia/stringmatchfilter.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + LOG4QT_DECLARE_STATIC_LOGGER(logger, Log4Qt::Factory) + + + // Appenders + + Appender *console_file_appender() + { return new ConsoleAppender; } + + Appender *create_daily_rolling_file_appender() + { return new DailyRollingFileAppender; } + + Appender *create_debug_appender() + { return new DebugAppender; } + + Appender *create_file_appender() + { return new FileAppender; } + + Appender *create_list_appender() + { return new ListAppender; } + + Appender *create_null_appender() + { return new NullAppender; } + + Appender *create_rolling_file_appender() + { return new RollingFileAppender; } + + + // Filters + + Filter *create_deny_all_filter() + { return new DenyAllFilter; } + + Filter *create_level_match_filter() + { return new LevelMatchFilter; } + + Filter *create_level_range_filter() + { return new LevelRangeFilter; } + + Filter *create_string_match_filter() + { return new StringMatchFilter; } + + + // Layouts + + Layout *create_pattern_layout() + { return new PatternLayout; } + + Layout *create_simple_layout() + { return new SimpleLayout; } + + Layout *create_ttcc_layout() + { return new TTCCLayout; } + + + + /************************************************************************** + * Class implementation: Factory + **************************************************************************/ + + + Factory::Factory() : + mObjectGuard(), + mAppenderRegistry(), + mFilterRegistry(), + mLayoutRegistry() + { + registerDefaultAppenders(); + registerDefaultFilters(); + registerDefaultLayouts(); + } + + + LOG4QT_IMPLEMENT_INSTANCE(Factory) + + + Appender *Factory::doCreateAppender(const QString &rAppenderClassName) + { + QMutexLocker locker(&mObjectGuard); + + if (!mAppenderRegistry.contains(rAppenderClassName)) + { + logger()->warn("Request for the creation of Appender with class '%1', which is not registered", rAppenderClassName); + return 0; + } + return mAppenderRegistry.value(rAppenderClassName)(); + } + + + Filter *Factory::doCreateFilter(const QString &rFilterClassName) + { + QMutexLocker locker(&mObjectGuard); + + if (!mFilterRegistry.contains(rFilterClassName)) + { + logger()->warn("Request for the creation of Filter with class '%1', which is not registered", rFilterClassName); + return 0; + } + return mFilterRegistry.value(rFilterClassName)(); + } + + + Layout *Factory::doCreateLayout(const QString &rLayoutClassName) + { + QMutexLocker locker(&mObjectGuard); + + if (!mLayoutRegistry.contains(rLayoutClassName)) + { + logger()->warn("Request for the creation of Layout with class '%1', which is not registered", rLayoutClassName); + return 0; + } + return mLayoutRegistry.value(rLayoutClassName)(); + } + + + void Factory::doRegisterAppender(const QString &rAppenderClassName, + AppenderFactoryFunc pAppenderFactoryFunc) + { + QMutexLocker locker(&mObjectGuard); + + if(rAppenderClassName.isEmpty()) + { + logger()->warn("Registering Appender factory function with empty class name"); + return; + } + mAppenderRegistry.insert(rAppenderClassName, pAppenderFactoryFunc); + } + + + void Factory::doRegisterFilter(const QString &rFilterClassName, + FilterFactoryFunc pFilterFactoryFunc) + { + QMutexLocker locker(&mObjectGuard); + + if(rFilterClassName.isEmpty()) + { + logger()->warn("Registering Filter factory function with empty class name"); + return; + } + mFilterRegistry.insert(rFilterClassName, pFilterFactoryFunc); + } + + + void Factory::doRegisterLayout(const QString &rLayoutClassName, + LayoutFactoryFunc pLayoutFactoryFunc) + { + QMutexLocker locker(&mObjectGuard); + + if(rLayoutClassName.isEmpty()) + { + logger()->warn("Registering Layout factory function with empty class name"); + return; + } + mLayoutRegistry.insert(rLayoutClassName, pLayoutFactoryFunc); + } + + + void Factory::doSetObjectProperty(QObject *pObject, + const QString &rProperty, + const QString &rValue) + { + // - Validate property + // - Get correct property name from meta object + // - Find specific property setter + // - If no specfifc propery setter can be found, + // find general property setter + // - Call property setter + + QMetaProperty meta_property; + if (!validateObjectProperty(meta_property, rProperty, pObject)) + return; + + QString property = QLatin1String(meta_property.name()); + QString type = QLatin1String(meta_property.typeName()); + logger()->debug("Setting property '%1' on object of class '%2' to value '%3'", + property, + QLatin1String(pObject->metaObject()->className()), + rValue); + + QVariant value; + bool ok = true; + if (type == QLatin1String("bool")) + value = OptionConverter::toBoolean(rValue, &ok); + else if (type == QLatin1String("int")) + value = OptionConverter::toInt(rValue, &ok); + else if (type == QLatin1String("qint64") || type == QLatin1String("qlonglong")) + value = OptionConverter::toQInt64(rValue, &ok); + else if (type == QLatin1String("Log4Qt::Level")) + value = QVariant::fromValue(OptionConverter::toLevel(rValue, &ok)); + else if (type == QLatin1String("QString")) + value = rValue; + else + { + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Cannot convert to type '%1' for property '%2' on object of class '%3'"), + CONFIGURATOR_UNKNOWN_TYPE_ERROR, + "Log4Qt::Factory"); + e << type + << property + << QString::fromLatin1(pObject->metaObject()->className()); + logger()->error(e); + return; + } + if (!ok) + return; + + // Everything is checked and the type is the one of the property. + // Write should never return false + if (!meta_property.write(pObject, value)) + logger()->warn("Unxpected error result from QMetaProperty.write()"); + } + + + void Factory::doUnregisterAppender(const QString &rAppenderClassName) + { + QMutexLocker locker(&mObjectGuard); + + if (!mAppenderRegistry.contains(rAppenderClassName)) + { + logger()->warn("Request to unregister not registered Appender factory function for class '%1'", rAppenderClassName); + return; + } + mAppenderRegistry.remove(rAppenderClassName); + } + + + void Factory::doUnregisterFilter(const QString &rFilterClassName) + { + QMutexLocker locker(&mObjectGuard); + + if (!mFilterRegistry.contains(rFilterClassName)) + { + logger()->warn("Request to unregister not registered Filter factory function for class '%1'", rFilterClassName); + return; + } + mFilterRegistry.remove(rFilterClassName); + } + + + void Factory::doUnregisterLayout(const QString &rLayoutClassName) + { + QMutexLocker locker(&mObjectGuard); + + if (!mLayoutRegistry.contains(rLayoutClassName)) + { + logger()->warn("Request to unregister not registered Layout factory function for class '%1'", rLayoutClassName); + return; + } + mLayoutRegistry.remove(rLayoutClassName); + } + + + void Factory::registerDefaultAppenders() + { + mAppenderRegistry.insert(QLatin1String("org.apache.log4j.ConsoleAppender"), console_file_appender); + mAppenderRegistry.insert(QLatin1String("Log4Qt::ConsoleAppender"), console_file_appender); + mAppenderRegistry.insert(QLatin1String("org.apache.log4j.DailyRollingFileAppender"), create_daily_rolling_file_appender); + mAppenderRegistry.insert(QLatin1String("Log4Qt::DailyRollingFileAppender"), create_daily_rolling_file_appender); + mAppenderRegistry.insert(QLatin1String("org.apache.log4j.varia.DebugAppender"), create_debug_appender); + mAppenderRegistry.insert(QLatin1String("Log4Qt::DebugAppender"), create_debug_appender); + mAppenderRegistry.insert(QLatin1String("org.apache.log4j.FileAppender"), create_file_appender); + mAppenderRegistry.insert(QLatin1String("Log4Qt::FileAppender"), create_file_appender); + mAppenderRegistry.insert(QLatin1String("org.apache.log4j.varia.ListAppender"), create_list_appender); + mAppenderRegistry.insert(QLatin1String("Log4Qt::ListAppender"), create_list_appender); + mAppenderRegistry.insert(QLatin1String("org.apache.log4j.varia.NullAppender"), create_null_appender); + mAppenderRegistry.insert(QLatin1String("Log4Qt::NullAppender"), create_null_appender); + mAppenderRegistry.insert(QLatin1String("org.apache.log4j.RollingFileAppender"), create_rolling_file_appender); + mAppenderRegistry.insert(QLatin1String("Log4Qt::RollingFileAppender"), create_rolling_file_appender); + } + + + void Factory::registerDefaultFilters() + { + mFilterRegistry.insert(QLatin1String("org.apache.log4j.varia.DenyAllFilter"), create_deny_all_filter); + mFilterRegistry.insert(QLatin1String("Log4Qt::DenyAllFilter"), create_deny_all_filter); + mFilterRegistry.insert(QLatin1String("org.apache.log4j.varia.LevelMatchFilter"), create_level_match_filter); + mFilterRegistry.insert(QLatin1String("Log4Qt::LevelMatchFilter"), create_level_match_filter); + mFilterRegistry.insert(QLatin1String("org.apache.log4j.varia.LevelRangeFilter"), create_level_range_filter); + mFilterRegistry.insert(QLatin1String("Log4Qt::LevelRangeFilter"), create_level_range_filter); + mFilterRegistry.insert(QLatin1String("org.apache.log4j.varia.StringMatchFilter"), create_string_match_filter); + mFilterRegistry.insert(QLatin1String("Log4Qt::StringMatchFilter"), create_string_match_filter); + } + + + void Factory::registerDefaultLayouts() + { + mLayoutRegistry.insert(QLatin1String("org.apache.log4j.PatternLayout"), create_pattern_layout); + mLayoutRegistry.insert(QLatin1String("Log4Qt::PatternLayout"), create_pattern_layout); + mLayoutRegistry.insert(QLatin1String("org.apache.log4j.SimpleLayout"), create_simple_layout); + mLayoutRegistry.insert(QLatin1String("Log4Qt::SimpleLayout"), create_simple_layout); + mLayoutRegistry.insert(QLatin1String("org.apache.log4j.TTCCLayout"), create_ttcc_layout); + mLayoutRegistry.insert(QLatin1String("Log4Qt::TTCCLayout"), create_ttcc_layout); + } + + + bool Factory::validateObjectProperty(QMetaProperty &rMetaProperty, + const QString &rProperty, + QObject *pObject) + { + // Validate: + // - No null object pointer + // - No empty property name + // - Property exists on the object (QT or Java name) + // - Property is readable + // - Property is writable + + const char *p_context = "Log4Qt::Factory"; + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Unable to set property value on object"), + CONFIGURATOR_PROPERTY_ERROR, + p_context); + + if (!pObject) + { + LogError ce = LOG4QT_ERROR(QT_TR_NOOP("Invalid null object pointer"), + 0, + p_context); + e.addCausingError(ce); + logger()->error(e); + return false; + } + if (rProperty.isEmpty()) + { + LogError ce = LOG4QT_ERROR(QT_TR_NOOP("Invalid empty property name"), + 0, + p_context); + e.addCausingError(ce); + logger()->error(e); + return false; + } + const QMetaObject *p_meta_object = pObject->metaObject(); + QString property = rProperty; + int i = p_meta_object->indexOfProperty(property.toLatin1()); + if (i < 0) + { + // Try name with lower case first character. Java properties names + // start upper case + property[0] = property[0].toLower(); + i = p_meta_object->indexOfProperty(property.toLatin1()); + if (i < 0) + { + LogError ce = LOG4QT_ERROR(QT_TR_NOOP("Property '%1' does not exist in class '%2'"), + 0, + p_context); + ce << property + << QString::fromLatin1(pObject->metaObject()->className()); + e.addCausingError(ce); + logger()->error(e); + return false; + } + } + rMetaProperty = p_meta_object->property(i); + if (!rMetaProperty.isWritable()) + { + LogError ce = LOG4QT_ERROR(QT_TR_NOOP("Property '%1' is not writable in class '%2'"), + 0, + p_context); + ce << property + << QString::fromLatin1(pObject->metaObject()->className()); + e.addCausingError(ce); + logger()->error(e); + return false; + } + + return true; + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, + const Factory &rFactory) + { + debug.nospace() << "Factory(" + << "appenderfactories:" << rFactory.registeredAppenders() + << "filterfactories:" << rFactory.registeredFilters() + << "layoutfactories:" << rFactory.registeredLayouts() + << ")"; + return debug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + +} // namespace Log4Qt + diff --git a/src/log4qt/log4qt/helpers/factory.h b/src/log4qt/log4qt/helpers/factory.h new file mode 100644 index 0000000..b70104f --- /dev/null +++ b/src/log4qt/log4qt/helpers/factory.h @@ -0,0 +1,494 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: factory.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_HELPERS_FACTORY_H +#define LOG4QT_HELPERS_FACTORY_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#include +#include + +#include "ukui-logmacros.h" + +QT_BEGIN_NAMESPACE +class QMetaProperty; +class QObject; +QT_END_NAMESPACE + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + class Appender; + class Filter; + class Layout; + + /*! + * \brief The class Factory provides factories for Appender, Filter and + * Layout objects. + * + * The functions createAppender(), createFilter() and createLayout() + * allow to create objects by specifying their class names. By default + * all classes of the package are recognised with their Log4j and Log4Qt + * classanmes. For example an object of the class FileAppender can be + * craeted using "org.apache.log4j.FileAppender" or "Log4Qt::FileAppender". + * Additional classes can be registered using registerAppender(), + * registerFilter() and registerLayout(). + * + * An QObject property can be set from a string value with + * setObjectProperty(). The function handles the required error checking + * and type conversion. + * + * \note All the functions declared in this class are thread-safe. + * + * \sa PropertyConfigurator + */ + class LIBUKUILOG4QT_EXPORT Factory + { + public: + /*! + * Prototype for an Appender factory function. The function creates + * an Appender object on the heap and returns a pointer to it. + * + * \sa registerAppender(), createAppender() + */ + typedef Appender *(*AppenderFactoryFunc)(); + + /*! + * Prototype for a Filter factory function. The function creates + * a Filter object on the heap and returns a pointer to it. + * + * \sa registerFilter(), createFilter() + */ + typedef Filter *(*FilterFactoryFunc)(); + + /*! + * Prototype for a Layout factory function. The function creates + * a Layout object on the heap and returns a pointer to it. + * + * \sa registerLayout(), createLayout() + */ + typedef Layout *(*LayoutFactoryFunc)(); + + private: + Factory(); + Q_DISABLE_COPY(Factory) + + public: + /*! + * Creates an object for the class \a rAppenderClassName on the heap + * and returns a pointer to it. If the class has no registered factory + * function a null pointer is returned. + * + * \sa registerAppender(), unregisterAppender(), registeredAppenders() + */ + static Appender *createAppender(const QString &rAppenderClassName); + + /*! + * This is an overloaded member function, provided for convenience. + */ + static Appender *createAppender(const char *pAppenderClassName); + + /*! + * Creates an object for the class \a rFilterClassName on the heap + * and returns a pointer to it. If the class has no registered factory + * function a null pointer is returned. + * + * \sa registerFilter(), unregisterFilter(), registeredFilters() + */ + static Filter *createFilter(const QString &rFilterClassName); + + /*! + * This is an overloaded member function, provided for convenience. + */ + static Filter *createFilter(const char *pFilterClassName); + + /*! + * Creates an object for the class \a rLayoutClassName on the heap + * and returns a pointer to it. If the class has no registered factory + * function a null pointer is returned. + * + * \sa registerLayout(), unregisterLayout(), registeredLayouts() + */ + static Layout *createLayout(const QString &rLayoutClassName); + + /*! + * This is an overloaded member function, provided for convenience. + */ + static Layout *createLayout(const char *pLayoutClassName); + + /*! + * Returns the Factory instance. + */ + static Factory *instance(); + + /*! + * Registers the Appender factory function \a pAppenderFactoryFunc + * for the class \a rAppenderClassName. If a registered factory + * function exists for the class, it is replaced with + * \a pAppenderFactoryFunc. + * + * \sa unregisterAppender(), registeredAppenders(), createAppender() + */ + static void registerAppender(const QString &rAppenderClassName, + AppenderFactoryFunc pAppenderFactoryFunc); + + /*! + * This is an overloaded member function, provided for convenience. + */ + static void registerAppender(const char *pAppenderClassName, + AppenderFactoryFunc pAppenderFactoryFunc); + + /*! + * Registers the Filter factory function \a pFilterFactoryFunc + * for the class \a rFilterClassName. If a registered factory + * function exists for the class, it is replaced with + * \a pFilterFactoryFunc. + * + * \sa unregisterFilter(), registeredFilters(), createFilter() + */ + static void registerFilter(const QString &rFilterClassName, + FilterFactoryFunc pFilterFactoryFunc); + + /*! + * This is an overloaded member function, provided for convenience. + */ + static void registerFilter(const char *pFilterClassName, + FilterFactoryFunc pFilterFactoryFunc); + + /*! + * Registers the Layout factory function \a pLayoutFactoryFunc + * for the class \a rLayoutClassName. If a registered factory + * function exists for the class, it is replaced with + * \a pLayoutFactoryFunc. + * + * \sa unregisterLayout(), registeredLayout(), createLayout() + */ + static void registerLayout(const QString &rLayoutClassName, + LayoutFactoryFunc pLayoutFactoryFunc); + + /*! + * This is an overloaded member function, provided for convenience. + */ + static void registerLayout(const char *pLayoutClassName, + LayoutFactoryFunc pLayoutFactoryFunc); + + /*! + * Returns a list of the class names for registered Appender factory + * functions. + * + * \sa registerAppender(), unregisterAppender() + */ + static QStringList registeredAppenders(); + + /*! + * Returns a list of the class names for registered Filter factory + * functions. + * + * \sa registerFilter(), unregisterFilter() + */ + static QStringList registeredFilters(); + + /*! + * Returns a list of the class names for registered Layout factory + * functions. + * + * \sa registerLayout(), unregisterLayout() + */ + static QStringList registeredLayouts(); + + /*! + * Sets the property \a rProperty of the object \a pObject to the + * value \a rValue. The function will test that the property + * \a rProperty is writeable and of a type the function can convert to. + * The types bool, int, Level and QString are supported. + * + * \sa OptionConverter + */ + static void setObjectProperty(QObject *pObject, + const QString &rProperty, + const QString &rValue); + + /*! + * This is an overloaded member function, provided for convenience. + */ + static void setObjectProperty(QObject *pObject, + const char *pProperty, + const QString &rValue); + + /*! + * Unregisters the Appender factory function for the class + * \a rAppenderClassName. + * + * \sa registerAppender(), registeredAppenders() + */ + static void unregisterAppender(const QString &rAppenderClassName); + + /*! + * This is an overloaded member function, provided for convenience. + */ + static void unregisterAppender(const char *pAppenderClassName); + + /*! + * Unregisters the Filter factory function for the class + * \a rFilterClassName. + * + * \sa registerFilter(), registeredFilters() + */ + static void unregisterFilter(const QString &rFilterClassName); + + /*! + * This is an overloaded member function, provided for convenience. + */ + static void unregisterFilter(const char *pFilterClassName); + + /*! + * Unregisters the Layout factory function for the class + * \a rLayoutClassName. + * + * \sa registerLayout(), registeredLayouts() + */ + static void unregisterLayout(const QString &rLayoutClassName); + + /*! + * This is an overloaded member function, provided for convenience. + */ + static void unregisterLayout(const char *pLayoutClassName); + + private: + Appender *doCreateAppender(const QString &rAppenderClassName); + Filter *doCreateFilter(const QString &rFilterClassName); + Layout *doCreateLayout(const QString &rLayoutClassName); + void doRegisterAppender(const QString &rAppenderClassName, + AppenderFactoryFunc pAppenderFactoryFunc); + void doRegisterFilter(const QString &rFilterClassName, + FilterFactoryFunc pFilterFactoryFunc); + void doRegisterLayout(const QString &rLayoutClassName, + LayoutFactoryFunc pLayoutFactoryFunc); + void doSetObjectProperty(QObject *pObject, + const QString &rProperty, + const QString &rValue); + void doUnregisterAppender(const QString &rAppenderClassName); + void doUnregisterFilter(const QString &rFilterClassName); + void doUnregisterLayout(const QString &rLayoutClassName); + void registerDefaultAppenders(); + void registerDefaultFilters(); + void registerDefaultLayouts(); + bool validateObjectProperty(QMetaProperty &rMetaProperty, + const QString &rProperty, + QObject *pObject); + + private: + mutable QMutex mObjectGuard; + QHash mAppenderRegistry; + QHash mFilterRegistry; + QHash mLayoutRegistry; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + +#ifndef QT_NO_DEBUG_STREAM + /*! + * \relates Factory + * + * Writes all object member variables to the given debug stream \a rDebug and + * returns the stream. + * + * + * %Factory(appenderfactories:("Log4Qt::DebugAppender", "Log4Qt::NullAppender", + * "Log4Qt::ConsoleAppender", "org.apache.log4j.varia.DebugAppender", + * "org.apache.log4j.FileAppender", "org.apache.log4j.RollingFileAppender", + * "org.apache.log4j.DailyRollingFileAppender", + * "org.apache.log4j.varia.ListAppender", + * "org.apache.log4j.varia.NullAppender", + * "Log4Qt::FileAppender", "org.apache.log4j.ConsoleAppender", + * "Log4Qt::DailyRollingFileAppender", "Log4Qt::ListAppender", + * "Log4Qt::RollingFileAppender") filterfactories: + * ("Log4Qt::DenyAllFilter", "Log4Qt::StringMatchFilter", + * "Log4Qt::LevelRangeFilter", "org.apache.log4j.varia.DenyAllFilter", + * "org.apache.log4j.varia.LevelRangeFilter", + * "org.apache.log4j.varia.StringMatchFilter", "Log4Qt::LevelMatchFilter", + * "org.apache.log4j.varia.LevelMatchFilter") layoutfactories: + * ("org.apache.log4j.SimpleLayout", "Log4Qt::PatternLayout", + * "Log4Qt::SimpleLayout", "org.apache.log4j.TTCCLayout", + * "Log4Qt::TTCCLayout", "org.apache.log4j.PatternLayout") ) + * + * \sa QDebug, Factory::logManager() + */ + QDebug operator<<(QDebug debug, + const Factory &rFactory); +#endif // QT_NO_DEBUG_STREAM + + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline Appender *Factory::createAppender(const QString &rAppenderClassName) + { + return instance()->doCreateAppender(rAppenderClassName); + } + + inline Appender *Factory::createAppender(const char *pAppenderClassName) + { + return instance()->doCreateAppender(QLatin1String(pAppenderClassName)); + } + + inline Filter *Factory::createFilter(const QString &rFilterClassName) + { + return instance()->doCreateFilter(rFilterClassName); + } + + inline Filter *Factory::createFilter(const char *pFilterClassName) + { + return instance()->doCreateFilter(QLatin1String(pFilterClassName)); + } + + inline Layout *Factory::createLayout(const QString &rLayoutClassName) + { + return instance()->doCreateLayout(rLayoutClassName); + } + + inline Layout *Factory::createLayout(const char *pLayoutClassName) + { + return instance()->doCreateLayout(QLatin1String(pLayoutClassName)); + } + + inline void Factory::registerAppender(const QString &rAppenderClassName, + AppenderFactoryFunc pAppenderFactoryFunc) + { + instance()->doRegisterAppender(rAppenderClassName, pAppenderFactoryFunc); + } + + inline void Factory::registerAppender(const char *pAppenderClassName, + AppenderFactoryFunc pAppenderFactoryFunc) + { + instance()->doRegisterAppender(QLatin1String(pAppenderClassName), pAppenderFactoryFunc); + } + + inline void Factory::registerFilter(const QString &rFilterClassName, + FilterFactoryFunc pFilterFactoryFunc) + { + instance()->doRegisterFilter(rFilterClassName, pFilterFactoryFunc); + } + + inline void Factory::registerFilter(const char *pFilterClassName, + FilterFactoryFunc pFilterFactoryFunc) + { + instance()->doRegisterFilter(QLatin1String(pFilterClassName), pFilterFactoryFunc); + } + + inline void Factory::registerLayout(const QString &rLayoutClassName, + LayoutFactoryFunc pLayoutFactoryFunc) + { + instance()->doRegisterLayout(rLayoutClassName, pLayoutFactoryFunc); + } + + inline void Factory::registerLayout(const char *pLayoutClassName, + LayoutFactoryFunc pLayoutFactoryFunc) + { + instance()->doRegisterLayout(QLatin1String(pLayoutClassName), pLayoutFactoryFunc); + } + + inline QStringList Factory::registeredAppenders() + { + QMutexLocker locker(&instance()->mObjectGuard); + return instance()->mAppenderRegistry.keys(); + } + + inline QStringList Factory::registeredFilters() + { + QMutexLocker locker(&instance()->mObjectGuard); + return instance()->mFilterRegistry.keys(); + } + + inline QStringList Factory::registeredLayouts() + { + QMutexLocker locker(&instance()->mObjectGuard); + return instance()->mLayoutRegistry.keys(); + } + + inline void Factory::setObjectProperty(QObject *pObject, + const QString &rProperty, + const QString &rValue) + { + instance()->doSetObjectProperty(pObject, rProperty, rValue); + } + + inline void Factory::setObjectProperty(QObject *pObject, + const char *pProperty, + const QString &rValue) + { + instance()->doSetObjectProperty(pObject, QLatin1String(pProperty), rValue); + } + + inline void Factory::unregisterAppender(const QString &rAppenderClassName) + { + instance()->doUnregisterAppender(rAppenderClassName); + } + + inline void Factory::unregisterAppender(const char *pAppenderClassName) + { + instance()->doUnregisterAppender(QLatin1String(pAppenderClassName)); + } + + inline void Factory::unregisterFilter(const QString &rFilterClassName) + { + instance()->doUnregisterFilter(rFilterClassName); + } + + inline void Factory::unregisterFilter(const char *pFilterClassName) + { + instance()->doUnregisterFilter(QLatin1String(pFilterClassName)); + } + + inline void Factory::unregisterLayout(const QString &rLayoutClassName) + { + instance()->doUnregisterLayout(rLayoutClassName); + } + + inline void Factory::unregisterLayout(const char *pLayoutClassName) + { + instance()->doUnregisterLayout(QLatin1String(pLayoutClassName)); + } + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::Factory, Q_COMPLEX_TYPE); // use default + + +#endif // LOG4QT_HELPERS_FACTORY_H diff --git a/src/log4qt/log4qt/helpers/initialisationhelper.cpp b/src/log4qt/log4qt/helpers/initialisationhelper.cpp new file mode 100644 index 0000000..e8ba59b --- /dev/null +++ b/src/log4qt/log4qt/helpers/initialisationhelper.cpp @@ -0,0 +1,185 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: initialisationhelper.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * changes Feb 2009, Martin Heinrich + * - Fixed VS 2008 unreferenced formal parameter warning by using + * Q_UNUSED in operator<<. + * + * + * Copyright 2007 - 2009 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/helpers/initialisationhelper.h" + +#include +#include +#include +#include +#include +#ifndef QT_NO_DATASTREAM +#include +#endif +#include "log4qt/helpers/datetime.h" +#include "log4qt/helpers/logerror.h" +#include "log4qt/loggingevent.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + *Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: InitialisationHelper + **************************************************************************/ + + + InitialisationHelper::InitialisationHelper() : + mStartTime(DateTime::currentDateTime().toMilliSeconds()), + mEnvironmentSettings() + { + doRegisterTypes(); + doInitialiseEnvironmentSettings(); + } + + + InitialisationHelper::~InitialisationHelper() + { + Q_ASSERT_X(false, "InitialisationHelper::~InitialisationHelper()", "Unexpected destruction of singleton object"); + } + + + LOG4QT_IMPLEMENT_INSTANCE(InitialisationHelper) + + + void InitialisationHelper::doInitialiseEnvironmentSettings() + { + // Is Process::systemEnvironment() safe to be used before a QCoreApplication + // object has been created? + + QStringList setting_keys; + setting_keys << QLatin1String("Debug"); + setting_keys << QLatin1String("DefaultInitOverride"); + setting_keys << QLatin1String("Configuration"); + setting_keys << QLatin1String("ConfiguratorClass"); + + QHash env_keys; + QString entry; + Q_FOREACH(entry, setting_keys) + env_keys.insert(QString::fromLatin1("log4qt_").append(entry).toUpper(), entry); + + QStringList sys_env = QProcess::systemEnvironment(); + Q_FOREACH(entry, sys_env) + { + int i = entry.indexOf(QLatin1Char('=')); + if (i == -1) + continue; + QString key = entry.left(i); + QString value = entry.mid(i + 1).trimmed(); + if (env_keys.contains(key)) + mEnvironmentSettings.insert(env_keys.value(key), value); + } + } + + + void InitialisationHelper::doRegisterTypes() + { + qRegisterMetaType("Log4Qt::LogError"); + qRegisterMetaType("Log4Qt::Level"); + qRegisterMetaType("Log4Qt::LoggingEvent"); + + #ifndef QT_NO_DATASTREAM + qRegisterMetaTypeStreamOperators("Log4Qt::LogError"); + qRegisterMetaTypeStreamOperators("Log4Qt::Level"); + qRegisterMetaTypeStreamOperators("Log4Qt::LoggingEvent"); + #endif + } + + + QString InitialisationHelper::doSetting(const QString &rKey, + const QString &rDefault) const + { + if (mEnvironmentSettings.contains(rKey)) + return mEnvironmentSettings.value(rKey); + + if (QCoreApplication::instance()) + { + QSettings s; + s.beginGroup(QLatin1String("Log4Qt")); + return s.value(rKey, rDefault).toString().trimmed(); + } + else + return rDefault; + } + + + bool InitialisationHelper::staticInitialisation() + { + instance(); + return true; + } + + + bool InitialisationHelper::msStaticInitialisation = staticInitialisation(); + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, + const InitialisationHelper &rInitialisationHelper) + { + Q_UNUSED(rInitialisationHelper); + debug.nospace() << "InitialisationHelper(" + << "starttime:" << InitialisationHelper::startTime() + << "(" << DateTime::fromMilliSeconds(InitialisationHelper::startTime()) << ")" + << "environmentsettings:" << InitialisationHelper::environmentSettings() + << ")"; + return debug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/helpers/initialisationhelper.h b/src/log4qt/log4qt/helpers/initialisationhelper.h new file mode 100644 index 0000000..f6c531c --- /dev/null +++ b/src/log4qt/log4qt/helpers/initialisationhelper.h @@ -0,0 +1,437 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: initialisationhelper.h + * created: September 2007 + * author: Martin Heinrich + * + * + * changes: Sep 2008, Martin Heinrich: + * - Replaced usage of q_atomic_test_and_set_ptr with + * QBasicAtomicPointer + * + * + * Copyright 2007 - 2008 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_HELPERS_INITIALISATIONHELPER_H +#define LOG4QT_HELPERS_INITIALISATIONHELPER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#include +#include + +#include "ukui-logmacros.h" + +#if QT_VERSION >= QT_VERSION_CHECK(4, 4, 0) +# ifndef Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE +# warning "QAtomicPointer test and set is not native. The macros Log4Qt::LOG4QT_GLOBAL_STATIC and Log4Qt::LOG4QT_IMPLEMENT_INSTANCE are not thread-safe." +# endif +#endif + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +class QMutex; + +namespace Log4Qt +{ + /*! + * LOG4QT_GLOBAL_STATIC declares a static function \a FUNCTION that + * returns a pointer to a singleton object of the type \a TYPE. + * + * The macro uses a static variable to store a pointer to the singleton + * object. On the first invocation an object of the type \a TYPE is created + * on the heap and the pointer is set. Any further invocations will return + * the stored pointer. If multiple threads are accessing the function + * without the pointer being set, each thread will create an object of the + * type \a TYPE. The threads that find the pointer already been set will + * delete their object. The singleton object will not be deleted during static + * de-initialisation. + * + * The following example uses a global global mutex object to synchronise + * access to a static member variable. + * + * \code + * #file: myclass.h + * + * class MyClass + * { + * public: + * MyClass(); + * ~MyClass(); + * private: + * static qint64 msObjectCount; + * } + * \endcode + * \code + * #file: myclass.cpp + * + * #include myclass.h + * + * LOG4QT_GLOBAL_STATIC(QMutex, class_guard) + * + * MyClass::MyClass() + * { + * QMutexLocker(class_guard()); + * msObjectCount++; + * } + * + * MyClass::~MyClass() + * { + * QMutexLocker(class_guard()); + * msObjectCount--; + * } + * + * qint64 MyClass::msObjectCount = 0; + * \endcode + * + * \note The function created by the macro is thread-safe. + * + * \sa \ref Log4Qt::LOG4QT_IMPLEMENT_INSTANCE "LOG4QT_IMPLEMENT_INSTANCE", + * \ref Log4Qt::InitialisationHelper "InitialisationHelper" + */ +#if QT_VERSION < QT_VERSION_CHECK(4, 4, 0) + #define LOG4QT_GLOBAL_STATIC(TYPE, FUNCTION) \ + static volatile TYPE *sp_global_static_##FUNCTION = 0; \ + TYPE *FUNCTION() \ + { \ + if (!sp_global_static_##FUNCTION) \ + { \ + TYPE *p_temp = new TYPE; \ + if (!q_atomic_test_and_set_ptr(&sp_global_static_##FUNCTION, \ + 0, p_temp)) \ + delete p_temp; \ + } \ + return const_cast(sp_global_static_##FUNCTION); \ + } +#elif QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + #define LOG4QT_GLOBAL_STATIC(TYPE, FUNCTION) \ + static QBasicAtomicPointer sp_global_static_##FUNCTION = \ + Q_BASIC_ATOMIC_INITIALIZER(0); \ + TYPE *FUNCTION() \ + { \ + if (!sp_global_static_##FUNCTION) \ + { \ + TYPE *p_temp = new TYPE; \ + if (!sp_global_static_##FUNCTION.testAndSetOrdered(0, \ + p_temp)) \ + delete p_temp; \ + } \ + return sp_global_static_##FUNCTION; \ + } +#else + #define LOG4QT_GLOBAL_STATIC(TYPE, FUNCTION) \ + static QBasicAtomicPointer sp_global_static_##FUNCTION = \ + Q_BASIC_ATOMIC_INITIALIZER(0); \ + TYPE *FUNCTION() \ + { \ + if (!sp_global_static_##FUNCTION.loadAcquire()) \ + { \ + TYPE *p_temp = new TYPE; \ + if (!sp_global_static_##FUNCTION.testAndSetOrdered(0, \ + p_temp)) \ + delete p_temp; \ + } \ + return sp_global_static_##FUNCTION.loadAcquire(); \ + } +#endif + + /*! + * LOG4QT_IMPLEMENT_INSTANCE implements an instance function for a + * singleton class \a TYPE. + * + * The function works like the one created by + * \ref Log4Qt::LOG4QT_GLOBAL_STATIC "LOG4QT_GLOBAL_STATIC". + * + * The following example illustrates how to use the macro to create a + * singleton class: + * + * \code + * #file: mysingleton.h + * + * class MySingleton + * { + * private: + * MySingleton(); + * ~MySingleton(); + * public: + * MySingleton *instance(); + * } + * \endcode + * \code + * #file: mysingleton.cpp + * + * #include mysingleton.h + * + * MySingleton::MySingleton() + * {} + * + * MySingleton::~MySingleton() + * {} + * + * LOG4QT_IMPLEMENT_INSTANCE(MySingleton) + * + * \endcode + * + * \note The function created by the macro is thread-safe. + * + * \sa \ref Log4Qt::LOG4QT_GLOBAL_STATIC "LOG4QT_GLOBAL_STATIC", + * \ref Log4Qt::InitialisationHelper "InitialisationHelper" + */ +#if QT_VERSION < QT_VERSION_CHECK(4, 4, 0) + #define LOG4QT_IMPLEMENT_INSTANCE(TYPE) \ + static TYPE *sp_singleton_##TYPE = 0; \ + TYPE *TYPE::instance() \ + { \ + if (!sp_singleton_##TYPE) \ + { \ + TYPE *p_temp = new TYPE; \ + if (!q_atomic_test_and_set_ptr(&sp_singleton_##TYPE, \ + 0, p_temp)) \ + delete p_temp; \ + } \ + return sp_singleton_##TYPE; \ + } +#elif QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + #define LOG4QT_IMPLEMENT_INSTANCE(TYPE) \ + static QBasicAtomicPointer sp_singleton_##TYPE = \ + Q_BASIC_ATOMIC_INITIALIZER(0); \ + TYPE *TYPE::instance() \ + { \ + if (!sp_singleton_##TYPE) \ + { \ + TYPE *p_temp = new TYPE; \ + if (!sp_singleton_##TYPE.testAndSetOrdered(0, p_temp)) \ + delete p_temp; \ + } \ + return sp_singleton_##TYPE; \ + } +#else + #define LOG4QT_IMPLEMENT_INSTANCE(TYPE) \ + static QBasicAtomicPointer sp_singleton_##TYPE = \ + Q_BASIC_ATOMIC_INITIALIZER(0); \ + TYPE *TYPE::instance() \ + { \ + if (!sp_singleton_##TYPE.loadAcquire()) \ + { \ + TYPE *p_temp = new TYPE; \ + if (!sp_singleton_##TYPE.testAndSetOrdered(0, p_temp)) \ + delete p_temp; \ + } \ + return sp_singleton_##TYPE.loadAcquire(); \ + } +#endif + + /*! + * \brief The class InitialisationHelper performs static initialisation + * tasks. + * + * The InitialisationHelper is either created on the first call or through + * static initialisation. It will capture the programs startup time, + * which can be retrieved using startTime(). The system environment + * is analysed for package related definitions. The result is available + * over environmentSettings(). The packages custom types are registered with + * the Qt type system. + * + * Settings for the package can be retrieved using setting(). Two macros + * are available to help with the creation of singletons / global static + * objects (\ref Log4Qt::LOG4QT_GLOBAL_STATIC "LOG4QT_GLOBAL_STATIC" and + * \ref Log4Qt::LOG4QT_IMPLEMENT_INSTANCE "LOG4QT_IMPLEMENT_INSTANCE"). + * + * \note All the functions declared in this class are thread-safe. + * + * \sa \ref Init "Initialization procedure", + */ + class LIBUKUILOG4QT_EXPORT InitialisationHelper + { + private: + InitialisationHelper(); + InitialisationHelper(const InitialisationHelper &rOther); // Not implemented + virtual ~InitialisationHelper(); + InitialisationHelper &operator=(const InitialisationHelper &rOther); // Not implemented + + public: + + /*! + * Returns a hash with the settings retrieved from the system + * environment on startup. + * + * The following table shows the environment variables taken into + * account and the setting key used for them. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Environment variable Setting key
LOG4QT_DEBUG Debug
LOG4QT_DEFAULTINITOVERRIDE DefaultInitOverride
LOG4QT_CONFIGURATION Configuration
LOG4QT_CONFIGURATORCLASS ConfiguratorClass
+ * + * \sa \ref Env "Environment Variables", + * setting() + */ + static QHash environmentSettings(); + + /*! + * Returns the InitialisationHelper instance. + */ + static InitialisationHelper *instance(); + + /*! + * Returns the value for the setting \a rKey or \a rDefault, if it is + * not defined. + * + * A setting can be either defined by an environment variable or by a + * key in the application setting. The function will first test the + * settings made by environment variables for the key \a rKey using + * environmentSettings(). If the key is not present and a + * QCoreApplication exists, the application settings are tested for + * the key \a rKey in the group \c %Log4Qt. + * + * The following setting exists: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Setting key Description
Debug The variable controls the Level value for the logger + * LogManager::logLogger(). If the value is a valid Level string, + * the level for the logger is set to the level. If the value is not + * a valid Level string, \ref Level::DEBUG_INT "DEBUG_INT" is used. + * Otherwise \ref Level::ERROR_INT "ERROR_INT" is used.
DefaultInitOverride The variable controls the \ref Init "initialization procedure" + * performed by the \ref LogManager "LogManager" on startup. + * If it is set to any other value then \c false the \ref Init + * "initialization procedure" is skipped.
Configuration Specifies the configuration file used for initialising the package.
ConfiguratorClass Specifies the configurator class used for initialising the package.
+ * + * \sa environmentSettings(), \ref Env "Environment Variables", + * \ref Init "Initialization procedure", + * LogManager::configureLogLogger(), LogManager::startup() + */ + static QString setting(const QString &rKey, + const QString &rDefault = QString()); + + /*! + * Returns the start time of the program as the number of milliseconds + * that have passed since 1970-01-01T00:00:00,000, Coordinated + * Universal Time (Qt::UTC). + * + * \sa DateTime::fromMilliSeconds(), + * DateTime::toMilliSeconds() + */ + static qint64 startTime(); + + private: + void doInitialiseEnvironmentSettings(); + void doRegisterTypes(); + QString doSetting(const QString &rKey, + const QString &rDefault) const; + static bool shutdown(); + static bool staticInitialisation(); + + private: + // QMutex mObjectGuard; + const qint64 mStartTime; + QHash mEnvironmentSettings; + static bool msStaticInitialisation; + +#ifndef QT_NO_DEBUG_STREAM + // Needs to be friend to access details + friend QDebug operator<<(QDebug debug, + const InitialisationHelper &rInitialisationHelper); +#endif // QT_NO_DEBUG_STREAM + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + +#ifndef QT_NO_DEBUG_STREAM + /*! + * \relates InitialisationHelper + * + * Writes all object member variables to the given debug stream \a rDebug and + * returns the stream. + * + * + * %InitialisationHelper(InitialisationHelper(starttime:1193883677438( + * QDateTime("Wed Oct 31 21:21:17 2007") ) + * environmentsettings: QHash(("configuration", "\myapp.log4j") + * ("Debug", "DEBUG")) ) ) + * + * \sa QDebug, InitialisationHelper::logManager() + */ + QDebug operator<<(QDebug debug, + const InitialisationHelper &rInitialisationHelper); +#endif // QT_NO_DEBUG_STREAM + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline QHash InitialisationHelper::environmentSettings() + { // QMutexLocker locker(&instance()->mObjectGuard); // Constant for object lifetime + return instance()->mEnvironmentSettings; } + + inline QString InitialisationHelper::setting(const QString &rKey, + const QString &rDefault) + { // QMutexLocker locker(&instance()->mObjectGuard); // Reentrant and const + return instance()->doSetting(rKey, rDefault); } + + inline qint64 InitialisationHelper::startTime() + { // QMutexLocker locker(&instance()->mObjectGuard); // Constant for object lifetime + return instance()->mStartTime; } + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::InitialisationHelper, Q_COMPLEX_TYPE); // use default + + +#endif // LOG4QT_HELPERS_INITIALISATIONHELPER_H diff --git a/src/log4qt/log4qt/helpers/logerror.cpp b/src/log4qt/log4qt/helpers/logerror.cpp new file mode 100644 index 0000000..f78d2ab --- /dev/null +++ b/src/log4qt/log4qt/helpers/logerror.cpp @@ -0,0 +1,354 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: logerror.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + *****************************************************************************/ + + +#include "log4qt/helpers/logerror.h" + +#include +#include +#include +#include +#include +#include +#include +#include "log4qt/helpers/initialisationhelper.h" + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + typedef QThreadStorage ThreadError; + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + LOG4QT_GLOBAL_STATIC(ThreadError, thread_error) + + + + /************************************************************************** + * Class implementation: LogError + **************************************************************************/ + + + LogError::LogError() : + mCode(0), + mContext(), + mMessage(), + mSymbol(), + mArgs(), + mCausingErrors() + { + } + + + LogError::LogError(const QString &rMessage, + int code, + const QString &rSymbol, + const QString &rContext) : + mCode(code), + mContext(rContext), + mMessage(cleanMessage(rMessage)), + mSymbol(rSymbol), + mArgs(), + mCausingErrors() + { + } + + + LogError::LogError(const char *pMessage, + int code, + const char *pSymbol, + const char *pContext, + Encoding encoding) : + mCode(code), + mContext(QString::fromLatin1(pContext)), + mMessage(), + mSymbol(QString::fromLatin1(pSymbol)), + mArgs(), + mCausingErrors() + { + switch(encoding) + { + case LATIN1: + mMessage = QString::fromLatin1(pMessage); + break; + case CODECFORTR: +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + mMessage = QTextCodec::codecForTr()->toUnicode(pMessage); +#else + mMessage = QString::fromUtf8(pMessage); +#endif + break; + case UNICODEUTF8: + mMessage = QString::fromUtf8(pMessage); + break; + default: + Q_ASSERT_X(false, "LogError::LogError", "Unkown encoding constant"); + mMessage = QString::fromLatin1(pMessage); + } + mMessage = cleanMessage(mMessage); + + if (mSymbol == QString::number(mCode)) + mSymbol.clear(); + } + + + QString LogError::translatedMessage() const + { +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + return QCoreApplication::translate(mContext.toLatin1(), mMessage.toUtf8().data(), 0, QCoreApplication::UnicodeUTF8); +#else + return QCoreApplication::translate(mContext.toLatin1(), mMessage.toUtf8().data(), 0); +#endif + } + + + LogError LogError::lastError() + { + if (!thread_error()->hasLocalData()) + return LogError(); + else + return *thread_error()->localData(); + } + + + void LogError::setLastError(const LogError &rLogError) + { + if (!thread_error()->hasLocalData()) + thread_error()->setLocalData(new LogError); + + *thread_error()->localData() = rLogError; + } + + + QString LogError::toString() const + { + QString result = messageWithArgs(); + + QString context_symbol = mContext; + if (!context_symbol.isEmpty() && !mSymbol.isEmpty()) + context_symbol.append(QLatin1String("::")); + context_symbol.append(mSymbol); + + if (!context_symbol.isEmpty() || mCode) + { + result.append(QLatin1String(" (")); + if (!context_symbol.isEmpty()) + result.append(context_symbol); + if (!context_symbol.isEmpty() && mCode) + result.append(QLatin1String(", ")); + if (mCode) + result.append(QString::number(mCode)); + result.append(QLatin1String(")")); + } + + if (!mCausingErrors.isEmpty()) + { + QString causing_errors_str = QLatin1String(": ") + mCausingErrors.at(0).toString(); + int i = 1; + while (i < mCausingErrors.count()) + { + causing_errors_str.append(QLatin1String(", ")).append(mCausingErrors.at(i).toString()); + i++; + } + result.append(causing_errors_str); + } + + return result; + } + + + QString LogError::insertArgs(const QString &rMessage) const + { + QString result; + + /* + + // Don't use a loop to be able to handle arguments that conatin strings + // like %1. + // Using this method only 9 arguments can be handled as the %1 + // in %11 gets also replaced with the first argument. + + switch (mArgs.count()) + { + case 0: + break; + case 1: + result = rMessage.arg(mArgs.at(0)); + break; + case 2: + result = rMessage.arg(mArgs.at(0), mArgs.at(1)); + break; + case 3: + result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2)); + break; + case 4: + result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2), mArgs.at(3)); + break; + case 5: + result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2), mArgs.at(3), mArgs.at(4)); + break; + case 6: + result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2), mArgs.at(3), mArgs.at(4), mArgs.at(5)); + break; + case 7: + result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2), mArgs.at(3), mArgs.at(4), mArgs.at(5), mArgs.at(6)); + break; + case 8: + result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2), mArgs.at(3), mArgs.at(4), mArgs.at(5), mArgs.at(6), mArgs.at(7)); + break; + default: + result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2), mArgs.at(3), mArgs.at(4), mArgs.at(5), mArgs.at(6), mArgs.at(7), mArgs.at(8)); + break; + } + + if (mArgs.count() > 9) + { + int i = 9; + while(i < mArgs.count()) + { + result = result.arg(mArgs.at(i)); + i++; + } + } + */ + + result = rMessage; + QVariant arg; + Q_FOREACH(arg, mArgs) + result = result.arg(arg.toString()); + return result; + } + + + QString LogError::cleanMessage(const QString &rMessage) + { + if (rMessage.isEmpty()) + return rMessage; + + QString result = rMessage; + if (rMessage.at(rMessage.size() - 1) == QLatin1Char('.')) + result = rMessage.left(rMessage.size() - 1); + return result; + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DATASTREAM + QDataStream &operator<<(QDataStream &rStream, + const LogError &rLogError) + { + QBuffer buffer; + buffer.open(QIODevice::WriteOnly); + QDataStream stream(&buffer); + + // version + quint16 version = 0; + stream << version; + // version 0 data + stream << rLogError.mCode + << rLogError.mContext + << rLogError.mMessage + << rLogError.mSymbol + << rLogError.mArgs + << rLogError.mCausingErrors; + + buffer.close(); + rStream << buffer.buffer(); + return rStream; + } + + + QDataStream &operator>>(QDataStream &rStream, + LogError &rLogError) + { + QByteArray array; + rStream >> array; + QBuffer buffer(&array); + buffer.open(QIODevice::ReadOnly); + QDataStream stream(&buffer); + + // version + quint16 version; + stream >> version; + // Version 0 data + QString level; + QString logger; + stream >> rLogError.mCode + >> rLogError.mContext + >> rLogError.mMessage + >> rLogError.mSymbol + >> rLogError.mArgs + >> rLogError.mCausingErrors; + + buffer.close(); + return rStream; + } +#endif // QT_NO_DATASTREAM + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, + const LogError &rLogError) + { + // Escape % sign + QString message = rLogError.message(); + message.replace(QLatin1String("%"), QLatin1String("%%")); + + debug.nospace() << "LogError(" + << "code:" << rLogError.code() << " " + << "context:" << rLogError.context() << " " + << "message:" << message << " " + << "symbol:" << rLogError.symbol() << " " + << "args:" << rLogError.args() + << "translatedMessage:" << rLogError.translatedMessage() + << ")"; + return debug.maybeSpace(); + } +#endif // QT_NO_DEBUG_STREAM + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/helpers/logerror.h b/src/log4qt/log4qt/helpers/logerror.h new file mode 100644 index 0000000..3c83135 --- /dev/null +++ b/src/log4qt/log4qt/helpers/logerror.h @@ -0,0 +1,552 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: logerror.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_LOGERROR_H +#define LOG4QT_LOGERROR_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#include + +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + /*! + * Creates an LogError object with the error message \a message, the error + * code \a code and the context \a context. The symbol of the error is + * set to \a code as string value. + * + * The following example logs an error, if a character is not a digit. + * + * \code + * if (!c.isDigit()) + * { + * Error e = LOG4QT_ERROR(QT_TR_NOOP("Found character '%1' where digit was expected."), + * LAYOUT_EXPECTED_DIGIT_ERROR, + * "Log4Qt::PatternFormatter"); + * e << QString(c); + * logger()->error(e); + * } + * \endcode + */ + #define LOG4QT_ERROR(message, code, context) \ + LogError(message, code, #code, context) + + /*! + * Creates an LogError object with the error message \a message and the + * error code \a code. The symbol of the error is set to \a code as string + * value. The context is set to the class name of the current object. The + * current objects class must be derived from QObject. + * + * The following example handles an error while opening a file. + * + * \code + * if (!mpFile->open(mode)) + * { + * LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to open file '%1' for appender '%2'"), + * APPENDER_OPENING_FILE_ERROR); + * e << mFileName << name(); + * e.addCausingError(LogError(mpFile->errorString(), mpFile->error())); + * logger()->error(e); + * return; + * } + * \endcode + */ + #define LOG4QT_QCLASS_ERROR(message, code) \ + LogError(message, code, #code, this->metaObject()->className()) + + /*! + * \brief The class LogError represents an error. + * + * The class error allows storing error information in a structured way. + * The error message is stored separately from the information that may be + * substituted into the message string. This way it is possible to access + * all information after the error has been raised. It also allows to + * translate the error at a later point in time or to get a translated and + * a not translated error text (e.g. translated for the UI and not + * translated for a log). + * + * The message is accessed using message() and setMessage(). Arguments for + * the message can be added using addArg() or operator<<(). The arguments + * can be retrieved using args(). The message with substituted arguments + * is returned by messageWithArgs(). + * + * An error code can be set as integer value code() and/or a symbolic value + * symbol(). + * + * To allow the translation of the message the error stores the translation + * context (context(), setContext()). The translated message can be accessed + * using translatedMessage() or using translatedMessageWithArgs(), if it + * should contain the arguments. + * + * An error can have one or more related errors that caused it. An error is + * related using addCausingError(). All causing errors can be retrieved using + * causingErrors(). + * + * A per thread error can be maintained using lastError() and setLastError(). + * + * There are two macros avaiable to simplify the error creation. The macro + * \ref Log4Qt::LOG4QT_ERROR "LOG4QT_ERROR" is used with classes not derived + * from QObject. The macro \ref Log4Qt::LOG4QT_QCLASS_ERROR "LOG4QT_QCLASS_ERROR" + * is used with classes derived from QObject. + */ + class LIBUKUILOG4QT_EXPORT LogError + { + public: + + /*! + * The enum Encoding defines the 8-bit encoding of a character string + * arguments to \ref LogError::LogError(const char *, int, const char *, + * const char *, Encoding) "LogError::LogError()". + * + * \sa \ref LogError::LogError(const char *, int, const char *, const char *, Encoding) "LogError::LogError()" + */ + enum Encoding + { + /*! LATIN-1 */ + LATIN1, + /*! + * The encoding specified by QTextCodec::codecForTr() + * (Latin-1 if none has been set). + */ + CODECFORTR, + /*! UTF-8 */ + UNICODEUTF8 + }; + Q_ENUMS(Encoding) + + /*! + * Creates an empty error. The error code is set to 0 and all other + * members are set to be empty. + * + * \sa isEmpty() + */ + LogError(); + + /*! + * Creates an error with the Message \a rMessage and the error code + * \a code. The symbol for the error code is set to \a rSymbol and the + * context to \a rContext. + * + * \a rContext must be string that can be converted to Latin-1. The + * Latin-1 representation of the string is used with + * QApplication::translate(), if a translation for \a rMessage is + * requested. + * + * \sa translatedMessage(), translatedMessageWithArgs() + */ + LogError(const QString &rMessage, + int code = 0, + const QString &rSymbol = QString(), + const QString &rContext = QString()); + + /*! + * Creates an error with the Message \a pMessage and the error code + * \a code. The symbol for the error code is set to \a pSymbol and the + * context to \a pContext. + * + * \a encoding specifies the encoding of \a pMessage. \a pSymbol and + * \a pContext are expected to be Latin-1. + * + * \note To support the macros \ref Log4Qt::LOG4QT_ERROR "LOG4QT_ERROR" + * and \ref Log4Qt::LOG4QT_QCLASS_ERROR "LOG4QT_QCLASS_ERROR" + * the function tests, if \a pSymbol is the string representation of + * \a code. If it is, the symbol is set to be empty. Otherwise symbol + * is set to \a pSymbol. + * + * \sa translatedMessage(), translatedMessageWithArgs() + */ + LogError(const char *pMessage, + int code = 0, + const char *pSymbol = 0, + const char *pContext = 0, + Encoding encoding = LATIN1); + + // LogError(const LogError &rOther); // Use compiler default + // virtual ~LogError(); // Use compiler default + // LogError &operator=(const LogError &rOther); // Use compiler default + + /*! + * Returns the error code. + * + * \sa setCode() + */ + int code() const; + + /*! + * Returns the context for the error. + * + * \sa setContext() + */ + QString context() const; + + /*! + * Returns the error message. + * + * \sa setMessage() + */ + QString message() const; + + /*! + * Returns the symbol for the error code. + * + * \sa setSymbol() + */ + QString symbol() const; + + /*! + * Returns the translated error message. + * + * The translated message is created by calling + * QCoreApplication::translate() using context().toLatin1() as + * context and message.toUtf8() as message. + * + * \sa translatedMessageWithArgs() + */ + QString translatedMessage() const; + + /*! + * Sets the error code to \a code. + * + * \sa code() + */ + void setCode(int code); + + /*! + * Sets the context to \a rClassName. + * + * \a rContext must be string that can be converted to Latin-1. The + * Latin-1 representation of the string is used with + * QApplication::translate(), if a translation for \a rMessage is + * requestd. + * + * \sa context(), translatedMessage(), translatedMessageWithArgs() + */ + void setContext(const QString &rClassName); + + /*! + * Sets the error message to \a rMessage + * + * \sa message() + */ + void setMessage(const QString &rMessage); + + /*! + * Sets the symbol for the error code to \a rSymbol. + * + * \sa symbol() + */ + void setSymbol(const QString &rSymbol); + + /*! + * Returns the last error set for the current thread using + * setLastError(). + * + * \note: This function is thread-safe. + * + * \sa setLastError() + */ + static LogError lastError(); + + /*! + * Sets the last error for the current thread to \a rLogError. + * + * \note: This function is thread-safe. + * + * \sa lastError() + */ + static void setLastError(const LogError &rLogError); + + /*! + * Appends \a rArg to the list of arguments and returns a reference to + * this error. + * + * \sa operator<<(), args(), clearArgs() + */ + LogError &addArg(const QVariant &rArg); + + /*! + * This is an overloaded member function, provided for convenience. + */ + LogError &addArg(int arg); + + /*! + * This is an overloaded member function, provided for convenience. + */ + LogError &addArg(const QString &rArg); + + /*! + * Appends \a rLogError to the list of causing errors and returns a + * reference to this error. + * + * \sa causingErrors(), clearCausingErrors() + */ + LogError &addCausingError(const LogError &rLogError); + + /*! + * Returns the list of arguments that have been added to this error. + * + * \sa addArg(), operator<<(), clearArgs() + */ + QList args() const; + + /*! + * Returns the list of causing errors that have been added to this error. + * + * \sa addArg(), operator<<(), clearArgs() + */ + QList causingErrors() const; + + /*! + * Clears the list of arguments that have been added to this error. + * + * \sa addArg(), operator<<(), args() + */ + void clearArgs(); + + /*! + * Clears the list of causing errors that have been added to this error. + * + * \sa addCausingError(), causingErrors() + */ + void clearCausingErrors(); + + /*! + * Returns true, if the error code is 0 and the message is empty. + * Otherwise it returns false. + * + * \sa code(), message() + */ + bool isEmpty() const; + + /*! + * Returns the message with arguments. The arguments are incoorporated + * into the messag using QString::arg(). + * + * \sa QString::arg(), translatedMessageWithArgs() + */ + QString messageWithArgs() const; + + /*! + * Returns the translated message with arguments. The arguments are + * incoorporated into the messag using QString::arg(). + * + * \sa QString::arg(), messageWithArgs(), translatedMessage() + */ + QString translatedMessageWithArgs() const; + + /*! + * Appends \a rArg to the list of arguments and returns a reference to + * this error. + * + * \sa addArg() + */ + LogError &operator<<(const QVariant &rArg); + + /*! + * This is an overloaded member function, provided for convenience. + */ + LogError &operator<<(int arg); + + /*! + * This is an overloaded member function, provided for convenience. + */ + LogError &operator<<(const QString &rArg); + + /*! + * Returns a string representation of the error. + * + * The string has the following format: + * + * + * message (context::symbol, code): causing_error, causing_error + * + * + * If members are empty they are omitted: + * - Omit context, if empty + * - Omit symbol, if empty + * - Omit double colon with context and symbol, if both are empty + * - Omit code, if 0 + * - Omit bracket with context/symbol and code, if all are empty + * - Omit colon with causing errors, if no causing errors exist + */ + QString toString() const; + + private: + QString insertArgs(const QString &rMessage) const; + QString cleanMessage(const QString &rMessage); + + private: + int mCode; + QString mContext; + QString mMessage; + QString mSymbol; + QList mArgs; + QList mCausingErrors; + +#ifndef QT_NO_DATASTREAM + // Needs to be friend to stream objects + friend QDataStream &operator<<(QDataStream &rStream, + const LogError &rLogError); + friend QDataStream &operator>>(QDataStream &rStream, + LogError &rLogError); +#endif // QT_NO_DATASTREAM + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + +#ifndef QT_NO_DATASTREAM + /*! + * \relates LogError + * + * Writes the given error \a rLogError to the given stream \a rStream, + * and returns a reference to the stream. + */ + QDataStream &operator<<(QDataStream &rStream, + const LogError &rLogError); + + /*! + * \relates LogError + * + * Reads an error from the given stream \a rStream into the given + * error \a rLogError, and returns a reference to the stream. + */ + QDataStream &operator>>(QDataStream &rStream, + LogError &rLogError); +#endif // QT_NO_DATASTREAM + +#ifndef QT_NO_DEBUG_STREAM + /*! + * \relates LogError + * + * Writes all object member variables to the given debug stream \a debug and + * returns the stream. + * + * + * %LogError(code:7 context:"Log4Qt::FileAppender" + * message:"Unable to open file '%1' for appender '%2'" + * symbol:"APPENDER_OPENING_FILE_ERROR" + * args:(QVariant(QString, "G:\logs\client.log") , QVariant(QString, "Client FileAppender") ) + * translatedMessage: "Unable to open file '%1' for appender '%2'" ) + * + * + * \sa QDebug + */ + QDebug operator<<(QDebug debug, + const LogError &rLogError); +#endif // QT_NO_DEBUG_STREAM + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline int LogError::code() const + { return mCode; } + + inline QString LogError::context() const + { return mContext; } + + inline QString LogError::message() const + { return mMessage; } + + inline QString LogError::symbol() const + { return mSymbol; } + + inline void LogError::setCode(int code) + { mCode = code; } + + inline void LogError::setContext(const QString &rContext) + { mContext = rContext; } + + inline void LogError::setMessage(const QString &rMessage) + { mMessage = cleanMessage(rMessage); } + + inline void LogError::setSymbol(const QString &rSymbol) + { mSymbol = rSymbol; } + + inline LogError &LogError::addArg(const QVariant &rArg) + { mArgs << rArg; return *this; } + + inline LogError &LogError::addArg(int arg) + { mArgs << QVariant(arg); return *this; } + + inline LogError &LogError::addArg(const QString &rArg) + { mArgs << QVariant(rArg); return *this; } + + inline LogError &LogError::addCausingError(const LogError &rLogError) + { mCausingErrors << rLogError; return *this; } + + inline QList LogError::args() const + { return mArgs; } + + inline void LogError::clearArgs() + { mArgs.clear(); } + + inline void LogError::clearCausingErrors() + { mCausingErrors.clear(); } + + inline QList LogError::causingErrors() const + { return mCausingErrors; } + + inline bool LogError::isEmpty() const + { return mCode || !mMessage.isEmpty(); } + + inline QString LogError::messageWithArgs() const + { return insertArgs(message()); } + + inline QString LogError::translatedMessageWithArgs() const + { return insertArgs(translatedMessage()); } + + inline LogError &LogError::operator<<(const QVariant &rArg) + { return addArg(rArg); } + + inline LogError &LogError::operator<<(int arg) + { return addArg(arg); } + + inline LogError &LogError::operator<<(const QString &rArg) + { return addArg(rArg); } + + +} // namespace Log4Qt + + +Q_DECLARE_METATYPE(Log4Qt::LogError) +Q_DECLARE_TYPEINFO(Log4Qt::LogError, Q_MOVABLE_TYPE); + + +#endif // LOG4QT_ERROR_H diff --git a/src/log4qt/log4qt/helpers/logobject.cpp b/src/log4qt/log4qt/helpers/logobject.cpp new file mode 100644 index 0000000..44f1121 --- /dev/null +++ b/src/log4qt/log4qt/helpers/logobject.cpp @@ -0,0 +1,74 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: logobject.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/helpers/logobject.h" + +#include + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: LogObject + **************************************************************************/ + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, + const LogObject &rLogObject) + { + return rLogObject.debug(debug); + } +#endif // QT_NO_DEBUG_STREAM + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/helpers/logobject.h b/src/log4qt/log4qt/helpers/logobject.h new file mode 100644 index 0000000..1c4efaf --- /dev/null +++ b/src/log4qt/log4qt/helpers/logobject.h @@ -0,0 +1,218 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: logobject.h + * created: September 2007 + * author: Martin Heinrich + * + * + * changes: Sep 2008, Martin Heinrich: + * - Replaced usage of q_atomic_increment and q_atomic_decrement + * with QAtomicInt. + * Feb 2009, Martin Heinrich + * - Fixed a problem where the pParent parameter of the constructor + * was not passed on to the QObject constructor + * + * + * Copyright 2007 - 2009 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_LOGOBJECT_H +#define LOG4QT_LOGOBJECT_H + +#include "ukui-logmacros.h" + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include + +#include "log4qt/helpers/classlogger.h" +#if QT_VERSION >= QT_VERSION_CHECK(4, 4, 0) +# include +# ifndef Q_ATOMIC_INT_REFERENCE_COUNTING_IS_ALWAYS_NATIVE +# warning "QAtomicInt reference counting is not native. The class Log4Qt::LogObject is not thread-safe." +# endif +#endif + + +namespace Log4Qt +{ + + class Logger; + + /*! + * \brief The class LogObject is the common base class for many classes + * in the package. + * + * The class inherits QObject to allow its subclass to be accessed using + * the Qt property system. + * + * LogObject objects provide a reference counter. A reference to the + * object is established by calling retain() and freed by calling + * release(). The object will delete itself when the reference counter + * is decremented to 0. + * + * A class specific logger can be accessed over logger(). + * + * The class also implements generic streaming to QDebug. Streaming an + * object to QDebug will invoke debug() to create class specific output. + * + * \note All the functions declared in this class are thread-safe. + * + * \sa \ref Ownership "Object ownership", + * LOG4QT_DECLARE_QCLASS_LOGGER + */ + class LIBUKUILOG4QT_EXPORT LogObject : public QObject + { + Q_OBJECT + + public: + /*! + * Creates a LogObject which is a child of \a pObject. + */ + LogObject(QObject *pObject = 0); + + /*! + * Destroys the LogObject. + */ + virtual ~LogObject(); + + private: + LogObject(const LogObject &rOther); // Not implemented + LogObject &operator=(const LogObject &rOther); // Not implemented + + public: + /*! + * Returns the value of the reference counter. + */ + int referenceCount() const; + + /*! + * Decrements the reference count of the object. If the reference count + * count reaches zero and the object does not have a parent the object + * is deleted. + */ + void release(); + + /*! + * Increments the reference count of the object. + */ + void retain(); + + protected: + #ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream + * \a rDebug and returns the stream. + * + * The member function is used by + * QDebug operator<<(QDebug debug, const LogObject &rLogObject) to + * generate class specific output. + * + * \sa QDebug operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const = 0; + + // Needs to be friend to access internal data + friend QDebug operator<<(QDebug debug, + const LogObject &rLogObject); + #endif // QT_NO_DEBUG_STREAM + + /*! + * Returns a pointer to a Logger named after of the object. + * + * \sa Logger::logger(const char *pName) + */ + Logger* logger() const; + + private: +#if QT_VERSION < QT_VERSION_CHECK(4, 4, 0) + volatile int mReferenceCount; +#else + mutable QAtomicInt mReferenceCount; +#endif + mutable ClassLogger mLog4QtClassLogger; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + #ifndef QT_NO_DEBUG_STREAM + /*! + * \relates LogObject + * + * Writes all object member variables to the given debug stream \a debug + * and returns the stream. + * + * To handle sub-classing the function uses the virtual member function + * debug(). This allows each class to generate its own output. + * + * \sa QDebug, debug() + */ + QDebug operator<<(QDebug debug, + const LogObject &rLogObject); + #endif + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline LogObject::LogObject(QObject *pParent) : + QObject(pParent), + mReferenceCount() + {} + + inline LogObject::~LogObject() + {} + + inline int LogObject::referenceCount() const +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + { return mReferenceCount; } +#else + { return mReferenceCount.loadAcquire(); } +#endif + + inline void LogObject::release() +#if QT_VERSION < QT_VERSION_CHECK(4, 4, 0) + { if ((q_atomic_decrement(&mReferenceCount) == 0) && !parent()) + delete(this); } +#else + { if (!mReferenceCount.deref()) + delete(this); } +#endif + + inline void LogObject::retain() +#if QT_VERSION < QT_VERSION_CHECK(4, 4, 0) + { q_atomic_increment(&mReferenceCount); } +#else + { mReferenceCount.ref(); } +#endif + + inline Logger *LogObject::logger() const + { return mLog4QtClassLogger.logger(this); } + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::LogObject, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_LOGOBJECT_H diff --git a/src/log4qt/log4qt/helpers/logobjectptr.cpp b/src/log4qt/log4qt/helpers/logobjectptr.cpp new file mode 100644 index 0000000..8084a79 --- /dev/null +++ b/src/log4qt/log4qt/helpers/logobjectptr.cpp @@ -0,0 +1,65 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: logobjectptr.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/helpers/logobjectptr.h" + +#include + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: LogObjectPtr + **************************************************************************/ + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/helpers/logobjectptr.h b/src/log4qt/log4qt/helpers/logobjectptr.h new file mode 100644 index 0000000..7b86508 --- /dev/null +++ b/src/log4qt/log4qt/helpers/logobjectptr.h @@ -0,0 +1,188 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: logobjectptr.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_LOGOBJECTPTR_H +#define LOG4QT_LOGOBJECTPTR_H + +#include "ukui-logmacros.h" + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/helpers/logobject.h" + +namespace Log4Qt +{ + /*! + * \brief The class LogObjectPtr implements automatic reference counting + * for LogObject objects. + */ + template + class LIBUKUILOG4QT_EXPORT LogObjectPtr + { + public: + /*! + * Constructs a 0 LogObject pointer. + */ + LogObjectPtr(); + + /*! + * Constructs a LogObject pointer that points to the same object then + * \a rOther. The reference counter of the object is incremented by + * one. + */ + LogObjectPtr(const LogObjectPtr &rOther); + + /*! + * Constructs a LogObject pointer that points to the object + * \a LogObject. The reference counter of the object is incremented by + * one. + */ + LogObjectPtr(T *pLogObject); + + /*! + * Assignment operator. Sets the LogObject pointer to point to the + * same object that \a rOther points to. The reference counter of the + * object the LogObjectPtr pointed to before the assignment is + * decremented by one. The reference counter of the object \a rOther + * is pointing to is incremented by one. + */ + LogObjectPtr &operator=(const LogObjectPtr &rOther); + + /*! + * Destructs the object. The reference counter of the object the + * LogObjectPtr points to is decremented by one. + */ + ~LogObjectPtr(); + + /*! + * Assignment operator. Sets the LogObject pointer to point to the + * object \a pLogObject. The reference counter of the object the + * LogObjectPtr pointed to before the assignment is decremented by + * one. The reference counter of the object \a pLogObject is pointing + * to is incremented by one. + */ + LogObjectPtr &operator=(T *pLogObject); + + /*! + * Arrow operator. Returns the LogObject the object points to. + */ + T *operator->() const; + + /*! + * Dereference operator. Returns a pointer to the LogObject the + * object points to. + */ + T &operator*() const; + + /*! + * Cast operator. Cast the object to the LogObject the object points + * to. + */ + operator T*() const; + + private: + void retain() const; + void release() const; + + private: + T *mpLogObject; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + template + inline LogObjectPtr::LogObjectPtr() : + mpLogObject(0) + {} + + template + inline LogObjectPtr::LogObjectPtr(const LogObjectPtr &rOther) : + mpLogObject(rOther.mpLogObject) + { retain(); } + + template + inline LogObjectPtr::LogObjectPtr(T *pLogObject) : + mpLogObject(pLogObject) + { retain(); } + + template + inline LogObjectPtr &LogObjectPtr::operator=(const LogObjectPtr &rOther) + { rOther.retain(); + release(); + mpLogObject = rOther.mpLogObject; + return *this; } + + template + inline LogObjectPtr::~LogObjectPtr() + { release(); } + + template + inline LogObjectPtr &LogObjectPtr::operator=(T *pLogObject) + { if (pLogObject) + reinterpret_cast(pLogObject)->retain(); + release(); + mpLogObject = pLogObject; + return *this; } + + template + inline T *LogObjectPtr::operator->() const + { return mpLogObject; } + + template + inline T &LogObjectPtr::operator*() const + { return *mpLogObject; } + + template + inline LogObjectPtr::operator T*() const + { return mpLogObject; } + + template + inline void LogObjectPtr::retain() const + { if (mpLogObject) + reinterpret_cast(mpLogObject)->retain(); } + + template + inline void LogObjectPtr::release() const + { + if (mpLogObject) + reinterpret_cast(mpLogObject)->release(); + } + +} // namespace Log4Qt + + +//Q_DECLARE_TYPEINFO(Log4Qt::LogObjectPtr, Q_MOVABLE_TYPE); // Declare within T + + +#endif // LOG4QT_LOGOBJECTPTR_H diff --git a/src/log4qt/log4qt/helpers/optionconverter.cpp b/src/log4qt/log4qt/helpers/optionconverter.cpp new file mode 100644 index 0000000..a0a7b34 --- /dev/null +++ b/src/log4qt/log4qt/helpers/optionconverter.cpp @@ -0,0 +1,315 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: optionconverter.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * changes Feb 2009, Martin Heinrich + * - Fixed a problem were OptionConverter::toBoolean would not + * return the default value, if the conversion fails. + * + * + * Copyright 2007 - 2009 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/helpers/optionconverter.h" + +#include +#include "log4qt/helpers/logerror.h" +#include "log4qt/helpers/properties.h" +#include "log4qt/logger.h" +#include "log4qt/consoleappender.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + LOG4QT_DECLARE_STATIC_LOGGER(logger, Log4Qt::OptionConverter) + + + + /************************************************************************** + * Class implementation: OptionConverter + **************************************************************************/ + + + QString OptionConverter::findAndSubst(const Properties &rProperties, + const QString &rKey) + { + QString value = rProperties.property(rKey); + if (value.isNull()) + return value; + + const QString begin_subst = QLatin1String("${"); + const QString end_subst = QLatin1String("}"); + const int begin_length = begin_subst.length(); + const int end_length = end_subst.length(); + + // Don't return a null string, the null string indicates that the + // property key does not exist. + QString result = QLatin1String(""); + + int i = 0; + int begin; + int end; + while (i < value.length()) + { + begin = value.indexOf(begin_subst, i); + if (begin == -1) + { + result += value.mid(i); + i = value.length(); + } + else + { + result += value.mid(i, begin - i); + end = value.indexOf(end_subst, i + begin_length); + if (end == -1) + { + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Missing closing bracket for opening bracket at %1. Invalid substitution in value %2."), + CONFIGURATOR_INVALID_SUBSTITUTION_ERROR, + "Log4Qt::OptionConverter"); + e << begin << value; + logger()->error(e); + return result; + } + else + { + result += findAndSubst(rProperties, value.mid(begin + begin_length, end - begin - end_length - 1)); + i = end + end_length; + } + } + } + return result; + } + + + QString OptionConverter::classNameJavaToCpp(const QString &rClassName) + { + const QLatin1String java_class_delimiter("."); + const QLatin1String cpp_class_delimiter("::"); + + QString result = rClassName; + return result.replace(java_class_delimiter, cpp_class_delimiter); + } + + + bool OptionConverter::toBoolean(const QString &rOption, + bool *p_ok) + { + const QLatin1String str_true("true"); + const QLatin1String str_enabled("enabled"); + const QLatin1String str_one("1"); + const QLatin1String str_false("false"); + const QLatin1String str_disabled("disabled"); + const QLatin1String str_zero("0"); + + if (p_ok) + *p_ok = true; + QString s = rOption.trimmed().toLower(); + if (s == str_true || s == str_enabled || s == str_one) + return true; + if (s == str_false || s == str_disabled || s == str_zero) + return false; + + if (p_ok) + *p_ok = false; + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Invalid option string '%1' for a boolean"), + CONFIGURATOR_INVALID_OPTION_ERROR, + "Log4Qt::OptionConverter"); + e << rOption; + logger()->error(e); + return false; + } + + + bool OptionConverter::toBoolean(const QString &rOption, + bool default_value) + { + bool ok; + bool result = toBoolean(rOption, &ok); + if (ok) + return result; + else + return default_value; + } + + qint64 OptionConverter::toFileSize(const QString &rOption, + bool *p_ok) + { + // - Search for unit + // - Convert characters befor unit to int + // - Error, if + // - the conversion failed + // - the value < 0 + // - there is text after the unit characters + + if (p_ok) + *p_ok = false; + QString s = rOption.trimmed().toLower(); + qint64 f = 1; + int i; + i = s.indexOf(QLatin1String("kb")); + if (i >= 0) + f = 1024; + else + { + i = s.indexOf(QLatin1String("mb")); + if (i >= 0) + f = 1024 * 1024; + else + { + i = s.indexOf(QLatin1String("gb")); + if (i >= 0) + f = 1024 * 1024 * 1024; + } + } + if (i < 0) + i = s.length(); + bool ok; + qint64 value = s.left(i).toLongLong(&ok); + if (!ok || value < 0 || s.length() > i + 2) + { + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Invalid option string '%1' for a file size"), + CONFIGURATOR_INVALID_OPTION_ERROR, + "Log4Qt::OptionConverter"); + e << rOption; + logger()->error(e); + return 0; + } + if (p_ok) + *p_ok = true; + return value * f; + } + + + int OptionConverter::toInt(const QString &rOption, + bool *p_ok) + { + int value = rOption.trimmed().toInt(p_ok); + if (*p_ok) + return value; + + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Invalid option string '%1' for an integer"), + CONFIGURATOR_INVALID_OPTION_ERROR, + "Log4Qt::OptionConverter"); + e << rOption; + logger()->error(e); + return 0; + } + + qint64 OptionConverter::toQInt64(const QString &rOption, + bool *p_ok) + { + int value = rOption.trimmed().toLongLong(p_ok); + if (*p_ok) + return value; + + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Invalid option string '%1' for an qint64"), + CONFIGURATOR_INVALID_OPTION_ERROR, + "Log4Qt::OptionConverter"); + e << rOption; + logger()->error(e); + return 0; + } + + Level OptionConverter::toLevel(const QString &rOption, + bool *p_ok) + { + bool ok; + Level level = Level::fromString(rOption.toUpper().trimmed(), &ok); + if (p_ok) + *p_ok = ok; + if (ok) + return level; + + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Invalid option string '%1' for a level"), + CONFIGURATOR_INVALID_OPTION_ERROR, + "Log4Qt::OptionConverter"); + e << rOption; + logger()->error(e); + return level; + } + + + Level OptionConverter::toLevel(const QString &rOption, + const Level &rDefaultValue) + { + bool ok; + Level result = toLevel(rOption, &ok); + if (ok) + return result; + else + return rDefaultValue; + } + + + int OptionConverter::toTarget(const QString &rOption, + bool *p_ok) + { + const QLatin1String java_stdout("system.out"); + const QLatin1String cpp_stdout("stdout_target"); + const QLatin1String java_stderr("system.err"); + const QLatin1String cpp_stderr("stderr_target"); + + if (p_ok) + *p_ok = true; + QString s = rOption.trimmed().toLower(); + if (s == java_stdout || s == cpp_stdout) + return ConsoleAppender::STDOUT_TARGET; + if (s == java_stderr || s == cpp_stderr) + return ConsoleAppender::STDERR_TARGET; + + if (p_ok) + *p_ok = false; + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Invalid option string '%1' for a target"), + CONFIGURATOR_INVALID_OPTION_ERROR, + "Log4Qt::OptionConverter"); + e << rOption; + logger()->error(e); + return ConsoleAppender::STDOUT_TARGET; + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/helpers/optionconverter.h b/src/log4qt/log4qt/helpers/optionconverter.h new file mode 100644 index 0000000..c29cbda --- /dev/null +++ b/src/log4qt/log4qt/helpers/optionconverter.h @@ -0,0 +1,151 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: optionconverter.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_OPTIONCONVERTER_H +#define LOG4QT_OPTIONCONVERTER_H + +#include "ukui-logmacros.h" + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#include "log4qt/level.h" + +namespace Log4Qt +{ + class Properties; + + /*! + * \brief The class OptionConverter provides functions to convert strings + * to property values. + */ + class LIBUKUILOG4QT_EXPORT OptionConverter + { + private: + OptionConverter(); + OptionConverter(const OptionConverter &rOther); // Not implemented + // virtual ~OptionConverter(); // Use compiler default + OptionConverter &operator=(const OptionConverter &rOther); // Not implemented + + public: + static QString findAndSubst(const Properties &rProperties, + const QString &rKey); + + /*! + * Returns the JAVA class name \a rClassName as C++ class name by + * replacing all . characters with ::. + */ + static QString classNameJavaToCpp(const QString &rClassName); + + /*! + * Converts the option \a rOption to a boolean value. Valid strings + * for true are "true", "enabled" and "1". Valid strings + * for false are "false", "disabled" and "0". If the conversion is + * successful, the target is returned and \a p_ok is set to true. + * Otherwise an error is written to the log, \a p_ok is set to false + * and false is returned. + */ + static bool toBoolean(const QString &rOption, + bool *p_ok = 0); + + static bool toBoolean(const QString &rOption, + bool default_value); + + /*! + * Converts the option string \a rOption to a file size. The string can + * be a positive integer followed by an optional unit suffix "KB", "MB" + * or "GB". If a unit suffix is specified the the integer is + * interpreted as kilobytes, megabytes or gigabytes. If the conversion + * is successful, the size is returned and \a p_ok is set to true. + * Otherwise an error is written to the log, \a p_ok is set to false + * and 0 is returned. + */ + static qint64 toFileSize(const QString &rOption, + bool *p_ok = 0); + + /*! + * Converts the option \a rOption to a integer value using + * QString::toInt(). If the conversion is successful, the integer is + * returned and \a p_ok is set to true. Otherwise an error is written + * to the log, \a p_ok is set to false and 0 is returned. + */ + static int toInt(const QString &rOption, + bool *p_ok = 0); + + /*! + * Converts the option \a rOption to a qint64 value using + * QString::toLongLong(). If the conversion is successful, the qint64 is + * returned and \a p_ok is set to true. Otherwise an error is written + * to the log, \a p_ok is set to false and 0 is returned. + */ + static qint64 toQInt64(const QString &rOption, + bool *p_ok = 0); + + /*! + * Converts the option \a rOption to a level value using + * Level::fromString(). If the conversion is successful, the level + * is returned and \a p_ok is set to true. Otherwise an error is + * written to the log, \a p_ok is set to false and a level with + * the value Level::NULL_INT is returned. + * + * \sa Level::fromString() + */ + static Level toLevel(const QString &rOption, + bool *p_ok = 0); + + static Level toLevel(const QString &rOption, + const Level &rDefaultValue); + + /*! + * Converts the option \a rOption to a ConsoleAppender::Target value. + * Valid strings for \a rOption are "System.out", "STDOUT_TARGET", + * "System.err" and "STDERR_TARGET". If the conversion is successful, + * the target is returned and \a p_ok is set to true. Otherwise an + * error is written to the log, \a p_ok is set to false and + * ConsoleAppender::STDOUT_TARGET is returned. + */ + static int toTarget(const QString &rOption, + bool *p_ok = 0); + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + +} // namespace Log4Qt + + +Q_DECLARE_TYPEINFO(Log4Qt::OptionConverter, Q_MOVABLE_TYPE); + + +#endif // LOG4QT_OPTIONCONVERTER_H diff --git a/src/log4qt/log4qt/helpers/patternformatter.cpp b/src/log4qt/log4qt/helpers/patternformatter.cpp new file mode 100644 index 0000000..60f5271 --- /dev/null +++ b/src/log4qt/log4qt/helpers/patternformatter.cpp @@ -0,0 +1,893 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: patternformatter.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * changes Feb 2009, Martin Heinrich + * - Fixed VS 2008 unreferenced formal parameter warning by using + * Q_UNUSED in LiteralPatternConverter::convert. + * + * + * Copyright 2007 - 2009 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/helpers/patternformatter.h" + +#include +#include +#include +#include "log4qt/helpers/datetime.h" +#include "log4qt/helpers/logerror.h" +#include "log4qt/layout.h" +#include "log4qt/logger.h" +#include "log4qt/loggingevent.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + *Declarations + **************************************************************************/ + + + /*! + * \brief The class FormattingInfo stores the formatting modifier for a + * pattern converter. + * + * \sa PatternConverter + */ + class FormattingInfo + { + public: + FormattingInfo() + { clear(); } + // FormattingInfo(const FormattingInfo &rOther); // Use compiler default + // virtual ~FormattingInfo(); // Use compiler default + // FormattingInfo &operator=(const FormattingInfo &rOther); // Use compiler default + + void clear(); + static QString intToString(int i); + + public: + int mMinLength; + int mMaxLength; + bool mLeftAligned; + }; + + + /*! + * \brief The class PatternConverter is the abstract base class for all + * pattern converters. + * + * PatternConverter handles the minimum and maximum modifier for a + * conversion character. The actual conversion is by calling the + * convert() member function of the derived class. + * + * \sa PatternLayout::format() + */ + class PatternConverter + { + public: + PatternConverter(const FormattingInfo &rFormattingInfo = FormattingInfo()) : + mFormattingInfo(rFormattingInfo) + {}; + virtual ~PatternConverter() + {}; + private: + PatternConverter(const PatternConverter &rOther); // Not implemented + PatternConverter &operator=(const PatternConverter &rOther); // Not implemented + + public: + void format(QString &rFormat, const LoggingEvent &rLoggingEvent) const; + + protected: + virtual QString convert(const LoggingEvent &rLoggingEvent) const = 0; + #ifndef QT_NO_DEBUG_STREAM + virtual QDebug debug(QDebug &rDebug) const = 0; + friend QDebug operator<<(QDebug, const PatternConverter &rPatternConverter); + #endif + + protected: + FormattingInfo mFormattingInfo; + }; + + + /*! + * \brief The class BasicPatternConverter converts several members of a + * LoggingEvent to a string. + * + * BasicPatternConverter is used by PatternLayout to convert members that + * do not reuquire additional formatting to a string as part of formatting + * the LoggingEvent. It handles the following conversion characters: + * 'm', 'p', 't', 'x' + * + * \sa PatternLayout::format() + * \sa PatternConverter::format() + */ + class BasicPatternConverter : public PatternConverter + { + public: + enum Type { + MESSAGE_CONVERTER, + NDC_CONVERTER, + LEVEL_CONVERTER, + THREAD_CONVERTER, + }; + + public: + BasicPatternConverter(const FormattingInfo &rFormattingInfo, + Type type) : + PatternConverter(rFormattingInfo), + mType(type) + {}; + // virtual ~BasicPatternConverter(); // Use compiler default + private: + BasicPatternConverter(const BasicPatternConverter &rOther); // Not implemented + BasicPatternConverter &operator=(const BasicPatternConverter &rOther); // Not implemented + + protected: + virtual QString convert(const LoggingEvent &rLoggingEvent) const; + #ifndef QT_NO_DEBUG_STREAM + virtual QDebug debug(QDebug &rDebug) const; + #endif + + private: + Type mType; + }; + + + /*! + * \brief The class DatePatternConverter converts the time stamp of a + * LoggingEvent to a string. + * + * DatePatternConverter is used by PatternLayout to convert the time stamp + * of a LoggingEvent to a string as part of formatting the LoggingEvent. + * It handles the 'd' and 'r' conversion character. + * + * \sa PatternLayout::format() + * \sa PatternConverter::format() + */ + class DatePatternConverter : public PatternConverter + { + public: + DatePatternConverter(const FormattingInfo &rFormattingInfo, + const QString &rFormat) : + PatternConverter(rFormattingInfo), + mFormat(rFormat) + {}; + // virtual ~DatePatternConverter(); // Use compiler default + private: + DatePatternConverter(const DatePatternConverter &rOther); // Not implemented + DatePatternConverter &operator=(const DatePatternConverter &rOther); // Not implemented + + protected: + virtual QString convert(const LoggingEvent &rLoggingEvent) const; + #ifndef QT_NO_DEBUG_STREAM + virtual QDebug debug(QDebug &rDebug) const; + #endif + + private: + QString mFormat; + }; + + + /*! + * \brief The class LiteralPatternConverter provides string literals. + * + * LiteralPatternConverter is used by PatternLayout to embed string + * literals as part of formatting the LoggingEvent. It handles string + * literals and the 'n' conversion character. + * + * \sa PatternLayout::format() + * \sa PatternConverter::format() + */ + class LiteralPatternConverter : public PatternConverter + { + public: + LiteralPatternConverter(const QString &rLiteral) : + PatternConverter(), + mLiteral(rLiteral) + {}; + // virtual ~LiteralPatternConverter(); // Use compiler default + private: + LiteralPatternConverter(const LiteralPatternConverter &rOther); // Not implemented + LiteralPatternConverter &operator=(const LiteralPatternConverter &rOther); // Not implemented + + protected: + virtual QString convert(const LoggingEvent &rLoggingEvent) const; + #ifndef QT_NO_DEBUG_STREAM + virtual QDebug debug(QDebug &rDebug) const; + #endif + + private: + QString mLiteral; + }; + + + /*! + * \brief The class LoggerPatternConverter converts the Logger name of a + * LoggingEvent to a string. + * + * LoggerPatternConverter is used by PatternLayout to convert the Logger + * name of a LoggingEvent to a string as part of formatting the + * LoggingEvent. It handles the 'c' conversion character. + * + * \sa PatternLayout::format() + * \sa PatternConverter::format() + */ + class LoggerPatternConverter : public PatternConverter + { + public: + LoggerPatternConverter(const FormattingInfo &rFormattingInfo, + int precision) : + PatternConverter(rFormattingInfo), + mPrecision(precision) + {}; + // virtual ~LoggerPatternConverter(); // Use compiler default + private: + LoggerPatternConverter(const LoggerPatternConverter &rOther); // Not implemented + LoggerPatternConverter &operator=(const LoggerPatternConverter &rOther); // Not implemented + + protected: + virtual QString convert(const LoggingEvent &rLoggingEvent) const; + #ifndef QT_NO_DEBUG_STREAM + virtual QDebug debug(QDebug &rDebug) const; + #endif + + private: + int mPrecision; + }; + + + + /*! + * \brief The class MDCPatternConverter converts the MDC data of a + * LoggingEvent to a string. + * + * MDCPatternConverter is used by PatternLayout to convert the MDC data of + * a LoggingEvent to a string as part of formatting the LoggingEvent. It + * handles the 'X' conversion character. + * + * \sa PatternLayout::format() + * \sa PatternConverter::format() + */ + class MDCPatternConverter : public PatternConverter + { + public: + MDCPatternConverter(const FormattingInfo &rFormattingInfo, + const QString &rKey) : + PatternConverter(rFormattingInfo), + mKey(rKey) + {}; + // virtual ~MDCPatternConverter(); // Use compiler default + private: + MDCPatternConverter(const MDCPatternConverter &rOther); // Not implemented + MDCPatternConverter &operator=(const MDCPatternConverter &rOther); // Not implemented + + protected: + virtual QString convert(const LoggingEvent &rLoggingEvent) const; + #ifndef QT_NO_DEBUG_STREAM + virtual QDebug debug(QDebug &rDebug) const; + #endif + + private: + QString mKey; + }; + + + #ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug, const FormattingInfo &rFormattingInfo); + #endif + + + #ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug, const PatternConverter &rPatternConverter); + #endif + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + LOG4QT_DECLARE_STATIC_LOGGER(logger, Log4Qt::PatternFormatter) + + + + /************************************************************************** + * Class implementation: PatternFormatter + **************************************************************************/ + + + PatternFormatter::PatternFormatter(const QString &rPattern) : + mIgnoreCharacters(QLatin1String("CFlLM")), + mConversionCharacters(QLatin1String("cdmprtxX")), + mOptionCharacters(QLatin1String("cd")), + mPattern(rPattern), + mPatternConverters() + { + parse(); + } + + + PatternFormatter::~PatternFormatter() + { + PatternConverter *p_converter; + Q_FOREACH(p_converter, mPatternConverters) + delete p_converter; + } + + + QString PatternFormatter::format(const LoggingEvent &rLoggingEvent) const + { + QString result; + PatternConverter *p_converter; + Q_FOREACH(p_converter, mPatternConverters) + p_converter->format(result, rLoggingEvent); + return result; + } + + + bool PatternFormatter::addDigit(const QChar &rDigit, + int &rValue) + { + if (!rDigit.isDigit()) + return false; + + int digit_value = rDigit.digitValue(); + if (rValue > (INT_MAX - digit_value) / 10) + rValue = INT_MAX; + else + rValue = rValue * 10 + digit_value; + return true; + } + + + void PatternFormatter::createConverter(const QChar &rChar, + const FormattingInfo &rFormattingInfo, + const QString &rOption) + { + Q_ASSERT_X(mConversionCharacters.indexOf(rChar) >= 0, "PatternFormatter::createConverter", "Unknown conversion character" ); + + LogError e("Creating Converter for character '%1' min %2, max %3, left %4 and option '%5'"); + e << QString(rChar) + << FormattingInfo::intToString(rFormattingInfo.mMinLength) + << FormattingInfo::intToString(rFormattingInfo.mMaxLength) + << rFormattingInfo.mLeftAligned + << rOption; + logger()->trace(e); + + switch (rChar.toLatin1()) + { + case 'c': + mPatternConverters << new LoggerPatternConverter(rFormattingInfo, + parseIntegerOption(rOption)); + break; + case 'd': + { + QString option = rOption; + if (rOption.isEmpty()) + option = QLatin1String("ISO8601"); + mPatternConverters << new DatePatternConverter(rFormattingInfo, + option); + break; + } + case 'm': + mPatternConverters << new BasicPatternConverter(rFormattingInfo, + BasicPatternConverter::MESSAGE_CONVERTER); + break; + case 'p': + mPatternConverters << new BasicPatternConverter(rFormattingInfo, + BasicPatternConverter::LEVEL_CONVERTER); + break; + case 'r': + mPatternConverters << new DatePatternConverter(rFormattingInfo, + QLatin1String("TIME_RELATIVE")); + break; + case 't': + mPatternConverters << new BasicPatternConverter(rFormattingInfo, + BasicPatternConverter::THREAD_CONVERTER); + break; + case 'x': + mPatternConverters << new BasicPatternConverter(rFormattingInfo, + BasicPatternConverter::NDC_CONVERTER); + break; + case 'X': + mPatternConverters << new MDCPatternConverter(rFormattingInfo, + rOption); + break; + default: + Q_ASSERT_X(false, "PatternFormatter::createConverter", "Unknown pattern character"); + } + } + + + void PatternFormatter::createLiteralConverter(const QString &rLiteral) + { + logger()->trace("Creating literal LiteralConverter with Literal '%1'", + rLiteral); + mPatternConverters << new LiteralPatternConverter(rLiteral); + } + + + void PatternFormatter::parse() + { + enum State { + LITERAL_STATE, + ESCAPE_STATE, + MIN_STATE, + DOT_STATE, + MAX_STATE, + CHARACTER_STATE, + POSSIBLEOPTION_STATE, + OPTION_STATE + }; + + int i = 0; + QChar c; + char ch; + State state = LITERAL_STATE; + FormattingInfo formatting_info; + QString literal; + int converter_start; + int option_start; + while (i < mPattern.length()) + { + // i points to the current character + // c contains the current character + // ch contains the Latin1 equivalent of the current character + // i is incremented at the end of the loop to consume the character + // continue is used to change state without consuming the character + + c = mPattern.at(i); + ch = c.toLatin1(); + switch (state) + { + case LITERAL_STATE: + if (ch == '%') + { + formatting_info.clear(); + converter_start = i; + state = ESCAPE_STATE; + } else + literal += c; + break; + case ESCAPE_STATE: + if (ch == '%') + { + literal += c; + state = LITERAL_STATE; + } + else if (ch == 'n') + { + literal += Layout::endOfLine(); + state = LITERAL_STATE; + } + else + { + if (!literal.isEmpty()) + { + createLiteralConverter(literal); + literal.clear(); + } + if (ch == '-') + formatting_info.mLeftAligned = true; + else if (c.isDigit()) + { + formatting_info.mMinLength = c.digitValue(); + state = MIN_STATE; + } + else if (ch == '.') + state = DOT_STATE; + else + { + state = CHARACTER_STATE; + continue; + } + } + break; + case MIN_STATE: + if (!addDigit(c, formatting_info.mMinLength)) + { + if (ch == '.') + state = DOT_STATE; + else + { + state = CHARACTER_STATE; + continue; + } + } + break; + case DOT_STATE: + if (c.isDigit()) + { + formatting_info.mMaxLength = c.digitValue(); + state = MAX_STATE; + } + else + { + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Found character '%1' where digit was expected."), + LAYOUT_EXPECTED_DIGIT_ERROR, + "Log4Qt::PatternFormatter"); + e << QString(c); + logger()->error(e); + } + break; + case MAX_STATE: + if (!addDigit(c, formatting_info.mMaxLength)) + { + state = CHARACTER_STATE; + continue; + } + break; + case CHARACTER_STATE: + if (mIgnoreCharacters.indexOf(c) >= 0) + state = LITERAL_STATE; + else if (mOptionCharacters.indexOf(c) >= 0) + state = POSSIBLEOPTION_STATE; + else if (mConversionCharacters.indexOf(c) >= 0) + { + createConverter(c, formatting_info); + state = LITERAL_STATE; + } + else + { + logger()->warn("Invalid conversion character '%1' at %2 in pattern '%3'", + c, i, mPattern); + createLiteralConverter(mPattern.mid(converter_start, i - converter_start + 1)); + state = LITERAL_STATE; + } + break; + case POSSIBLEOPTION_STATE: + if (ch == '{') + { + option_start = i; + state = OPTION_STATE; + } + else + { + createConverter(mPattern.at(i - 1), + formatting_info); + state = LITERAL_STATE; + continue; + } + break; + case OPTION_STATE: + if (ch == '}') + { + createConverter(mPattern.at(option_start - 1), + formatting_info, + mPattern.mid(option_start + 1, i - option_start - 1)); + state = LITERAL_STATE; + } + break; + default: + Q_ASSERT_X(false, "PatternFormatter::parse()", "Unknown parsing state constant"); + state = LITERAL_STATE; + } + i++; + } + + if (state != LITERAL_STATE) + { + logger()->warn("Unexptected end of pattern '%1'", mPattern); + if (state == ESCAPE_STATE) + literal += c; + else + literal += mPattern.mid(converter_start); + } + + if (!literal.isEmpty()) + createLiteralConverter(literal); + } + + + int PatternFormatter::parseIntegerOption(const QString &rOption) + { + if (rOption.isEmpty()) + return 0; + + bool ok; + int result = rOption.toInt(&ok); + if (!ok) + { + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Option '%1' cannot be converted into an integer"), + LAYOUT_OPTION_IS_NOT_INTEGER_ERROR, + "Log4Qt::PatterFormatter"); + e << rOption; + logger()->error(e); + } + if (result < 0) + { + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Option %1 isn't a positive integer"), + LAYOUT_INTEGER_IS_NOT_POSITIVE_ERROR, + "Log4Qt::PatterFormatter"); + e << result; + logger()->error(e); + result = 0; + } + return result; + } + + + /************************************************************************** + * Class implementation: FormattingInfo + **************************************************************************/ + + + void FormattingInfo::clear() + { + mMinLength = 0; + mMaxLength = INT_MAX; + mLeftAligned = false; + }; + + + QString FormattingInfo::intToString(int i) + { + if (i == INT_MAX) + return QLatin1String("INT_MAX"); + else + return QString::number(i); + } + + + + /************************************************************************** + * Class implementation: PatternConverter + **************************************************************************/ + + + void PatternConverter::format(QString &rFormat, const LoggingEvent &rLoggingEvent) const + { + const QLatin1Char space(' '); + QString s = convert(rLoggingEvent); + + if (s.length() > mFormattingInfo.mMaxLength) + rFormat += s.left(mFormattingInfo.mMaxLength); + else if (mFormattingInfo.mLeftAligned) + rFormat += s.leftJustified(mFormattingInfo.mMinLength, space, false); + else + rFormat += s.rightJustified(mFormattingInfo.mMinLength, space, false); + } + + + + /************************************************************************** + * Class implementation: BasicPatternConverter + **************************************************************************/ + + + QString BasicPatternConverter::convert(const LoggingEvent &rLoggingEvent) const + { + switch (mType) + { + case MESSAGE_CONVERTER: + return rLoggingEvent.message(); + break; + case NDC_CONVERTER: + return rLoggingEvent.ndc(); + break; + case LEVEL_CONVERTER: + return rLoggingEvent.level().toString(); + break; + case THREAD_CONVERTER: + return rLoggingEvent.threadName(); + break; + default: + Q_ASSERT_X(false, "BasicPatternConverter::convert()", "Unkown type constant"); + return QString(); + } + } + + + QDebug BasicPatternConverter::debug(QDebug &rDebug) const + { + QString type; + switch (mType) + { + case MESSAGE_CONVERTER: + type = QLatin1String("MESSAGE_CONVERTER"); + break; + case NDC_CONVERTER: + type = QLatin1String("NDC_CONVERTER"); + break; + case LEVEL_CONVERTER: + type = QLatin1String("LEVEL_CONVERTER"); + break; + case THREAD_CONVERTER: + type = QLatin1String("THREAD_CONVERTER"); + break; + default: + Q_ASSERT_X(false, "BasicPatternConverter::debug()", "Unkown type constant"); + } + rDebug.nospace() << "BasicPatternConverter(" + << mFormattingInfo + << "type:" << type + << ")"; + return rDebug.space(); + } + + + + /************************************************************************** + * Class implementation: DatePatternConverter + **************************************************************************/ + + + QString DatePatternConverter::convert(const LoggingEvent &rLoggingEvent) const + { + return DateTime::fromMilliSeconds(rLoggingEvent.timeStamp()).toString(mFormat); + } + + + QDebug DatePatternConverter::debug(QDebug &rDebug) const + { + rDebug.nospace() << "DatePatternConverter(" + << mFormattingInfo + << "format:" << mFormat + << ")"; + return rDebug.space(); + } + + + + /************************************************************************** + * Class implementation: LiteralPatternConverter + **************************************************************************/ + + + QString LiteralPatternConverter::convert(const LoggingEvent &rLoggingEvent) const + { + Q_UNUSED(rLoggingEvent); + return mLiteral; + }; + + + QDebug LiteralPatternConverter::debug(QDebug &rDebug) const + { + rDebug.nospace() << "LiteralPatternConverter(" + << mFormattingInfo + << "literal:" << mLiteral + << ")"; + return rDebug.space(); + } + + + + /************************************************************************** + * Class implementation: LoggerPatternConverter + **************************************************************************/ + + + QString LoggerPatternConverter::convert(const LoggingEvent &rLoggingEvent) const + { + if (!rLoggingEvent.logger()) + return QString(); + QString name = rLoggingEvent.logger()->name(); + if (mPrecision <= 0 || (name.isEmpty())) + return name; + + const QString separator(QLatin1String("::")); + + int i = mPrecision; + int begin = name.length(); + while ((i > 0) && (begin >= 0)) + { + begin = name.lastIndexOf(separator, begin - name.length() - 1); + i--; + } + if (begin < 0) + begin = 0; + else + begin += 2; + return name.mid(begin); + } + + + QDebug LoggerPatternConverter::debug(QDebug &rDebug) const + { + rDebug.nospace() << "LoggerPatternConverter(" + << mFormattingInfo + << "precision:" << mPrecision + << ")"; + return rDebug.space(); + } + + + + /****************************************************************************** + * Class implementation: MDCPatternConverter + ******************************************************************************/ + + + QString MDCPatternConverter::convert(const LoggingEvent &rLoggingEvent) const + { + return rLoggingEvent.mdc().value(mKey); + }; + + + QDebug MDCPatternConverter::debug(QDebug &rDebug) const + { + rDebug.nospace() << "MDCPatternConverter(" + << mFormattingInfo + << "key:" << mKey + << ")"; + return rDebug.space(); + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + + #ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, const PatternFormatter &rPatternFormatter) + { + debug.nospace() << "PatternFormatter(" + << "pattern:" << rPatternFormatter.mPattern << " " + << "converters:("; + int i; + for (i = 0; i < rPatternFormatter.mPatternConverters.size(); i++) + { + if (i > 0) + debug.nospace() << ", "; + debug.nospace() << *rPatternFormatter.mPatternConverters.at(i); + } + debug.nospace() << ") )"; + return debug.space(); + } + #endif + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, const FormattingInfo &rFormattingInfo) + { + debug.nospace() << "FormattingInfo(" + << "min:" << FormattingInfo::intToString(rFormattingInfo.mMinLength) << " " + << "max:" << FormattingInfo::intToString(rFormattingInfo.mMaxLength) << " " + << "left:" << rFormattingInfo.mLeftAligned + << ")"; + return debug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, const PatternConverter &rPatternConverter) + { + return rPatternConverter.debug(debug); + } +#endif // QT_NO_DEBUG_STREAM + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/helpers/patternformatter.h b/src/log4qt/log4qt/helpers/patternformatter.h new file mode 100644 index 0000000..fa21a19 --- /dev/null +++ b/src/log4qt/log4qt/helpers/patternformatter.h @@ -0,0 +1,196 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: patternformatter.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_PATTERNFORMATTER_H +#define LOG4QT_PATTERNFORMATTER_H + +#include "ukui-logmacros.h" + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#include + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + + +namespace Log4Qt +{ + + class FormattingInfo; + class PatternConverter; + class LoggingEvent; + + /*! + * \brief The class PatternFormatter formats a logging event based on a + * pattern string. + * + * The class PatternFormatter formats a LoggingEvent base on a pattern + * string. It is used by the patternLayout and TTCCLayout class to + * implement the formatting. + * + * On object construction the provided patterns tring is parsed. Based on + * the information found a chain of PatternConverter is created. Each + * PatternConverter handles a certain member of a LoggingEvent. + * + * \sa PatternLayout::format() + * \sa TTCCLayout::format() + */ + class LIBUKUILOG4QT_EXPORT PatternFormatter + { + public: + /*! + * Creates a PatternFormatter using a the specified \a rPattern. + */ + PatternFormatter(const QString &rPattern); + + /*! + * Destroys the PatternFormatter and all PatternConverter. + */ + virtual ~PatternFormatter(); + + private: + PatternFormatter(const PatternFormatter &rOther); // Not implemented + PatternFormatter &operator=(const PatternFormatter &rOther); // Not implemented + + public: + /*! + * Formats the given \a rLoggingEvent using the chain of + * PatternConverter created during construction from the specified + * pattern. + */ + QString format(const LoggingEvent &rLoggingEvent) const; + + private: + /*! + * If the character \a rDigit is a digit the digit is added to the + * integer \a rValue and the function returns true. Otherwise the + * function returns false. + * + * The function adds the digit by multiplying the existing value + * with ten and adding the numerical value of the digit. If the + * maximum integer value would be exceeded by the operation + * \a rValue is set to INT_MAX. + */ + bool addDigit(const QChar &rDigit, + int &rValue); + + /*! + * Creates a PatternConverter based on the specified conversion + * character \a rChar, the formatting information + * \a rFormattingInfo and the option \a rOption. + * + * The PatternConverter converter is appended to the list of + * PatternConverters. + */ + void createConverter(const QChar &rChar, + const FormattingInfo &rFormattingInfo, + const QString &rOption = QString()); + + /*! + * Creates a LiteralPatternConverter with the string literal + * \a rLiteral. + * + * The PatternConverter converter is appended to the list of + * PatternConverters. + */ + void createLiteralConverter(const QString &rLiteral); + + /*! + * Parses the pattern string specified on construction and creates + * PatternConverter according to it. + */ + void parse(); + + /*! + * Parses an integer option from an option string. If the string is + * not a valid integer or the integer value is less then zero, zero + * is returned. Returns the end of line seperator for the operating + * system. + */ + int parseIntegerOption(const QString &rOption); + + private: + const QString mIgnoreCharacters; + const QString mConversionCharacters; + const QString mOptionCharacters; + QString mPattern; + QList mPatternConverters; + + // Needs to be friend to access internal data + friend QDebug operator<<(QDebug, const PatternFormatter &rPatternFormatter); + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + +#ifndef QT_NO_DEBUG_STREAM + /*! + * \relates PatternFormatter + * + * Writes all object member variables to the given debug stream \a rDebug and + * returns the stream. + * + * + * %PatternFormatter(pattern:"%r [%t] %p %c %x - %m%n" + * converters:( + * DatePatternConverter(FormattingInfo(min:"0" max:"INT_MAX" left:false) format: "TIME_RELATIVE" ) , + * LiteralPatternConverter(FormattingInfo(min:"0" max:"INT_MAX" left:false) literal: " [" ) , + * BasicPatternConverter(FormattingInfo(min:"0" max:"INT_MAX" left:false) type: "THREAD_CONVERTER" ) , + * LiteralPatternConverter(FormattingInfo(min:"0" max:"INT_MAX" left:false) literal: "] " ) , + * BasicPatternConverter(FormattingInfo(min:"0" max:"INT_MAX" left:false) type: "LEVEL_CONVERTER" ) , + * LiteralPatternConverter(FormattingInfo(min:"0" max:"INT_MAX" left:false) literal: " " ) , + * LoggerPatternConverter(FormattingInfo(min:"0" max:"INT_MAX" left:false) precision: 0 ) , + * LiteralPatternConverter(FormattingInfo(min:"0" max:"INT_MAX" left:false) literal: " " ) , + * BasicPatternConverter(FormattingInfo(min:"0" max:"INT_MAX" left:false) type: "NDC_CONVERTER" ) , + * LiteralPatternConverter(FormattingInfo(min:"0" max:"INT_MAX" left:false) literal: " - " ) , + * BasicPatternConverter(FormattingInfo(min:"0" max:"INT_MAX" left:false) type: "MESSAGE_CONVERTER" ) , + * LiteralPatternConverter(FormattingInfo(min:"0" max:"INT_MAX" left:false) literal: "" ) ) ) + * + * \sa QDebug + */ + QDebug operator<<(QDebug debug, + const PatternFormatter &rPatternFormatter); +#endif // QT_NO_DEBUG_STREAM + + + /************************************************************************** + * Inline + **************************************************************************/ + + +} // namespace Log4Qt + + +Q_DECLARE_TYPEINFO(Log4Qt::PatternFormatter, Q_MOVABLE_TYPE); + + +#endif // LOG4QT_PATTERNFORMATTER_H diff --git a/src/log4qt/log4qt/helpers/properties.cpp b/src/log4qt/log4qt/helpers/properties.cpp new file mode 100644 index 0000000..96d04d7 --- /dev/null +++ b/src/log4qt/log4qt/helpers/properties.cpp @@ -0,0 +1,364 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: properties.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/helpers/properties.h" + +#include +#include +#include +#include +#include "log4qt/logger.h" + + + +namespace Log4Qt +{ + + + + /************************************************************************** + *Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + LOG4QT_DECLARE_STATIC_LOGGER(logger, Log4Qt::Properties) + + + + /************************************************************************** + * Class implementation: Properties + **************************************************************************/ + + + void Properties::load(QIODevice *pDevice) + { + const QLatin1Char append_char(msEscapeChar); + + if (!pDevice) + { + logger()->warn("No device specified for load."); + return; + } + + QTextStream stream(pDevice); + QString line; + int line_number = 0; + QString property; + int property_start_line = 1; + + do { + line = trimLeft(stream.readLine()); + line_number++; + + if (!line.isEmpty() && line.at(line.length() - 1) == append_char) + property += line.left(line.length() - 1); + else + { + property += line; + parseProperty(property, property_start_line); + property.clear(); + property_start_line = line_number + 1; + } + } + while (!line.isNull()); + } + + + void Properties::load(const QSettings &rSettings) + { + QStringList keys = rSettings.childKeys(); + QString key; + Q_FOREACH(key, keys) + insert(key, rSettings.value(key).toString()); + } + + + QString Properties::property(const QString &rKey) const + { + // Null string indicates the property does not contain the key. + + if (contains(rKey)) + { + QString value = this->value(rKey); + if (value.isNull()) + return QString(QLatin1String("")); + else + return value; + } + + if (mpDefaultProperties) + return mpDefaultProperties->property(rKey); + else + return QString(); + } + + + QString Properties::property(const QString &rKey, + const QString &rDefaultValue) const + { + QString value = property(rKey); + if (value.isNull()) + return rDefaultValue; + else + return value; + } + + + QStringList Properties::propertyNames() const + { + QStringList default_keys; + if (mpDefaultProperties) + default_keys = mpDefaultProperties->propertyNames(); + + QStringList keys = this->keys(); + QString key; + Q_FOREACH(key, default_keys) + if (!keys.contains(key)) + keys << key; + + return keys; + } + + + void Properties::parseProperty(const QString &rProperty, + int line) + { + Q_ASSERT_X(rProperty == trimLeft(rProperty), "parseProperty()", "rProperty has leading spaces"); + + enum State + { + KEY_STATE, + KEYSPACE_STATE, + SPACEVALUE_STATE, + VALUE_STATE, + KEYESCAPE_STATE, + VALUEESCAPE_STATE, + UNICODEESCAPE_STATE + }; + const QString value_escape_codes =QLatin1String(msValueEscapeCodes); + const QString value_escape_chars = QLatin1String(msValueEscapeChars); + Q_ASSERT_X(value_escape_codes.length() == value_escape_chars.length(), "parseProperty()", "Value escape sequence character definition does not map"); + const QString key_escape_codes = QLatin1String(msKeyEscapeCodes); + const QString key_escape_chars = QLatin1String(msKeyEscapeChars); + Q_ASSERT_X(key_escape_codes.length() == key_escape_chars.length(), "parseProperty()", "Key escape sequence character definition does not map"); + + if (rProperty.isEmpty()) + return; + + int i = 0; + QChar c; + char ch; + State state = KEY_STATE; + QString key; + QString value; + QString *p_string = &key; + uint ucs; + int ucs_digits; + while (i < rProperty.length()) + { + // i points to the current character. + // c contains the current character + // ch contains the Latin1 equivalent of the current character + // i is incremented at the end of the loop to consume the character. + // continue is used to change state without consuming the character + + c = rProperty.at(i); + ch = c.toLatin1(); + + switch (state) + { + case KEY_STATE: + if (ch == '!' || ch == '#' ) + return; + else if (c.isSpace()) + { + p_string = &value; + state = KEYSPACE_STATE; + } + else if (ch == '=' || ch == ':') + { + p_string = &value; + state = SPACEVALUE_STATE; + } + else if (ch == msEscapeChar) + state = KEYESCAPE_STATE; + else + *p_string += c; + break; + case KEYSPACE_STATE: + if (ch == '=' || ch == ':') + state = SPACEVALUE_STATE; + else if (!c.isSpace()) + { + *p_string += c; + state = VALUE_STATE; + } + break; + case SPACEVALUE_STATE: + if (!c.isSpace()) + { + *p_string += c; + state = VALUE_STATE; + } + break; + case VALUE_STATE: + if (ch == msEscapeChar) + state = VALUEESCAPE_STATE; + else + *p_string += c; + break; + case KEYESCAPE_STATE: + { + int convert = key_escape_codes.indexOf(c); + if (convert >= 0) + *p_string += key_escape_chars.at(convert); + else + { + logger()->warn("Unknown escape sequence '\\%1' in key of property starting at line %2", + QString(c), + line); + *p_string += c; + } + state = KEY_STATE; + break; + } + case VALUEESCAPE_STATE: + { + int convert = value_escape_codes.indexOf(c); + if (convert >= 0) + { + *p_string += value_escape_chars.at(convert); + state = VALUE_STATE; + } + else if (ch == 'u') + { + ucs = 0; + ucs_digits = 0; + state = UNICODEESCAPE_STATE; + } + else + { + logger()->warn("Unknown escape sequence '\\%1' in value of property starting at line %2", QString(c), line); + *p_string += c; + state = VALUE_STATE; + } + break; + } + case UNICODEESCAPE_STATE: + { + int hex = hexDigitValue(c); + if (hex >= 0) + { + ucs = ucs * 16 + hex; + ucs_digits++; + if (ucs_digits == 4 || i == rProperty.length() - 1) + { + *p_string += QChar(ucs); + state = VALUE_STATE; + } + } + else + { + if (ucs_digits > 0) + *p_string += QChar(ucs); + state = VALUE_STATE; + continue; + } + break; + } + default: + Q_ASSERT_X(false, "Properties::parseProperty()", "Unknown state constant"); + return; + } + i++; + } + + if (key.isEmpty() && !value.isEmpty()) + logger()->warn("Found value with no key in property starting at line %1", line); + + logger()->trace("Loaded property '%1' : '%2'", key, value); + insert(key, value); + } + + + int Properties::hexDigitValue(const QChar &rDigit) + { + bool ok; + int result = QString(rDigit).toInt(&ok, 16); + if (!ok) + return -1; + else + return result; + } + + + QString Properties::trimLeft(const QString &rLine) + { + int i = 0; + while (i < rLine.length() && rLine.at(i).isSpace()) + i++; + return rLine.right(rLine.length() - i); + } + + + const char Properties::msEscapeChar ='\\'; + const char *Properties::msValueEscapeCodes = "tnr\\\"\' "; + const char *Properties::msValueEscapeChars = "\t\n\r\\\"\' "; + const char *Properties::msKeyEscapeCodes = " :="; + const char *Properties::msKeyEscapeChars = " :="; + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, const Properties &rProperties) + { + debug.nospace() << "Properties(" + << "default:" << rProperties.defaultProperties() << " " + << "properties:" << *reinterpret_cast *>(&rProperties) + << ")"; + return debug.space(); + } +#endif + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/helpers/properties.h b/src/log4qt/log4qt/helpers/properties.h new file mode 100644 index 0000000..71566fc --- /dev/null +++ b/src/log4qt/log4qt/helpers/properties.h @@ -0,0 +1,162 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: properties.h + * created: September + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_PROPERTIES_H +#define LOG4QT_PROPERTIES_H + +#include "ukui-logmacros.h" + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#include + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +class QIODevice; +class QSettings; + + +namespace Log4Qt +{ + /*! + * \brief The class Properties implements a JAVA property hash. + */ + class LIBUKUILOG4QT_EXPORT Properties : public QHash + { + public: + Properties(Properties *pDefaultProperties = 0); + // virtual ~Properties(); // Use compiler default + // Properties(const Properties &rOther); // Use compiler default + // Properties &operator=(const Properties &rOther); // Not implemented + + public: + Properties *defaultProperties() const; + QString property(const QString &rKey) const; + QString property(const QString &rKey, + const QString &rDefaultValue) const; + void setDefaultProperties(Properties *pDefault); + void setProperty(const QString &rKey, + const QString &rValue); + + // JAVA: void list(QTextStream &rTextStream); + void load(QIODevice *pDevice); + + /*! + * Reads all child keys from the QSettings object \a rSettings and + * inserts them into this object. The value is created using + * QVariant::toString(). Types that do not support toString() are + * resulting in an empty string. + * + * \code + * QSettings settings; + * settings.setValue("Package", "Full"); + * settings.setValue("Background", Qt::white); + * settings.setValue("Support", true); + * settings.setValue("Help/Language", "en_UK"); + * + * Properties properties + * properties.load(&settings) + * + * // properties (("Package", "Full"), ("Background", ""), ("Support", "true")) + * \endcode + */ + void load(const QSettings &rSettings); + + QStringList propertyNames() const; + // JAVA: void save(QIODevice *pDevice) const; + + private: + void parseProperty(const QString &rProperty, + int line); + static int hexDigitValue(const QChar &rDigit); + static QString trimLeft(const QString &rString); + + private: + Properties *mpDefaultProperties; + static const char msEscapeChar; + static const char *msValueEscapeCodes; + static const char *msValueEscapeChars; + static const char *msKeyEscapeCodes; + static const char *msKeyEscapeChars; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + +#ifndef QT_NO_DEBUG_STREAM + /*! + * \relates Properties + * + * Writes all object member variables to the given debug stream \a rDebug and + * returns the stream. + * + * + * %Properties(default:0x0 properties:QHash(("log4j.appender.testAppender.layout", "org.apache.log4j.PatternLayout ") + * ("log4j.appender.testAppender.layout.ConversionPattern", "[%t] %-5p %l: %m%n") + * ("log4j.appender.testAppender.Append", "false ") + * ("log4j.appender.testAppender.File", "output/temp ") + * ("log4j.rootCategory", "TRACE, testAppender") + * ("log4j.appender.testAppender", "org.apache.log4j.FileAppender")) ) + * + * \sa QDebug + */ + QDebug operator<<(QDebug debug, + const Properties &rProperties); +#endif // QT_NO_DEBUG_STREAM + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline Properties::Properties(Properties *pDefaultProperties) : + mpDefaultProperties(pDefaultProperties) + {} + + inline Properties *Properties::defaultProperties() const + { return mpDefaultProperties; } + + inline void Properties::setDefaultProperties(Properties *pDefaultProperties) + { mpDefaultProperties = pDefaultProperties; } + + inline void Properties::setProperty(const QString &rKey, + const QString &rValue) + { insert(rKey, rValue); } + + +} // namespace Log4Qt + + +Q_DECLARE_TYPEINFO(Log4Qt::Properties, Q_MOVABLE_TYPE); + + +#endif // LOG4QT_PROPERTIES_H diff --git a/src/log4qt/log4qt/hierarchy.cpp b/src/log4qt/log4qt/hierarchy.cpp new file mode 100644 index 0000000..283c7fd --- /dev/null +++ b/src/log4qt/log4qt/hierarchy.cpp @@ -0,0 +1,212 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: hierarchy.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * changes: Sep 2008, Martin Heinrich: + * - Fixed problem in Qt 4.4 where QReadWriteLock is by default + * non-recursive. + * + * + * Copyright 2007 - 2008 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/hierarchy.h" + +#include +#include "log4qt/logger.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + LOG4QT_DECLARE_STATIC_LOGGER(static_logger, Log4Qt::LoggerRepository) + + + + /************************************************************************** + * Class implementation: Hierarchy + **************************************************************************/ + + + Hierarchy::Hierarchy() : +#if QT_VERSION < QT_VERSION_CHECK(4, 4, 0) + mObjectGuard(), +#else + mObjectGuard(QReadWriteLock::Recursive), +#endif + mLoggers(), + mThreshold(Level::NULL_INT), + mpRootLogger(logger(QString())) + { + // Store root logger to allow rootLogger() to be const + } + + + Hierarchy::~Hierarchy() + { + static_logger()->warn("Unexpected destruction of Hierarchy"); + + // QWriteLocker locker(&mObjectGuard); + // + // resetConfiguration(); + // clear(); + // delete mpRootLogger; + } + + + bool Hierarchy::exists(const QString &rName) const + { + QReadLocker locker(&mObjectGuard); + + return mLoggers.contains(rName); + } + + + Logger *Hierarchy::logger(const QString &rName) + { + QWriteLocker locker(&mObjectGuard); + + return createLogger(rName); + } + + + QList Hierarchy::loggers() const + { + QReadLocker locker(&mObjectGuard); + + return mLoggers.values(); + } + + + void Hierarchy::setThreshold(const QString &rThreshold) + { + setThreshold(Level::fromString(rThreshold)); + } + + + void Hierarchy::resetConfiguration() + { + QWriteLocker locker(&mObjectGuard); + + // Reset all loggers. + // Leave log, qt and root logger to the last to allow debugging of shutdown. + + Logger *p_logging_logger = logger(QLatin1String("Log4Qt")); + Logger *p_qt_logger = logger(QLatin1String("Qt")); + Logger *p_root_logger = rootLogger(); + + Logger *p_logger; + Q_FOREACH(p_logger, mLoggers) + { + if ((p_logger == p_logging_logger) || (p_logger == p_qt_logger) || (p_logger == p_root_logger)) + continue; + resetLogger(p_logger, Level::NULL_INT); + } + resetLogger(p_qt_logger, Level::NULL_INT); + resetLogger(p_logging_logger, Level::NULL_INT); + resetLogger(p_root_logger, Level::DEBUG_INT); + } + + + void Hierarchy::shutdown() + { + static_logger()->debug("Shutting down Hierarchy"); + resetConfiguration(); + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug Hierarchy::debug(QDebug &rDebug) const + { + rDebug.nospace() << "Hierarchy(" + << "loggers:" << loggers().count() << " " + << "threshold:" << threshold().toString() << " " + << "root-level:" << rootLogger()->level().toString() << " " + << "root-appenders:" << rootLogger()->appenders().count() + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + Logger *Hierarchy::createLogger(const QString &rName) + { + // Q_ASSERT_X(, "Hierarchy::createLogger", "Lock must be held by caller") + + const QString name_separator = QLatin1String("::"); + + Logger *p_logger = mLoggers.value(rName, 0); + if (p_logger != 0) + return p_logger; + + if (rName.isEmpty()) + { + p_logger = new Logger(this, Level::DEBUG_INT, QLatin1String("root"), 0); + mLoggers.insert(QString(), p_logger); + return p_logger; + } + QString parent_name; + int index = rName.lastIndexOf(name_separator); + if (index >=0) + parent_name = rName.left(index); + p_logger = new Logger(this, Level::NULL_INT, rName, createLogger(parent_name)); + mLoggers.insert(rName, p_logger); + return p_logger; + } + + + void Hierarchy::resetLogger(Logger *pLogger, Level level) const + { + // Q_ASSERT_X(, "Hierarchy::resetLogger", "Lock must be held by caller") + + pLogger->removeAllAppenders(); + pLogger->setAdditivity(true); + pLogger->setLevel(level); + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/hierarchy.h b/src/log4qt/log4qt/hierarchy.h new file mode 100644 index 0000000..089980c --- /dev/null +++ b/src/log4qt/log4qt/hierarchy.h @@ -0,0 +1,142 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: hierarchy.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_HIERARCHY_H +#define LOG4QT_HIERARCHY_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/loggerrepository.h" +#include "ukui-logmacros.h" + +#include +#include + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + /*! + * \brief The class Hierarchy implements a logger repository. + * + * \note All the functions declared in this class are thread-safe. + */ + class LIBUKUILOG4QT_EXPORT Hierarchy : public LoggerRepository + { + public: + Hierarchy(); + // Hierarchy(const Hierarchy &rOther); // Use compiler default + virtual ~Hierarchy(); + // Hierarchy &operator=(const Hierarchy &rOther); // Use compiler default + + public: + virtual bool exists(const QString &rName) const; + virtual Logger *logger(const QString &rName); + virtual QList loggers() const; + // JAVA: virtual Logger *logger(const String &rName, LoggerFactory *pFactory); + virtual Logger *rootLogger() const; + virtual Level threshold() const; + virtual void setThreshold(Level level); + virtual void setThreshold(const QString &rThreshold); + + // JAVA: void clear(); + virtual bool isDisabled(Level level); + virtual void resetConfiguration(); + virtual void shutdown(); + + // JAVA: virtual void addHierarchyEventListener(HierarchyEventListener *pEventListener); + // JAVA: virtual void emitNoAppenderWarning(Logger *plogger) const; + // JAVA: virtual void fireAddAppenderEvent(Logger *plogger, Appender *pAppender) const; + + // JAVA: void addRenderer(const QString &rClass, ObjectRenderer *pObjectRenderer); + // JAVA: QHash getRendererMap() const; + // JAVA: setRenderer(const QString &rClass, ObjectRenderer *pObjectRenderer); + + protected: +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream \a rDebug and + * returns the stream. + * + * + * %Hierarchy(loggers:6 threshold:"ALL" root-level:"DEBUG" root-appenders:0) + * + * \sa QDebug, operator<<(QDebug debug, const LoggerRepository &rLoggerRepository) + */ + virtual QDebug debug(QDebug &rdebug) const; +#endif + + private: + Logger *createLogger(const QString &rName); + void resetLogger(Logger *pLogger, Level level) const; + + private: + mutable QReadWriteLock mObjectGuard; + QHash mLoggers; + volatile bool mHandleQtMessages; + Level mThreshold; + Logger *mpRootLogger; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline Logger *Hierarchy::rootLogger() const + { // QReadLocker locker(&mObjectGuard); // Constant for object lifetime + return mpRootLogger; } + + inline Level Hierarchy::threshold() const + { // QReadLocker locker(&mObjectGuard); // Level is threadsafe + return mThreshold; } + + inline void Hierarchy::setThreshold(Level level) + { // QReadLocker locker(&mObjectGuard); // Level is threadsafe + mThreshold = level; } + + inline bool Hierarchy::isDisabled(Level level) + { // QReadLocker locker(&mObjectGuard); // Level is threadsafe + return level < mThreshold; } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::Hierarchy, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_HIERARCHY_H diff --git a/src/log4qt/log4qt/layout.cpp b/src/log4qt/log4qt/layout.cpp new file mode 100644 index 0000000..160f80d --- /dev/null +++ b/src/log4qt/log4qt/layout.cpp @@ -0,0 +1,91 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: layout.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/layout.h" + +#include +#include "log4qt/loggingevent.h" +#include "log4qt/logmanager.h" + + + +namespace Log4Qt +{ + + + /*************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: Layout + **************************************************************************/ + + + QString Layout::contentType() const + { + return QString::fromLatin1("text/plain"); + } + + + void Layout::activateOptions() + { + } + + + QString Layout::endOfLine() + { + // There seams to be no function in Qt for this + +#ifdef Q_OS_WIN32 + return QLatin1String("\r\n"); +#endif // Q_OS_WIN32 +//#ifdef Q_OS_MAC +// return QLatin1String("\r"); +//#endif // Q_OS_MAC + return QLatin1String("\n"); + } + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/layout.h b/src/log4qt/log4qt/layout.h new file mode 100644 index 0000000..117cbef --- /dev/null +++ b/src/log4qt/log4qt/layout.h @@ -0,0 +1,157 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: layout.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_LAYOUT_H +#define LOG4QT_LAYOUT_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/helpers/logobject.h" + +#include "log4qt/helpers/logobjectptr.h" +#include "log4qt/log4qt.h" +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + class LoggingEvent; + + /*! + * \brief The class Layout is the base class for all layouts. + * + * \note The ownership and lifetime of objects of this class are managed. See + * \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT Layout : public LogObject + { + Q_OBJECT + + /*! + * The property holds the content type of the layout. + * + * \sa contentType() + */ + Q_PROPERTY(QString footercontentType READ contentType) + /*! + * The property holds the footer used by the layout. + * + * \sa footer(), setFooter() + */ + Q_PROPERTY(QString footer READ footer WRITE setFooter) + /*! + * The property holds the header used by the layout. + * + * \sa header(), setHeader() + */ + Q_PROPERTY(QString header READ header WRITE setHeader) + + public: + Layout(QObject *pParent = 0); + virtual ~Layout(); + private: + Layout(const Layout &rOther); // Not implemented + Layout &operator=(const Layout &rOther); // Not implemented + + public: + virtual QString contentType() const; + QString footer() const; + QString header() const; + // JAVA: virtual bool ignoresThrowable() const; + QString name() const; + void setFooter(const QString &rFooter); + void setHeader(const QString &rHeader); + void setName(const QString &rName); + // JAVA: void setIgnoresThrowable(bool) const; + + virtual void activateOptions(); + virtual QString format(const LoggingEvent &rEvent) = 0; + + /*! + * Returns the end of line seperator for the operating system. + * + * Windows: \\r\\n + * Mac: \\r + * UNIX: \\n + */ + static QString endOfLine(); + + // Member variables + private: + QString mFooter; + QString mHeader; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline Layout::Layout(QObject *pParent) : + LogObject(pParent) + {} + + inline Layout::~Layout() + {} + + inline QString Layout::footer() const + { return mFooter; } + + inline QString Layout::header() const + { return mHeader; } + + inline QString Layout::name() const + { return objectName(); } + + inline void Layout::setFooter(const QString &rFooter) + { mFooter = rFooter; } + + inline void Layout::setHeader(const QString &rHeader) + { mHeader = rHeader; } + + inline void Layout::setName(const QString &rName) + { setObjectName(rName); } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::Layout, Q_COMPLEX_TYPE); // Use default +Q_DECLARE_TYPEINFO(Log4Qt::LogObjectPtr, Q_MOVABLE_TYPE); + + +#endif // LOG4QT_LAYOUT_H diff --git a/src/log4qt/log4qt/level.cpp b/src/log4qt/log4qt/level.cpp new file mode 100644 index 0000000..9188581 --- /dev/null +++ b/src/log4qt/log4qt/level.cpp @@ -0,0 +1,238 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: level.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/level.h" + +#include +#include +#include +#include "log4qt/logger.h" + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + LOG4QT_DECLARE_STATIC_LOGGER(logger, Log4Qt::Level) + + + + /************************************************************************** + * Class implementation: Level + **************************************************************************/ + + + int Level::syslogEquivalent() const + { + // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + + switch (mValue) + { + case NULL_INT: + case ALL_INT: + case TRACE_INT: + case DEBUG_INT: + return 7; + case INFO_INT: + return 6; + case WARN_INT: + return 4; + case ERROR_INT: + return 3; + case FATAL_INT: + case OFF_INT: + return 0; + default: + Q_ASSERT_X(false, "Level::syslogEquivalent()", "Unknown level value"); + return 7; + } + } + + + QString Level::toString() const + { + // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + + const char *p_context = "Level"; + + switch (mValue) + { + case NULL_INT: + return QCoreApplication::translate(p_context, "NULL"); + case ALL_INT: + return QCoreApplication::translate(p_context, "ALL"); + case TRACE_INT: + return QCoreApplication::translate(p_context, "TRACE"); + case DEBUG_INT: + return QCoreApplication::translate(p_context, "DEBUG"); + case INFO_INT: + return QCoreApplication::translate(p_context, "INFO"); + case WARN_INT: + return QCoreApplication::translate(p_context, "WARN"); + case ERROR_INT: + return QCoreApplication::translate(p_context, "ERROR"); + case FATAL_INT: + return QCoreApplication::translate(p_context, "FATAL"); + case OFF_INT: + return QCoreApplication::translate(p_context, "OFF"); + default: + Q_ASSERT_X(false, "Level::toString()", "Unknown level value"); + return QCoreApplication::translate(p_context, "NULL"); + } + } + + + Level Level::fromString(const QString &rLevel, bool *pOk) + { + const char *p_context = "Level"; + if (pOk) + *pOk = true; + #if 1 + if (!rLevel.compare(QLatin1String("OFF"), Qt::CaseInsensitive) || + !rLevel.compare(QCoreApplication::translate(p_context, "OFF"), Qt::CaseInsensitive)) + return OFF_INT; + if (!rLevel.compare(QLatin1String("FATAL"), Qt::CaseInsensitive) || + !rLevel.compare(QCoreApplication::translate(p_context, "FATAL"), Qt::CaseInsensitive)) + return FATAL_INT; + if (!rLevel.compare(QLatin1String("ERROR"), Qt::CaseInsensitive) || + !rLevel.compare(QCoreApplication::translate(p_context, "ERROR"), Qt::CaseInsensitive)) + return ERROR_INT; + if (!rLevel.compare(QLatin1String("WARN"), Qt::CaseInsensitive) || + !rLevel.compare(QCoreApplication::translate(p_context, "WARN"), Qt::CaseInsensitive)) + return WARN_INT; + if (!rLevel.compare(QLatin1String("INFO"), Qt::CaseInsensitive) || + !rLevel.compare(QCoreApplication::translate(p_context, "INFO"), Qt::CaseInsensitive)) + return INFO_INT; + if (!rLevel.compare(QLatin1String("DEBUG"), Qt::CaseInsensitive) || + !rLevel.compare(QCoreApplication::translate(p_context, "DEBUG"), Qt::CaseInsensitive)) + return DEBUG_INT; + if (!rLevel.compare(QLatin1String("TRACE"), Qt::CaseInsensitive) || + !rLevel.compare(QCoreApplication::translate(p_context, "TRACE"), Qt::CaseInsensitive)) + return TRACE_INT; + if (!rLevel.compare(QLatin1String("ALL"), Qt::CaseInsensitive) || + !rLevel.compare(QCoreApplication::translate(p_context, "ALL"), Qt::CaseInsensitive)) + return ALL_INT; + if (!rLevel.compare(QLatin1String("NULL"), Qt::CaseInsensitive) || + !rLevel.compare(QCoreApplication::translate(p_context, "NULL"), Qt::CaseInsensitive)) + return NULL_INT; + + logger()->warn("Use of invalid level string '%1'. Using 'Level::OFF_INT' instead.", rLevel); + if (pOk) + *pOk = false; + return OFF_INT; + #else + if (rLevel == QLatin1String("OFF") || + rLevel == QCoreApplication::translate(p_context, "OFF")) + return OFF_INT; + if (rLevel == QLatin1String("FATAL") || + rLevel == QCoreApplication::translate(p_context, "FATAL")) + return FATAL_INT; + if (rLevel == QLatin1String("ERROR") || + rLevel == QCoreApplication::translate(p_context, "ERROR")) + return ERROR_INT; + if (rLevel == QLatin1String("WARN") || + rLevel == QCoreApplication::translate(p_context, "WARN")) + return WARN_INT; + if (rLevel == QLatin1String("INFO") || + rLevel == QCoreApplication::translate(p_context, "INFO")) + return INFO_INT; + if (rLevel == QLatin1String("DEBUG") || + rLevel == QCoreApplication::translate(p_context, "DEBUG")) + return DEBUG_INT; + if (rLevel == QLatin1String("TRACE") || + rLevel == QCoreApplication::translate(p_context, "TRACE")) + return TRACE_INT; + if (rLevel == QLatin1String("ALL") || + rLevel == QCoreApplication::translate(p_context, "ALL")) + return ALL_INT; + if (rLevel == QLatin1String("NULL") || + rLevel == QCoreApplication::translate(p_context, "NULL")) + return NULL_INT; + + logger()->warn("Use of invalid level string '%1'. Using 'Level::NULL_INT' instead.", rLevel); + if (pOk) + *pOk = false; + return NULL_INT; + #endif + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DATASTREAM + QDataStream &operator<<(QDataStream &rStream, + const Level &rLevel) + { + quint8 l = rLevel.mValue; + rStream << l; + return rStream; + } + + + QDataStream &operator>>(QDataStream &rStream, + Level &rLevel) + { + quint8 l; + rStream >> l; + rLevel.mValue = (Level::Value)l; + return rStream; + } +#endif // QT_NO_DATASTREAM + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, + const Level &rLevel) + { + debug.nospace() << "Level(" + << rLevel.toString() + << ")"; + return debug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/level.h b/src/log4qt/log4qt/level.h new file mode 100644 index 0000000..6fd26f1 --- /dev/null +++ b/src/log4qt/log4qt/level.h @@ -0,0 +1,194 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: level.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_LEVEL_H +#define LOG4QT_LEVEL_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#include +#include "log4qt/log4qt.h" +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + /*! + * \brief The class Level defines the level of a logging event. + * + * \note All the functions declared in this class are thread-safe. + */ + class LIBUKUILOG4QT_EXPORT Level + { + public: + // Comparisson operators rely on the order: + // NULL_INT < ALL_INT < TRACE_INT < ... + // Serialisation uses unsigned 8 bit int + + /*! + * The enumeration Value contains all possible Level values. + */ + enum Value + { + /*! NULL_INT is used for no level has been specified */ + NULL_INT = 0, + ALL_INT = 32, + TRACE_INT = 64, + DEBUG_INT = 96, + INFO_INT = 128, + WARN_INT = 150, + ERROR_INT = 182, + FATAL_INT = 214, + OFF_INT = 255 + }; + + public: + Level(Value value = NULL_INT); + // Level(const Level &rOther); // Use compiler default + // virtual ~Level(); // Use compiler default + // Level &operator=(const Level &rOther); // Use compiler default + + int syslogEquivalent() const; + int toInt() const; + + bool operator==(const Level &rOther) const; + bool operator!=(const Level &rOther) const; + bool operator<(const Level &rOther) const; + bool operator<=(const Level &rOther) const; + bool operator>(const Level &rOther) const; + bool operator>=(const Level &rOther) const; + QString toString() const; + + static Level fromString(const QString &rName, bool *pOk = 0); + + private: + // QMutex mObjectGuard; + volatile Value mValue; + +#ifndef QT_NO_DATASTREAM + // Needs to be friend to stream objects + friend QDataStream &operator<<(QDataStream &rStream, + const Level &rLevel); + friend QDataStream &operator>>(QDataStream &rStream, + Level &rLevel); +#endif // QT_NO_DATASTREAM + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + +#ifndef QT_NO_DATASTREAM + /*! + * \relates Level + * + * Writes the given error \a rLevel to the given stream \a rStream, + * and returns a reference to the stream. + */ + QDataStream &operator<<(QDataStream &rStream, + const Level &rLevel); + + /*! + * \relates Level + * + * Reads an error from the given stream \a rStream into the given + * error \a rLevel, and returns a reference to the stream. + */ + QDataStream &operator>>(QDataStream &rStream, + Level &rLevel); +#endif // QT_NO_DATASTREAM + +#ifndef QT_NO_DEBUG_STREAM + /*! + * \relates Level + * + * Writes all object member variables to the given debug stream \a rDebug + * and returns the stream. + * + * + * %Level("ERROR") + * + * \sa QDebug + */ + QDebug operator<<(QDebug debug, + const Level &rLevel); +#endif // QT_NO_DEBUG_STREAM + + + /************************************************************************** + * Inline + **************************************************************************/ + + + inline Level::Level(Value value) : + mValue(value) + {} + + inline int Level::toInt() const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mValue; } + + inline bool Level::operator==(const Level &rOther) const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mValue == rOther.mValue; } + + inline bool Level::operator!=(const Level &rOther) const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mValue != rOther.mValue; } + + inline bool Level::operator<(const Level &rOther) const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mValue < rOther.mValue; } + + inline bool Level::operator<=(const Level &rOther) const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mValue <= rOther.mValue; } + + inline bool Level::operator>(const Level &rOther) const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mValue > rOther.mValue; } + + inline bool Level::operator>=(const Level &rOther) const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mValue >= rOther.mValue; } + + +} // namespace Log4Qt + + +Q_DECLARE_METATYPE(Log4Qt::Level) +Q_DECLARE_TYPEINFO(Log4Qt::Level, Q_MOVABLE_TYPE); + + +#endif // LOG4QT_LEVEL_H diff --git a/src/log4qt/log4qt/log4qt.cpp b/src/log4qt/log4qt/log4qt.cpp new file mode 100644 index 0000000..9378f46 --- /dev/null +++ b/src/log4qt/log4qt/log4qt.cpp @@ -0,0 +1,58 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: logging.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *****************************************************************************/ + + + +/****************************************************************************** + *Dependencies + ******************************************************************************/ + + +#include "log4qt/log4qt.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + *Implementation: Operators, Helper + **************************************************************************/ + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/log4qt.h b/src/log4qt/log4qt/log4qt.h new file mode 100644 index 0000000..641f196 --- /dev/null +++ b/src/log4qt/log4qt/log4qt.h @@ -0,0 +1,616 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: logging.h + * created: September 2007 + * author: Martin Heinrich + * + * + * changes: Sep 2008, Martin Heinrich: + * - Added a compile time version check for the Qt version + * Jan 2009, Martin Heinrich: + * - Updated documentation and version information for version 0.2 + * Feb 2009, Martin Heinrich: + * - Updated version information for version 0.3 + * + * + * Copyright 2007 - 2009 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_H +#define LOG4QT_H + + +/*! + * \mainpage + * + * %Log4Qt is a C++ port of the Apache Software Foundation Log4j package + * using the Trolltech Qt Framework. + * + * The documentation describes classes and methods that have been added or + * changed compared to Log4j. + * + * The following sections are describing the implementation in more detail: + * - \ref Changes "Differences to Log4j" + * - \ref Ownership "Object ownership" + * - \ref LogLog "Logging within the package" + * - \ref Init "Initialization procedure" + * - \ref Env "Environment Variables" + * - \ref Undocumented "Undocumented functions" + * - \ref Assumptions "Assumptions" + * + * \author Martin Heinrich + * \version 0.3 (January 2009) + * + */ + +/*! + * \page Changes Differences to Log4j + * + * The following fundamental differences exist between %Log4Qt and Log4j: + * + * - As a JAVA package Log4j does not have to manage object ownership and + * lifetime in the same way then it is required in C++. For details on + * how object ownership is handled see \ref Ownership "Object ownership". + * - The package uses itself for its internal logging similar to Log4j 1.3. + * For details see \ref LogLog "Logging within the package". + * - The configuration using system properties was replaced with a combination + * of environment variables and application settings. For details see + * \ref Env "Environment Variables". + * - Custom levels are not supported. + * - Multiple Logger Repositories are not supported + * + * The following classes have been changed: + * + * - \ref Log4Qt::AppenderSkeleton "AppenderSkeleton" + * - The procedure of checking, if logging is possible, originally used by + * \ref Log4Qt::WriterAppender "WriterAppender" was generalised and is used + * in \ref Log4Qt::AppenderSkeleton "AppenderSkeleton" and derived classes + * (\ref Log4Qt::AppenderSkeleton::checkEntryConditions() "checkEntryConditions()"). + * - The \ref Log4Qt::AppenderSkeleton::doAppend() "doAppend()" member function will + * check the entry conditions by calling the sub-class specific + * \ref Log4Qt::AppenderSkeleton::checkEntryConditions() "checkEntryConditions()". + * If successful the sub-class specific + * \ref Log4Qt::AppenderSkeleton::append() "append()" function is called. + * + * - Configurator + * - Configure functions return a boolean indicating, if the configuration + * was successful. + * - Configure errors are accessible over + * \ref Log4Qt::ConfiguratorHelper::configureError() + * "ConfiguratorHelper::configureError()". + * - Watching for configuration file changes is a function performed + * centrally by the \ref Log4Qt::ConfiguratorHelper "ConfiguratorHelper". + * The class provides signals to notify on configuration change and errors. + * - The class \ref Log4Qt::PropertyConfigurator "PropertyConfigurator" was + * extended to be able to read configuration data from a QSettings object. + * + * - \ref Log4Qt::Level "Level" + * - A new value \ref Log4Qt::Level::NULL_INT "Level::NULL_INT" was + * introduced to indicate there is no level set. + * + * - \ref Log4Qt::Logger "Logger" + * - The method \ref Log4Qt::Logger::isEnabledFor() "isEnabledFor()" + * does also take the repository threshold into account. + * - Several overloaded convenience member function are available to log + * messages with arguments of different types. + * - Two macros, \ref Log4Qt::LOG4QT_DECLARE_STATIC_LOGGER "LOG4QT_DECLARE_STATIC_LOGGER" + * and \ref Log4Qt::LOG4QT_DECLARE_QCLASS_LOGGER "LOG4QT_DECLARE_QCLASS_LOGGER", + * allows retrieving and caching of a pointer to a logger object. + * + * - \ref Log4Qt::LogManager "LogManager" + * - A QtMessage handler can be installed via + * \ref Log4Qt::LogManager::setHandleQtMessages() "setHandleQtMessages()", + * to redirect all messages created by calls to qDebug(), qWarning(), + * qCritical() and qFatal() to a logger. The logger is named Qt and can be + * accessed using \ref Log4Qt::LogManager::qtLogger() "qtLogger()". + * - The initialisation procedure is available over a public method + * (\ref Log4Qt::LogManager::startup() "startup()"). + * - The LogManager provides access to the logger used internally by the + * package (\ref Log4Qt::LogManager::logLogger() "logLogger()") and to + * its default initialisation procedure + * (\ref Log4Qt::LogManager::configureLogLogger() "configureLogLogger()"). + * + * - \ref Log4Qt::WriterAppender "WriterAppender" + * - The class will call \ref Log4Qt::WriterAppender::handleIoErrors() + * "handleIoErrors()" after all I/O operations. Sub-classes should + * re-implement the function to handle errors. + * + * The following classes have been added: + * + * - An additional appender class, \ref Log4Qt::DebugAppender "DebugAppender", + * was added. The class appends logging events to the platform specific debug + * output. + * - Various helper class have been introduced: + * - \ref Log4Qt::ClassLogger "ClassLogger": The class ClassLogger provides + * logging for a QObject derived class. + * - \ref Log4Qt::ConfiguratorHelper "ConfiguratorHelper": The class + * ConfiguratorHelper provides a configuration file watch and last error + * for configurator classes. + * - \ref Log4Qt::DateTime "DateTime": The class DateTime provides extended + * functionality for QDateTime. + * - \ref Log4Qt::LogError "LogError": The class LogError represents an error. + * - \ref Log4Qt::Factory "Factory": The class Factory provides factories + * for Appender, Filter and Layout objects. + * - \ref Log4Qt::InitialisationHelper "InitialisationHelper": The class + * InitialisationHelper performs static initialisation tasks. + * - \ref Log4Qt::LogObject "LogObject": The class LogObject is the common + * base class for many classes in the package. + * - \ref Log4Qt::LogObjectPtr "LogObjectPtr": The class LogObjectPtr + * implements automatic reference counting for LogObject objects. + * - \ref Log4Qt::PatternFormatter "PatternFormatter": The class + * PatternFormatter formats a logging event based on a pattern string. + * - \ref Log4Qt::Properties "Properties": The class Properties implements a + * JAVA property hash. + */ + +/*! + * \page Ownership Object ownership + * + * In difference to the JAVA Log4j package %Log4Qt must manage ownership and + * lifetime of the objects used. This is non trivial as objects are created + * and used in different ways. + * + * In general an object can be created explicitly for example an application + * may create Loggers, Appenders and Layouts during creation of a QApplication + * object. But they can also be automatically created by the package on + * startup using a \ref Log4Qt::PropertyConfigurator "PropertyConfigurator" + * configuration file. Objects may also be created the one way and then used + * the other. Object may be used by multiple other objects. A Layout for example + * may be used by multiple Appenders. Objects are also created from multiple + * threads. The creation may happen during static initialisation and the + * deletion during static de-initialization. + * + * The parent child model used by QObject cannot be used to handle this. It + * cannot automatically delete an object that is used by multiple others as + * for example an Appender used by multiple Loggers. In addition to this + * QObjects and their children must reside in the same thread. This would + * either mean to impose restriction on how objects can be created or to move + * objects to a specific thread. + * + * To allow an automatic deletion of not required objects the package + * implements reference counting for Appenders, Layouts and Filters. The + * reference counting is implemented in \ref Log4Qt::LogObject "LogObject", + * which is used as a common base class. The reference count can be explicitly + * changed using the methods \ref Log4Qt::LogObject::retain() "retain()" and + * \ref Log4Qt::LogObject::release() "release()". Alternatively an auto pointer + * is available \ref Log4Qt::LogObjectPtr "LogObjectPtr", which is used + * throughout the package. + * + * The reference counting mechanism will test, if an object has a QObject + * parent object set. If a parent is set, the object will not be deleted, if + * the reference count reaches 0. This allows to mix the reference counted + * paradigm with the QObject parent child one. + * + * The following example configures a logger and uses reference counting to + * manage the ownership of objects. + * + * \code + * // Create layout + * TTCCLayout *p_layout = new TTCCLayout(); + * + * // Create appender + * ConsoleAppender *p_appender = new ConsoleAppender(p_layout, ConsoleAppender::STDOUT_TARGET); + * p_appender->activateOptions(); + * + * // Get logger + * Logger *p_logger = Logger::logger("MyClass"); + * p_logger->addAppender(p_appender); + * + * // ... + * + * // Remove appender from Logger + * p_logger->removeAllAppenders(); // p_appender and p_layout are deleted here + * \endcode + * + * The following example configures a logger and uses QObject ownership of + * objects. + * + * \code + * QObject *p_parent = new MyObject; + * + * // Create objects + * ConsoleAppender *p_appender = new ConsoleAppender(p_parent); + * TTCCLayout *p_layout = new TTCCLayout(p_appender); + * + * // Configure appender + * p_appender->setTarget(ConsoleAppender::STDOUT_TARGET); + * p_appender->setLayout(p_layout); + * p_appender->activateOptions(); + * + * // Get logger + * Logger *p_logger = Logger::logger("MyClass"); + * p_logger->addAppender(p_appender); + * + * // ... + * + * // Remove appender from Logger + * p_logger->removeAllAppenders(); + * + * delete p_parent; // p_appender and p_layout are deleted here + * \endcode + * + * The following example shows how to use objects created on the stack. + * + * \code + * { + * // Create layout + * TTCCLayout layout; + * layout.retain(); + * + * // Create appender + * ConsoleAppender appender(&layout, ConsoleAppender::STDOUT_TARGET); + * appender.retain(); + * appender.activateOptions(); + * + * // Get logger + * Logger *p_logger = Logger::logger("MyClass"); + * p_logger->addAppender(&appender); + * + * // ... + * + * // Remove appender from Logger + * p_logger->removeAllAppenders(); // Without retain() program crashes here + * + * } // p_appender and p_layout are deleted here + * \endcode + */ + +/*! + * \page LogLog Logging within the package + * + * The package uses itself for logging similar to Log4j 1.3. This brings much + * more flexibility over logging to stdout, stderr like in Log4j 1.2 using + * logLog. It also enables the program to capture and handle errors raised by + * the package. + * + * Using this approach introduces the issue of recursion. The following example + * explains a situation where this happens. Let's say all logger are configured + * to be additive and only the root logger has an appender set. The appender + * is a \ref Log4Qt::FileAppender "FileAppender". During the logging of an + * event an I/O error occurs. The \ref Log4Qt::FileAppender "FileAppender" logs + * an event by itself using the logger %Log4Qt::FileAppender. The event is + * passed to the root logger, which calls then the \ref Log4Qt::FileAppender + * "FileAppender". This causes another I/O error, which is logged by + * the \ref Log4Qt::FileAppender "FileAppender". + * + * To avoid an endless loop the appender will drop the event on a recursive + * invocation. This check is done by \ref Log4Qt::AppenderSkeleton + * "AppenderSkeleton" in \ref Log4Qt::AppenderSkeleton::doAppend() + * "doAppend()". + * + * The problem only occurs, if a logger, appender, layout or filter log an + * event while an event is appended. Neither the logger class nor any of the + * layout or filter classes log events during appending of an event. Most of + * the appender classes may log errors during appending. Only the + * \ref Log4Qt::ListAppender "ListAppender" and + * \ref Log4Qt::ListAppender "ConsoleAppender" are not logging events. + * + * The default configuration uses two \ref Log4Qt::ListAppender + * "ConsoleAppender", one for stderr and one for stdout. No event will be + * dropped, because no recursive invocations can occur. + */ + +/*! + * \page Init Initialization procedure + * + * The package is initialised in two stages. The first stage takes place during + * static initialization. The second stage takes place when the + * \ref Log4Qt::LogManager "LogManager" singleton is created. + * + * During static initialisation the \ref Log4Qt::InitialisationHelper + * "InitialisationHelper" singleton is created . On construction it captures + * the program startup time, reads the required values from the system + * environment and registers the package types with the Qt type system. + * + * The \ref Log4Qt::LogManager "LogManager" singleton is created on first use. + * The creation is usually triggered by the request for a \ref Log4Qt::Logger + * "Logger" object. The call to \ref Log4Qt::Logger::logger() + * "Logger::logger()" is passed through to \ref Log4Qt::LogManager::logger() + * "LogManager::logger()". On creation the \ref Log4Qt::LogManager "LogManager" + * creates a \ref Log4Qt::Hierarchy "Hierarchy" object as logger repository. + * + * After the singleton is created the logging of the package is configured to + * its default by a call to \ref Log4Qt::LogManager::configureLogLogger() + * "LogManager::configureLogLogger()". The logger + * \ref Log4Qt::LogManager::logLogger() "logLogger()" is configured to be not + * additive. Messages with the level \ref Log4Qt::Level::ERROR_INT + * "Level::ERROR_INT" and \ref Log4Qt::Level::FATAL_INT "Level::FATAL_INT" are + * written to \c stderr using a ConsoleAppender. The remaining messages are + * written to \c stdout using a second ConsoleAppender. The level is read from + * the system environment or application settings using + * \ref Log4Qt::InitialisationHelper::setting() + * "InitialisationHelper::setting()" with the key \c Debug. If a level value + * is found, but it is not a valid Level string, + * \ref Log4Qt::Level::DEBUG_INT "Level::DEBUG_INT" is used. If no level string + * is found \ref Log4Qt::Level::ERROR_INT "Level::ERROR_INT" is used. + * + * Once the logging is configured the package is initialised by a call to + * \ref Log4Qt::LogManager::startup() "LogManager::startup()". The function + * will test for the setting \c DefaultInitOverride in the system environment + * and application settings using \ref Log4Qt::InitialisationHelper::setting() + * "InitialisationHelper::setting()". If the value is present and set to + * anything else then \c false, the initialisation is aborted.
+ * The system environment and application settings are tested for the setting + * \c Configuration. If it is found and it is a valid path to a file, the + * package is configured with the file using + * \ref Log4Qt::PropertyConfigurator::doConfigure(const QString &, LoggerRepository *) + * "PropertyConfigurator::doConfigure()". If the setting \c Configuration is + * not available and a QCoreApplication object is present, the application + * settings are tested for a group \c Log4Qt/Properties. If the group exists, + * the package is configured with the setting using the + * \ref Log4Qt::PropertyConfigurator::doConfigure(const QSettings &r, LoggerRepository *) + * "PropertyConfiguratordoConfigure()". If neither a configuration file nor + * configuration settings could be found, the current working directory is + * searched for the file \c "log4qt.properties". If it is found, the package + * is configured with the file using + * \ref Log4Qt::PropertyConfigurator::doConfigure(const QString &, LoggerRepository *) + * "PropertyConfigurator::doConfigure()". + * + * The following example shows how to use application settings to initialise the + * package. + * + * \code + * # file: myapplication.h + * + * #include qapplication.h + * + * class MyApplication : public QApplication + * { + * Q_OBJECT + * + * public: + * MyApplication(); + * ~MyApplication(); + * void setupLog4Qt(); + * } + * \endcode + * \code + * # file: myapplication.cpp + * + * #include myapplication.h + * + * MyApplication::MyApplication( + * { + * // Set Application data to allow Log4Qt initialisation to read the + * // correct values + * setApplicationName("MyApplication"); + * setOrganisationName("MyOrganisation"); + * setOrganizationDomain("www.myorganisation.com"); + * + * // Log first message, which initialises Log4Qt + * Log4Qt::Logger::logger("MyApplication")->info("Hello World"); + * } + * + * MyApplication::~MyApplication() + * { + * } + * + * void MyApplication::setupLog4Qt() + * { + * QSettings s; + * + * // Set logging level for Log4Qt to TRACE + * s.beginGroup("Log4Qt"); + * s.setValue("Debug", "TRACE"); + * + * // Configure logging to log to the file C:/myapp.log using the level TRACE + * s.beginGroup("Properties"); + * s.setValue("log4j.appender.A1", "org.apache.log4j.FileAppender"); + * s.setValue("log4j.appender.A1.file", "C:/myapp.log"); + * s.setValue("log4j.appender.A1.layout", "org.apache.log4j.TTCCLayout"); + * s.setValue("log4j.appender.A1.layout.DateFormat", "ISO8601"); + * s.setValue("log4j.rootLogger", "TRACE, A1"); + * + * // Settings will become active on next application startup + * } + * \endcode + */ + +/*! + * \page Env Environment Variables + * + * The package uses environment variables to control the initialization + * procedure. The environment variables replace the system property entries + * used by Log4j. + * + * For compability reasons the Log4j entry is recognised. Alternatively a + * environment variable style Log4Qt form can be used. The following entries + * are used: + * + * - LOG4QT_DEBUG
+ * The variable controls the \ref Log4Qt::Level "Level" value for the + * logger \ref Log4Qt::LogManager::logLogger() "LogManager::logLogger()". + * If the value is a valid \ref Log4Qt::Level "Level" string, the level for + * the is set to the level. If the value is not a valid + * \ref Log4Qt::Level "Level" string, \ref Log4Qt::Level::DEBUG_INT + * "DEBUG_INT" is used. Otherwise \ref Log4Qt::Level::ERROR_INT "ERROR_INT" + * is used. + * - \ref Log4Qt::LogManager::configureLogLogger() + * "LogManager::configureLogLogger()" + * + * - LOG4QT_DEFAULTINITOVERRIDE
+ * The variable controls the \ref Init "initialization procedure" performed + * by the \ref Log4Qt::LogManager "LogManager" on startup. If it is set to + * any other value then \c false the \ref Init "initialization procedure" + * is skipped. + * - \ref Log4Qt::LogManager::startup() "LogManager::startup()" + * + * - LOG4QT_CONFIGURATION
+ * The variable specifies the configuration file used for initialising the + * package. + * - \ref Log4Qt::LogManager::startup() "LogManager::startup()" + * + * - LOG4QT_CONFIGURATORCLASS
+ * The variable specifies the configurator class used for initialising the + * package. + * + * Environment variables are read during static initialisation on creation of + * the \ref Log4Qt::InitialisationHelper "InitialisationHelper". They can be + * accessed by calling \ref Log4Qt::InitialisationHelper::environmentSettings() + * "InitialisationHelper::environmentSettings()". + * + * All settings can also be made in the application settings under the group + * \c %Log4Qt. For example the environment variable \c LOG4QT_DEBUG is + * equivalent to the setting \c Log4Qt/Debug. If an environment variable is + * set it takes precedence over the application setting. Settings are only + * used, if an QApplication object is available, when the + * \ref Log4Qt::LogManager "LogManager" is + * initialised (see \ref Log4Qt::InitialisationHelper::setting() + * "InitialisationHelper::setting()" for details). + */ + +/*! + * \page Undocumented Undocumented functions + * + * In general it was tried to avoid the usage of undocumented features of Qt. + * Nice to have features like for example Q_DECLARE_PRIVATE are not used. Only + * features that would have been resulted in re-coding the same functionality + * are used. + * + * - QT_WA: The macro is used to call Windows A/W functions + * - \ref Log4Qt::DebugAppender "DebugAppender" + * - QBasicAtomicPointer: The class is used instead of QAtomicPointer, because + * it allows the initialisation as plain old data type. + * - \ref Log4Qt::LOG4QT_GLOBAL_STATIC "LOG4QT_GLOBAL_STATIC" + * - \ref Log4Qt::LOG4QT_IMPLEMENT_INSTANCE "LOG4QT_IMPLEMENT_INSTANCE" + * - \ref Log4Qt::LOG4QT_DECLARE_STATIC_LOGGER "LOG4QT_DECLARE_STATIC_LOGGER" + * - Q_BASIC_ATOMIC_INITIALIZER: The macro is used to initialise QAtomicPointer + * objects as plain old data type. + * - \ref Log4Qt::LOG4QT_GLOBAL_STATIC "LOG4QT_GLOBAL_STATIC" + * - \ref Log4Qt::LOG4QT_IMPLEMENT_INSTANCE "LOG4QT_IMPLEMENT_INSTANCE" + * - \ref Log4Qt::LOG4QT_DECLARE_STATIC_LOGGER "LOG4QT_DECLARE_STATIC_LOGGER" + */ + +/*! + * \page Assumptions Assumptions + * + * The following assumptions are used throughout the package: + * + * - Reading / writing of bool or int is thread-safe, if declared volatile + * - \ref Log4Qt::ListAppender "ListAppender" + * - \ref Log4Qt::AppenderSkeleton "AppenderSkeleton" + * - \ref Log4Qt::ConsoleAppender "ConsoleAppender" + * - \ref Log4Qt::FileAppender "FileAppender" + * - \ref Log4Qt::Hierarchy "Hierarchy" + * - \ref Log4Qt::Level "Level" + * - \ref Log4Qt::Logger "Logger" + * - \ref Log4Qt::WriterAppender "WriterAppender" + * - \ref Log4Qt::Layout::format() "Layout::format()" is implemented reentrant + * in all sub-classes. + * - \ref Log4Qt::AppenderSkeleton "AppenderSkeleton" + * - Being able to use singleton objects during static de-initialization without + * order issues is more valuable then their destruction. + * - \ref Log4Qt::LogManager "LogManager" + * - \ref Log4Qt::LOG4QT_GLOBAL_STATIC "LOG4QT_GLOBAL_STATIC" + * - \ref Log4Qt::LOG4QT_IMPLEMENT_INSTANCE "LOG4QT_IMPLEMENT_INSTANCE" + */ + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include + +#include "ukui-logmacros.h" + +#if QT_VERSION < QT_VERSION_CHECK(4, 3, 0) +# error "Log4Qt requires Qt version 4.3.0 or higher" +#endif + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +/*! + * \brief The namespace %Log4Qt encloses all parts of the package. + */ +namespace Log4Qt +{ + /*! + * This macro expands a numeric value of the form 0xMMmmPP (MM = major, + * mm = minor, PP = patch) that specifies Log4Qt's version number. + * This is the version against which the application is compiled. + * + * \sa \ref Log4Qt::LOG4QT_VERSION_STR "LOG4QT_VERSION_STR", + * \ref Log4Qt::LogManager::version() "LogManager::version()" + */ + #define LOG4QT_VERSION 0x000200 + + /*! + * The macro expands to a string that specifies the Log4Qt's version + * number. This is the version against which the application is compiled. + * + * \sa \ref Log4Qt::LOG4QT_VERSION "LOG4QT_VERSION", + * \ref Log4Qt::LogManager::version() "LogManager::version()" + */ + #define LOG4QT_VERSION_STR "0.3.0" + + enum ErrorCode + { + OK = 0, + // AppenderSkeleton, FileAppender, WriterAppender + APPENDER_ACTIVATE_MISSING_LAYOUT_ERROR, + APPENDER_ACTIVATE_MISSING_WRITER_ERROR, + APPENDER_ACTIVATE_MISSING_FILE_ERROR, + APPENDER_CLOSED_ERROR, + APPENDER_INVALID_PATTERN_ERROR, + APPENDER_NO_OPEN_FILE_ERROR, + APPENDER_NOT_ACTIVATED_ERROR, + APPENDER_OPENING_FILE_ERROR, + APPENDER_RENAMING_FILE_ERROR, + APPENDER_REMOVE_FILE_ERROR, + APPENDER_USE_INVALID_PATTERN_ERROR, + APPENDER_USE_MISSING_LAYOUT_ERROR, + APPENDER_USE_MISSING_WRITER_ERROR, + APPENDER_WRITING_FILE_ERROR, + // Level + LEVEL_INVALID_LEVEL_STRING, + // Layouts, PatternFormatter + LAYOUT_EXPECTED_DIGIT_ERROR, + LAYOUT_OPTION_IS_NOT_INTEGER_ERROR, + LAYOUT_INTEGER_IS_NOT_POSITIVE_ERROR, + // Logger + LOGGER_INVALID_LEVEL_FOR_ROOT, + // PropertyConfigurator, OptionHandler + CONFIGURATOR_OPENING_FILE_ERROR, + CONFIGURATOR_READING_FILE_ERROR, + CONFIGURATOR_INVALID_SUBSTITUTION_ERROR, + CONFIGURATOR_INVALID_OPTION_ERROR, + CONFIGURATOR_MISSING_APPENDER_ERROR, + CONFIGURATOR_UNKNOWN_APPENDER_CLASS_ERROR, + CONFIGURATOR_MISSING_LAYOUT_ERROR, + CONFIGURATOR_UNKNOWN_LAYOUT_CLASS_ERROR, + CONFIGURATOR_PROPERTY_ERROR, + CONFIGURATOR_UNKNOWN_TYPE_ERROR + }; + + + /****************************************************************************** + * Operators, Helpers + ******************************************************************************/ + + + /****************************************************************************** + * Inline + ******************************************************************************/ + + +} // namespace Log4Qt + + +#endif // LOG4QT_H diff --git a/src/log4qt/log4qt/log4qt.pri b/src/log4qt/log4qt/log4qt.pri new file mode 100644 index 0000000..3c3b111 --- /dev/null +++ b/src/log4qt/log4qt/log4qt.pri @@ -0,0 +1,113 @@ +# ******************************************************************************* +# +# package: Log4Qt +# file: log4qt.pri +# created: September 2007 +# author: Martin Heinrich +# +# +# Copyright 2007 Martin Heinrich +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ******************************************************************************* + +INCLUDEPATH += $$PWD/.. +DEPENDPATH += $$PWD/.. +HEADERS += \ + $$PWD/appender.h \ + $$PWD/appenderskeleton.h \ + $$PWD/basicconfigurator.h \ + $$PWD/consoleappender.h \ + $$PWD/dailyrollingfileappender.h \ + $$PWD/fileappender.h \ + $$PWD/helpers/classlogger.h \ + $$PWD/helpers/configuratorhelper.h \ + $$PWD/helpers/datetime.h \ + $$PWD/helpers/factory.h \ + $$PWD/helpers/initialisationhelper.h \ + $$PWD/helpers/logerror.h \ + $$PWD/helpers/logobject.h \ + $$PWD/helpers/logobjectptr.h \ + $$PWD/helpers/optionconverter.h \ + $$PWD/helpers/patternformatter.h \ + $$PWD/helpers/properties.h \ + $$PWD/helpers/asyncdispatcher.h \ + $$PWD/hierarchy.h \ + $$PWD/layout.h \ + $$PWD/level.h \ + $$PWD/log4qt.h \ + $$PWD/logger.h \ + $$PWD/loggerrepository.h \ + $$PWD/loggingevent.h \ + $$PWD/logmanager.h \ + $$PWD/mdc.h \ + $$PWD/ndc.h \ + $$PWD/patternlayout.h \ + $$PWD/propertyconfigurator.h \ + $$PWD/rollingfileappender.h \ + $$PWD/simplelayout.h \ + $$PWD/spi/filter.h \ + $$PWD/ttcclayout.h \ + $$PWD/writerappender.h \ + $$PWD/varia/debugappender.h \ + $$PWD/varia/denyallfilter.h \ + $$PWD/varia/nullappender.h \ + $$PWD/varia/levelmatchfilter.h \ + $$PWD/varia/levelrangefilter.h \ + $$PWD/varia/listappender.h \ + $$PWD/varia/stringmatchfilter.h + +SOURCES += \ + $$PWD/appenderskeleton.cpp \ + $$PWD/basicconfigurator.cpp \ + $$PWD/consoleappender.cpp \ + $$PWD/dailyrollingfileappender.cpp \ + $$PWD/fileappender.cpp \ + $$PWD/helpers/classlogger.cpp \ + $$PWD/helpers/configuratorhelper.cpp \ + $$PWD/helpers/datetime.cpp \ + $$PWD/helpers/factory.cpp \ + $$PWD/helpers/initialisationhelper.cpp \ + $$PWD/helpers/logerror.cpp \ + $$PWD/helpers/logobject.cpp \ + $$PWD/helpers/logobjectptr.cpp \ + $$PWD/helpers/optionconverter.cpp \ + $$PWD/helpers/patternformatter.cpp \ + $$PWD/helpers/properties.cpp \ + $$PWD/helpers/asyncdispatcher.cpp \ + $$PWD/hierarchy.cpp \ + $$PWD/layout.cpp \ + $$PWD/level.cpp \ + $$PWD/log4qt.cpp \ + $$PWD/logger.cpp \ + $$PWD/loggerrepository.cpp \ + $$PWD/loggingevent.cpp \ + $$PWD/logmanager.cpp \ + $$PWD/mdc.cpp \ + $$PWD/ndc.cpp \ + $$PWD/patternlayout.cpp \ + $$PWD/propertyconfigurator.cpp \ + $$PWD/rollingfileappender.cpp \ + $$PWD/simplelayout.cpp \ + $$PWD/spi/filter.cpp \ + $$PWD/ttcclayout.cpp \ + $$PWD/writerappender.cpp \ + $$PWD/varia/debugappender.cpp \ + $$PWD/varia/denyallfilter.cpp \ + $$PWD/varia/nullappender.cpp \ + $$PWD/varia/levelmatchfilter.cpp \ + $$PWD/varia/levelrangefilter.cpp \ + $$PWD/varia/listappender.cpp \ + $$PWD/varia/stringmatchfilter.cpp + \ No newline at end of file diff --git a/src/log4qt/log4qt/logger.cpp b/src/log4qt/log4qt/logger.cpp new file mode 100644 index 0000000..d5dc936 --- /dev/null +++ b/src/log4qt/log4qt/logger.cpp @@ -0,0 +1,349 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: logger.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * changes: Sep 2008, Martin Heinrich: + * - Fixed problem in Qt 4.4 where QReadWriteLock is by default + * non-recursive. + * + * + * Copyright 2007 - 2008 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/logger.h" + +#include +#include "log4qt/appenderskeleton.h" +#include "log4qt/varia/listappender.h" +#include "log4qt/loggingevent.h" +#include "log4qt/log4qt.h" +#include "log4qt/loggerrepository.h" +#include "log4qt/logmanager.h" + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: Logger + **************************************************************************/ + + + Logger::Logger(LoggerRepository* pLoggerRepository, Level level, const QString &rName, Logger *pParent) : + QObject(0), +#if QT_VERSION < QT_VERSION_CHECK(4, 4, 0) + mObjectGuard(), +#else + mObjectGuard(QReadWriteLock::Recursive), +#endif + mName(rName), + mpLoggerRepository(pLoggerRepository), + mAdditivity(true), + mAppenders(), + mLevel(level), + mpParent(pParent) + { + Q_ASSERT_X(pLoggerRepository, "Logger::Logger()", "Construction of Logger with null LoggerRepository"); + + setObjectName(mName); + } + + + Logger::~Logger() + { + logger()->warn("Unexpected destruction of Logger"); + + // QWriteLocker locker(&mObjectGuard); + // + // QMutableListIterator< LogObjectPtr > i(mAppenders); + // while (i.hasNext()) + // { + // i.next(); + // i.remove(); + // } + } + + + QList Logger::appenders() const + { + QReadLocker locker(&mObjectGuard); + + QList result; + Appender *p_appender; + Q_FOREACH(p_appender, mAppenders) + result << p_appender; + return result; + } + + + void Logger::setLevel(Level level) + { + // QWriteLocker locker(&mObjectGuard); // Read/Write int is safe + + if ((parentLogger() == 0) && (level == Level::NULL_INT)) + { + logger()->warn("Invalid root logger level NULL_INT. Using DEBUG_INT instead"); + level = Level::DEBUG_INT; + } + mLevel = level; + } + + + void Logger::addAppender(Appender *pAppender) + { + // Avoid deadlock: + // - Handle warnings, before write lock is aquired + + // Keep objects with a 0 reference count safe + LogObjectPtr p_appender = pAppender; + + { + QReadLocker locker(&mObjectGuard); + + if(!p_appender) + { + logger()->warn("Adding null Appender to Logger '%1'", name()); + return; + } + if(mAppenders.contains(p_appender)) + { + logger()->warn("Adding of duplicate appender '%2' to logger '%1'", name(), p_appender->name()); + return; + } + } + { + QWriteLocker locker(&mObjectGuard); + + if(mAppenders.contains(p_appender)) + return; + mAppenders.append(p_appender); + } + } + + + Appender *Logger::appender(const QString &rName) const + { + QReadLocker locker(&mObjectGuard); + + Appender *p_appender; + Q_FOREACH(p_appender, mAppenders) + if (p_appender->name() == rName) + return p_appender; + return 0; + } + + + + void Logger::callAppenders(const LoggingEvent &rEvent) const + { + QReadLocker locker(&mObjectGuard); + + Appender *p_appender; + Q_FOREACH(p_appender, mAppenders) + p_appender->doAppend(rEvent); + if (additivity() && (parentLogger() != 0)) + parentLogger()->callAppenders(rEvent); + } + + + bool Logger::isAttached(Appender *pAppender) const + { + QReadLocker locker(&mObjectGuard); + + // Keep objects with a 0 reference count safe + LogObjectPtr p_appender = pAppender; + + return mAppenders.contains(p_appender); + } + + + void Logger::removeAllAppenders() + { + // Avoid deadlock: + // - Only log warnings without having the write log aquired + // - Hold a reference to all appenders so that the remove does not + // destruct the appender over the reference count while the write + // log is held. The appender may log messages. + + logger()->trace("Removing all appenders from logger '%1'", name()); + + QList< LogObjectPtr > appenders; + { + QWriteLocker locker(&mObjectGuard); + QMutableListIterator< LogObjectPtr > i(mAppenders); + while (i.hasNext()) + { + Appender *p_appender = i.next(); + ListAppender *p_listappender = qobject_cast(p_appender); + if (p_listappender && p_listappender->configuratorList()) + continue; + else + { + appenders << p_appender; + i.remove(); + } + } + } + appenders.clear(); + } + + + void Logger::removeAppender(Appender *pAppender) + { + // Avoid deadlock: + // - Only log warnings without having the write log aquired + // - Hold a reference to the appender so that the remove does not + // destruct the appender over the reference count while the write + // log is held. The appender may log messages. + + LogObjectPtr p_appender = pAppender; + + if(!p_appender) + { + logger()->warn("Request to remove null Appender from Logger '%1'", name()); + return; + } + int n; + { + QWriteLocker locker(&mObjectGuard); + + n = mAppenders.removeAll(p_appender); + } + if (n == 0) + { + logger()->warn("Request to remove Appender '%2', which is not part of Logger '%1' appenders", name(), p_appender->name()); + return; + } + } + + + void Logger::removeAppender(const QString &rName) + { + Appender *p_appender = appender(rName); + if (p_appender) + removeAppender(p_appender); + } + + + Level Logger::effectiveLevel() const + { + Q_ASSERT_X(LogManager::rootLogger()->level() != Level::NULL_INT, "Logger::effectiveLevel()", "Root logger level must not be NULL_INT"); + + QReadLocker locker(&mObjectGuard); + + const Logger *p_logger = this; + while (p_logger->level() == Level::NULL_INT) + p_logger = p_logger->parentLogger(); + return p_logger->level(); + } + + + bool Logger::isEnabledFor(Level level) const + { + if (mpLoggerRepository->isDisabled(level)) + return false; + return (effectiveLevel() <= level); + } + + + Logger *Logger::logger(const QString &rName) + { + return LogManager::logger(rName); + } + + + Logger *Logger::logger(const char *pName) + { + return LogManager::logger(QLatin1String(pName)); + } + + + Logger *Logger::rootLogger() + { + return LogManager::rootLogger(); + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug Logger::debug(QDebug &rDebug) const + { + QReadLocker locker(&mObjectGuard); + + QString parent_logger; + if (mpParent) + parent_logger = mpParent->name(); + + rDebug.nospace() << "Logger(" + << "name:" << name() << " " + << "appenders:" << mAppenders.count() << " " + << "additivity:" << mAdditivity << " " + << mLevel + << "parentLogger:" << parent_logger + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + void Logger::forcedLog(Level level, const QString &rMessage) const + { + QReadLocker locker(&mObjectGuard); + + LoggingEvent event(this, level, rMessage); + callAppenders(event); + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, const Logger &rLogger) + { + return rLogger.debug(debug); + } +#endif // QT_NO_DEBUG_STREAM + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/logger.h b/src/log4qt/log4qt/logger.h new file mode 100644 index 0000000..73a877d --- /dev/null +++ b/src/log4qt/log4qt/logger.h @@ -0,0 +1,1666 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: logger.h + * created: September 2007 + * author: Martin Heinrich + * + * + * changes: Sep 2008, Martin Heinrich: + * - Replaced usage of q_atomic_test_and_set_ptr with + * QBasicAtomicPointer + * + * + * Copyright 2007 - 2008 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_LOGGER_H +#define LOG4QT_LOGGER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include + +#include +#include +#include +#include "log4qt/helpers/logerror.h" +#include "log4qt/helpers/classlogger.h" +#include "log4qt/helpers/logobjectptr.h" +#include "log4qt/level.h" +#include "ukui-logmacros.h" + +#if QT_VERSION >= QT_VERSION_CHECK(4, 4, 0) +# ifndef Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE +# warning "QAtomicPointer test and set is not native. The macro Log4Qt::LOG4QT_DECLARE_STATIC_LOGGER is not thread-safe." +# endif +#endif + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + /*! + * LOG4QT_DECLARE_STATIC_LOGGER declares a static function \a FUNCTION that + * returns a pointer to a \ref Log4Qt::Logger "Logger" named after \a CLASS. + * + * On the first invocation the \ref Log4Qt::Logger "Logger" is requested + * by calling \ref Log4Qt::Logger::logger(const char *pName) + * "Logger::logger( #CLASS )". The pointer is stored to be returned on + * subsequent invocations. + * + * The following example shows how to use the macro to define a logger to be + * used within a class not derived from QObject. + * + * \code + * #file: counter.h + * + * #include logger.h + * + * class Counter + * { + * public: + * Counter(); + * Counter(int preset); + * private: + * int mCount; + * } + * \endcode + * \code + * #file: counter.cpp + * + * #include counter.h + * + * LOG4QT_DECLARE_STATIC_LOGGER(logger, Counter) + * + * Counter::Counter() : + * mCount(0) + * {} + * + * void Counter::Counter(int preset) : + * mCount(preset) + * { + * if (preset < 0) + * { + * logger()->warn("Invalid negative counter preset %1. Using 0 instead.", preset); + * mCount = 0; + * } + * } + * \endcode + * + * \note The function created by the macro is thread-safe. + * + * \sa \ref Log4Qt::Logger::logger(const char *pName) "Logger::logger(const char *pName)" + */ +#if QT_VERSION < QT_VERSION_CHECK(4, 4, 0) + #define LOG4QT_DECLARE_STATIC_LOGGER(FUNCTION, CLASS) \ + static Log4Qt::Logger *FUNCTION() \ + { \ + static Log4Qt::Logger *p_logger = 0; \ + if (!p_logger) \ + { \ + q_atomic_test_and_set_ptr( \ + &p_logger, \ + 0, \ + Log4Qt::Logger::logger( #CLASS )); \ + } \ + return p_logger; \ + } +#elif QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + #define LOG4QT_DECLARE_STATIC_LOGGER(FUNCTION, CLASS) \ + static Log4Qt::Logger *FUNCTION() \ + { \ + static QBasicAtomicPointer p_logger = \ + Q_BASIC_ATOMIC_INITIALIZER(0); \ + if (!p_logger) \ + { \ + p_logger.testAndSetOrdered(0, \ + Log4Qt::Logger::logger( #CLASS )); \ + } \ + return p_logger; \ + } +#else + #define LOG4QT_DECLARE_STATIC_LOGGER(FUNCTION, CLASS) \ + static Log4Qt::Logger *FUNCTION() \ + { \ + static QBasicAtomicPointer p_logger = \ + Q_BASIC_ATOMIC_INITIALIZER(0); \ + if (!p_logger.loadAcquire()) \ + { \ + p_logger.testAndSetOrdered(0, \ + Log4Qt::Logger::logger( #CLASS )); \ + } \ + return p_logger.loadAcquire(); \ + } +#endif + + /*! + * LOG4QT_DECLARE_QCLASS_LOGGER declares member functions to retrieve + * \ref Log4Qt::Logger "Logger" for the class it is used in. + * + * On the first invocation the \ref Log4Qt::Logger "Logger" is requested + * by a call to \ref Log4Qt::Logger::logger(const char *pName) + * "Logger::logger(const char *pName)". The pointer is stored to be + * returned on subsequent invocations. + * + * The following example shows how to use the macro to define a logger to be + * used within a class derived from QObject. + * + * \code + * #file: counter.h + * + * #include qobject.h + * #include logger.h + * + * class Counter : public QObject + * { + * Q_OBJECT + * LOG4QT_DECLARE_QCLASS_LOGGER + * public: + * Counter(); + * Counter(int preset); + * private: + * int mCount; + * } + * \endcode + * \code + * #file: counter.cpp + * + * #include counter.h + * + * Counter::Counter() : + * mCount(0) + * {} + * + * void Counter::Counter(int preset) + * mCount(preset) + * { + * if (preset < 0) + * { + * logger()->warn("Invalid negative counter preset %1. Using 0 instead.", preset); + * mCount = 0; + * } + * } + * \endcode + * + * \note The function created by the macro is thread-safe. + * + * \sa \ref Log4Qt::Logger::logger(const char *pName) "Logger::logger(const char *pName)", + * \ref Log4Qt::ClassLogger "ClassLogger" + */ + #define LOG4QT_DECLARE_QCLASS_LOGGER \ + private: \ + mutable Log4Qt::ClassLogger mLog4QtClassLogger; \ + public: \ + inline Log4Qt::Logger *logger() const \ + { return mLog4QtClassLogger.logger(this); } \ + private: + + class Appender; + class LoggingEvent; + class LoggerRepository; + + /*! + * \brief The class Logger provides logging services. + * + * A pointer to a logger can be retrieved by calling Logger::logger() or + * LogManager::logger() with the class name as argument. Because a logger + * is never destroyed it is possible to store the pointer to the logger. + * This way the lookup of the pointer in the repository is only required + * on the first logging operation. The macros \ref + * Log4Qt::LOG4QT_DECLARE_STATIC_LOGGER "LOG4QT_DECLARE_STATIC_LOGGER" and + * \ref Log4Qt::LOG4QT_DECLARE_QCLASS_LOGGER "LOG4QT_DECLARE_QCLASS_LOGGER" + * provide a thread-safe implementation to store the logger pointer. + * + * \note All the functions declared in this class are thread-safe. + */ + class LIBUKUILOG4QT_EXPORT Logger : public QObject + { + Q_OBJECT + + /*! + * The property holds, if the logger is additive. + * + * The default is true for being additive. + * + * \sa additive(), setAdditive() + */ + Q_PROPERTY(bool additivity READ additivity WRITE setAdditivity) + + /*! + * The property holds the level used by the logger. + * + * The default is Level::NULL_INT. + * \sa level(), setLevel() + */ + Q_PROPERTY(Level level READ level WRITE setLevel) + + /*! + * The property holds the LoggerRepository of the logger. + * + * \sa loggerRepository() + */ + Q_PROPERTY(LoggerRepository* loggerRepository READ loggerRepository) + + /*! + * The property holds the name of the logger. + * + * \sa name() + */ + Q_PROPERTY(QString name READ name) + + /*! + * The property holds the parent logger of the logger. + * + * \sa parentLogger() + */ + Q_PROPERTY(Logger* parentLogger READ parentLogger) + + LOG4QT_DECLARE_QCLASS_LOGGER + + protected: + Logger(LoggerRepository* pLoggerRepository, Level level, const QString &rName, Logger *pParent = 0); + virtual ~Logger(); + private: + Logger(const Logger &rOther); // Not implemented + Logger &operator=(const Logger &rOther); // Not implemented + + public: + bool additivity() const; + QList appenders() const; + Level level() const; + LoggerRepository *loggerRepository() const; + QString name() const; + Logger *parentLogger() const; + // JAVA: ResourceBundle *resourceBundle() const; + // JAVA: void setResourceBundle(ResourceBundle *pResourceBundle); + void setAdditivity(bool additivity); + virtual void setLevel(Level level); + + void addAppender(Appender *pAppender); + Appender *appender(const QString &rName) const; + void callAppenders(const LoggingEvent &rEvent) const; + bool isAttached(Appender *pAppender) const; + + /*! + * Removes all appenders that have been previously added from this + * Logger. + * + * To allow configurators to collect events during the configuration + * process ListAppenders with the configuratorList property set, will + * not be removed. + * + * \sa LisAppender::setConfiguratorList() + */ + void removeAllAppenders(); + + void removeAppender(Appender *pAppender); + void removeAppender(const QString &rName); + // JAVA: QString resourceBundleString(const QString &rKey) const; + + Level effectiveLevel() const; + bool isDebugEnabled() const; + + /*! + * Checks if this logger is enabled for a given Level \a level. If the + * logger is enabled the function returns true. Otherwise it returns + * false. + * + * A logger is enabled for a level, if the level is greater or equal + * then the repository threshold and greater and equal then the loggers + * effective level. + * + * \sa LoggerRepository::isDisabled(), effectiveLevel() + */ + bool isEnabledFor(Level level) const; + + bool isErrorEnabled() const; + bool isFatalEnabled() const; + bool isInfoEnabled() const; + bool isTraceEnabled() const; + bool isWarnEnabled() const; + + void debug(const QString &rMessage) const; + void debug(const LogError &rLogError) const; + void debug(const char *pMessage) const; + void debug(const char *pMessage, + const QString &rArg1) const; + void debug(const char *pMessage, + int arg1) const; + void debug(const char *pMessage, + const QString &rArg1, + const QString &rArg2) const; + void debug(const char *pMessage, + const QString &rArg1, + int arg2) const; + void debug(const char *pMessage, + int arg1, + const QString &rArg2) const; + void debug(const char *pMessage, + int arg1, + int arg2) const; + void debug(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const; + void debug(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const; + void debug(const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const; + void debug(const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const; + void debug(const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const; + void debug(const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const; + void debug(const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const; + void debug(const char *pMessage, + int arg1, + int arg2, + int arg3) const; + void debug(const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const; + + void error(const QString &rMessage) const; + void error(const LogError &rLogError) const; + void error(const char *pMessage) const; + void error(const char *pMessage, + const QString &rArg1) const; + void error(const char *pMessage, + int arg1) const; + void error(const char *pMessage, + const QString &rArg1, + const QString &rArg2) const; + void error(const char *pMessage, + const QString &rArg1, int arg2) const; + void error(const char *pMessage, + int arg1, + const QString &rArg2) const; + void error(const char *pMessage, + int arg1, + int arg2) const; + void error(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const; + void error(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const; + void error(const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const; + void error(const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const; + void error(const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const; + void error(const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const; + void error(const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const; + void error(const char *pMessage, + int arg1, + int arg2, + int arg3) const; + void error(const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const; + + void fatal(const QString &rMessage) const; + void fatal(const LogError &rLogError) const; + void fatal(const char *pMessage) const; + void fatal(const char *pMessage, + const QString &rArg1) const; + void fatal(const char *pMessage, + int arg1) const; + void fatal(const char *pMessage, + const QString &rArg1, + const QString &rArg2) const; + void fatal(const char *pMessage, + const QString &rArg1, + int arg2) const; + void fatal(const char *pMessage, + int arg1, + const QString &rArg2) const; + void fatal(const char *pMessage, + int arg1, + int arg2) const; + void fatal(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const; + void fatal(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const; + void fatal(const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const; + void fatal(const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const; + void fatal(const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const; + void fatal(const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const; + void fatal(const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const; + void fatal(const char *pMessage, + int arg1, + int arg2, + int arg3) const; + void fatal(const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const; + + void info(const QString &rMessage) const; + void info(const LogError &rLogError) const; + void info(const char *pMessage) const; + void info(const char *pMessage, + const QString &rArg1) const; + void info(const char *pMessage, + int arg1) const; + void info(const char *pMessage, + const QString &rArg1, + const QString &rArg2) const; + void info(const char *pMessage, + const QString &rArg1, + int arg2) const; + void info(const char *pMessage, + int arg1, + const QString &rArg2) const; + void info(const char *pMessage, + int arg1, + int arg2) const; + void info(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const; + void info(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const; + void info(const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const; + void info(const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const; + void info(const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const; + void info(const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const; + void info(const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const; + void info(const char *pMessage, + int arg1, + int arg2, + int arg3) const; + void info(const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const; + + void log(Level level, + const QString &rMessage) const; + void log(Level level, + const LogError &rLogError) const; + void log(Level level, + const char *pMessage) const; + void log(Level level, + const char *pMessage, + const QString &rArg1) const; + void log(Level level, + const char *pMessage, + int arg1) const; + void log(Level level, + const char *pMessage, + const QString &rArg1, + const QString &rArg2) const; + void log(Level level, + const char *pMessage, + const QString &rArg1, + int arg2) const; + void log(Level level, + const char *pMessage, + int arg1, + const QString &rArg2) const; + void log(Level level, + const char *pMessage, + int arg1, + int arg2) const; + void log(Level level, + const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const; + void log(Level level, + const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const; + void log(Level level, + const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const; + void log(Level level, + const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const; + void log(Level level, + const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const; + void log(Level level, + const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const; + void log(Level level, + const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const; + void log(Level level, + const char *pMessage, + int arg1, + int arg2, + int arg3) const; + void log(Level level, + const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const; + + // JAVA: void l7dlog(Level level, + // const QString &rKey); + // JAVA: void l7dlog(Level level, + // const QString &rKey, + // const QList rParameters); + + void trace(const QString &rMessage) const; + void trace(const LogError &rLogError) const; + void trace(const char *pMessage) const; + void trace(const char *pMessage, + const QString &rArg1) const; + void trace(const char *pMessage, + int arg1) const; + void trace(const char *pMessage, + const QString &rArg1, + const QString &rArg2) const; + void trace(const char *pMessage, + const QString &rArg1, + int arg2) const; + void trace(const char *pMessage, + int arg1, + const QString &rArg2) const; + void trace(const char *pMessage, + int arg1, + int arg2) const; + void trace(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const; + void trace(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const; + void trace(const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const; + void trace(const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const; + void trace(const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const; + void trace(const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const; + void trace(const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const; + void trace(const char *pMessage, + int arg1, + int arg2, + int arg3) const; + void trace(const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const; + + void warn(const QString &rMessage) const; + void warn(const LogError &rLogError) const; + void warn(const char *pMessage) const; + void warn(const char *pMessage, + const QString &rArg1) const; + void warn(const char *pMessage, + int arg1) const; + void warn(const char *pMessage, + const QString &rArg1, + const QString &rArg2) const; + void warn(const char *pMessage, + const QString &rArg1, + int arg2) const; + void warn(const char *pMessage, + int arg1, + const QString &rArg2) const; + void warn(const char *pMessage, + int arg1, + int arg2) const; + void warn(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const; + void warn(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const; + void warn(const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const; + void warn(const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const; + void warn(const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const; + void warn(const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const; + void warn(const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const; + void warn(const char *pMessage, + int arg1, + int arg2, + int arg3) const; + void warn(const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const; + + // LogManager operations + static Logger *logger(const QString &rName); + static Logger *logger(const char *pName); + static Logger *rootLogger(); + + protected: +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream \a rDebug + * and returns the stream. + * + * + * %Logger(name:"Log4Qt" appenders:0 additivity:true Level("NULL") + * parentLogger: "root" ) + * + * \sa QDebug, operator<<(QDebug debug, const Appender &rAppender) + */ + virtual QDebug debug(QDebug &rDebug) const; + friend QDebug operator<<(QDebug debug, + const Logger &rLogger); +#endif // QT_NO_DEBUG_STREAM + + void forcedLog(Level level, + const QString &rMessage) const; + + protected: + mutable QReadWriteLock mObjectGuard; + private: + const QString mName; + LoggerRepository* mpLoggerRepository; + volatile bool mAdditivity; + QList< LogObjectPtr > mAppenders; + Level mLevel; + Logger *mpParent; + + // Needs to be friend to create Logger objects + friend class Hierarchy; + }; + + + /****************************************************************************** + * Operators, Helper + ******************************************************************************/ + +#ifndef QT_NO_DEBUG_STREAM + /*! + * \relates Logger + * + * Writes all object member variables to the given debug stream \a debug and + * returns the stream. + * + * To handle subclassing the function uses the virtual member function debug(). + * This allows each class to generate its own output. + * + * \sa QDebug, debug() + */ + QDebug operator<<(QDebug debug, + const Logger &rLogger); +#endif // QT_NO_DEBUG_STREAM + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline bool Logger::additivity() const + { // QReadLocker locker(&mObjectGuard); // Read/Write of int is safe + return mAdditivity; } + + inline Level Logger::level() const + { // QReadLocker locker(&mObjectGuard); // Level is thread-safe + return mLevel; } + + inline LoggerRepository *Logger::loggerRepository() const + { // QReadLocker locker(&mObjectGuard); // Constant for object lifetime + return mpLoggerRepository; } + + inline QString Logger::name() const + { // QReadLocker locker(&mObjectGuard); // Constant for object lifetime + return mName; } + + inline Logger *Logger::parentLogger() const + { // QReadLocker locker(&mObjectGuard); // Constant for object lifetime + return mpParent; } + + inline void Logger::setAdditivity(bool additivity) + { // QWriteLocker locker(&mObjectGuard); // Read/Write of int is safe + mAdditivity = additivity; } + + // Level operations + + inline bool Logger::isDebugEnabled() const + { return isEnabledFor(Level::DEBUG_INT); } + + inline bool Logger::isErrorEnabled() const + { return isEnabledFor(Level::ERROR_INT); } + + inline bool Logger::isFatalEnabled() const + { return isEnabledFor(Level::FATAL_INT); } + + inline bool Logger::isInfoEnabled() const + { return isEnabledFor(Level::INFO_INT); } + + inline bool Logger::isTraceEnabled() const + { return isEnabledFor(Level::TRACE_INT); } + + inline bool Logger::isWarnEnabled() const + { return isEnabledFor(Level::WARN_INT); } + + // Log operations: debug + + inline void Logger::debug(const LogError &rLogError) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, rLogError.toString()); } + + inline void Logger::debug(const QString &rMessage) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, rMessage); } + + inline void Logger::debug(const char *pMessage) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage)); } + + inline void Logger::debug(const char *pMessage, + const QString &rArg1) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(rArg1)); } + + inline void Logger::debug(const char *pMessage, + int arg1) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(arg1)); } + + inline void Logger::debug(const char *pMessage, + const QString &rArg1, + const QString &rArg2) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2)); } + + inline void Logger::debug(const char *pMessage, + const QString &rArg1, + int arg2) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2)); } + + inline void Logger::debug(const char *pMessage, + int arg1, + const QString &rArg2) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2)); } + + inline void Logger::debug(const char *pMessage, + int arg1, + int arg2) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2)); } + + inline void Logger::debug(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2, rArg3)); } + + inline void Logger::debug(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2).arg(arg3)); } + + inline void Logger::debug(const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(rArg3)); } + + inline void Logger::debug(const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(arg3)); } + + inline void Logger::debug(const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(rArg3)); } + + inline void Logger::debug(const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(arg3)); } + + inline void Logger::debug(const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(rArg3)); } + + inline void Logger::debug(const char *pMessage, + int arg1, + int arg2, + int arg3) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(arg3)); } + + inline void Logger::debug(const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const + { if (isEnabledFor(Level::DEBUG_INT)) + forcedLog(Level::DEBUG_INT, QString::fromUtf8(pMessage).arg(rArg1.toString(), rArg2.toString(), rArg3.toString())); } + + // Log operations: error + + inline void Logger::error(const QString &rMessage) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, rMessage); } + + inline void Logger::error(const LogError &rLogError) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, rLogError.toString()); } + + inline void Logger::error(const char *pMessage) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage)); } + + inline void Logger::error(const char *pMessage, + const QString &rArg1) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(rArg1)); } + + inline void Logger::error(const char *pMessage, + int arg1) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(arg1)); } + + inline void Logger::error(const char *pMessage, + const QString &rArg1, + const QString &rArg2) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2)); } + + inline void Logger::error(const char *pMessage, + const QString &rArg1, + int arg2) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2)); } + + inline void Logger::error(const char *pMessage, + int arg1, + const QString &rArg2) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2)); } + + inline void Logger::error(const char *pMessage, + int arg1, + int arg2) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2)); } + + inline void Logger::error(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2, rArg3)); } + + inline void Logger::error(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2).arg(arg3)); } + + inline void Logger::error(const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(rArg3)); } + + inline void Logger::error(const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(arg3)); } + + inline void Logger::error(const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(rArg3)); } + + inline void Logger::error(const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(arg3)); } + + inline void Logger::error(const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(rArg3)); } + + inline void Logger::error(const char *pMessage, + int arg1, + int arg2, + int arg3) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(arg3)); } + + inline void Logger::error(const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const + { if (isEnabledFor(Level::ERROR_INT)) + forcedLog(Level::ERROR_INT, QString::fromUtf8(pMessage).arg(rArg1.toString(), rArg2.toString(), rArg3.toString())); } + + // Log operations: fatal + + inline void Logger::fatal(const QString &rMessage) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, rMessage); } + + inline void Logger::fatal(const LogError &rLogError) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, rLogError.toString()); } + + inline void Logger::fatal(const char *pMessage) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage)); } + + inline void Logger::fatal(const char *pMessage, + const QString &rArg1) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(rArg1)); } + + inline void Logger::fatal(const char *pMessage, + int arg1) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(arg1)); } + + inline void Logger::fatal(const char *pMessage, + const QString &rArg1, const QString &rArg2) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2)); } + + inline void Logger::fatal(const char *pMessage, + const QString &rArg1, int arg2) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2)); } + + inline void Logger::fatal(const char *pMessage, + int arg1, + const QString &rArg2) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2)); } + + inline void Logger::fatal(const char *pMessage, + int arg1, + int arg2) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2)); } + + inline void Logger::fatal(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2, rArg3)); } + + inline void Logger::fatal(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2).arg(arg3)); } + + inline void Logger::fatal(const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(rArg3)); } + + inline void Logger::fatal(const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(arg3)); } + + inline void Logger::fatal(const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(rArg3)); } + + inline void Logger::fatal(const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(arg3)); } + + inline void Logger::fatal(const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(rArg3)); } + + inline void Logger::fatal(const char *pMessage, + int arg1, + int arg2, + int arg3) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(arg3)); } + + inline void Logger::fatal(const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const + { if (isEnabledFor(Level::FATAL_INT)) + forcedLog(Level::FATAL_INT, QString::fromUtf8(pMessage).arg(rArg1.toString(), rArg2.toString(), rArg3.toString())); } + + // Log operations: info + + inline void Logger::info(const QString &rMessage) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, rMessage); } + + inline void Logger::info(const LogError &rLogError) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, rLogError.toString()); } + + inline void Logger::info(const char *pMessage) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage)); } + + inline void Logger::info(const char *pMessage, + const QString &rArg1) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(rArg1)); } + + inline void Logger::info(const char *pMessage, + int arg1) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(arg1)); } + + inline void Logger::info(const char *pMessage, + const QString &rArg1, + const QString &rArg2) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2)); } + + inline void Logger::info(const char *pMessage, + const QString &rArg1, + int arg2) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2)); } + + inline void Logger::info(const char *pMessage, + int arg1, + const QString &rArg2) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2)); } + + inline void Logger::info(const char *pMessage, + int arg1, + int arg2) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2)); } + + inline void Logger::info(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2, rArg3)); } + + inline void Logger::info(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2).arg(arg3)); } + + inline void Logger::info(const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(rArg3)); } + + inline void Logger::info(const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(arg3)); } + + inline void Logger::info(const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(rArg3)); } + + inline void Logger::info(const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(arg3)); } + + inline void Logger::info(const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(rArg3)); } + + inline void Logger::info(const char *pMessage, + int arg1, + int arg2, + int arg3) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(arg3)); } + + inline void Logger::info(const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const + { if (isEnabledFor(Level::INFO_INT)) + forcedLog(Level::INFO_INT, QString::fromUtf8(pMessage).arg(rArg1.toString(), rArg2.toString(), rArg3.toString())); } + + // Log operations: log + + inline void Logger::log(Level level, + const QString &rMessage) const + { if (isEnabledFor(level)) + forcedLog(level, rMessage); } + + inline void Logger::log(Level level, + const LogError &rLogError) const + { if (isEnabledFor(level)) + forcedLog(level, rLogError.toString()); } + + inline void Logger::log(Level level, + const char *pMessage) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage)); } + + inline void Logger::log(Level level, + const char *pMessage, + const QString &rArg1) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(rArg1)); } + + inline void Logger::log(Level level, + const char *pMessage, + int arg1) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(arg1)); } + + inline void Logger::log(Level level, + const char *pMessage, + const QString &rArg1, + const QString &rArg2) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(rArg1, rArg2)); } + + inline void Logger::log(Level level, + const char *pMessage, + const QString &rArg1, int arg2) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2)); } + + inline void Logger::log(Level level, + const char *pMessage, + int arg1, + const QString &rArg2) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2)); } + + inline void Logger::log(Level level, + const char *pMessage, + int arg1, + int arg2) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(arg1).arg(arg2)); } + + inline void Logger::log(Level level, + const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(rArg1, rArg2, rArg3)); } + + inline void Logger::log(Level level, + const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(rArg1, rArg2).arg(arg3)); } + + inline void Logger::log(Level level, + const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(rArg3)); } + + inline void Logger::log(Level level, + const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(arg3)); } + + inline void Logger::log(Level level, + const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(rArg3)); } + + inline void Logger::log(Level level, + const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(arg3)); } + + inline void Logger::log(Level level, + const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(rArg3)); } + + inline void Logger::log(Level level, + const char *pMessage, + int arg1, + int arg2, + int arg3) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(arg3)); } + + inline void Logger::log(Level level, + const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const + { if (isEnabledFor(level)) + forcedLog(level, QString::fromUtf8(pMessage).arg(rArg1.toString(), rArg2.toString(), rArg3.toString())); } + + // Log operations: trace + + inline void Logger::trace(const QString &rMessage) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, rMessage); } + + inline void Logger::trace(const LogError &rLogError) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, rLogError.toString()); } + + inline void Logger::trace(const char *pMessage) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage)); } + + inline void Logger::trace(const char *pMessage, + const QString &rArg1) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(rArg1)); } + + inline void Logger::trace(const char *pMessage, + int arg1) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(arg1)); } + + inline void Logger::trace(const char *pMessage, + const QString &rArg1, + const QString &rArg2) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2)); } + + inline void Logger::trace(const char *pMessage, + const QString &rArg1, + int arg2) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2)); } + + inline void Logger::trace(const char *pMessage, + int arg1, + const QString &rArg2) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2)); } + + inline void Logger::trace(const char *pMessage, + int arg1, + int arg2) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2)); } + + inline void Logger::trace(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2, rArg3)); } + + inline void Logger::trace(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2).arg(arg3)); } + + inline void Logger::trace(const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(rArg3)); } + + inline void Logger::trace(const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(arg3)); } + + inline void Logger::trace(const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(rArg3)); } + + inline void Logger::trace(const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(arg3)); } + + inline void Logger::trace(const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(rArg3)); } + + inline void Logger::trace(const char *pMessage, + int arg1, + int arg2, + int arg3) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(arg3)); } + + inline void Logger::trace(const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const + { if (isEnabledFor(Level::TRACE_INT)) + forcedLog(Level::TRACE_INT, QString::fromUtf8(pMessage).arg(rArg1.toString(), rArg2.toString(), rArg3.toString())); } + + // Log operations: warn + + inline void Logger::warn(const QString &rMessage) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, rMessage); } + + inline void Logger::warn(const LogError &rLogError) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, rLogError.toString()); } + + inline void Logger::warn(const char *pMessage) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage)); } + + inline void Logger::warn(const char *pMessage, + const QString &rArg1) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(rArg1)); } + + inline void Logger::warn(const char *pMessage, + int arg1) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(arg1)); } + + inline void Logger::warn(const char *pMessage, + const QString &rArg1, + const QString &rArg2) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2)); } + + inline void Logger::warn(const char *pMessage, + const QString &rArg1, + int arg2) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2)); } + + inline void Logger::warn(const char *pMessage, + int arg1, + const QString &rArg2) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2)); } + + inline void Logger::warn(const char *pMessage, + int arg1, + int arg2) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2)); } + + inline void Logger::warn(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2, rArg3)); } + + inline void Logger::warn(const char *pMessage, + const QString &rArg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(rArg1, rArg2).arg(arg3)); } + + inline void Logger::warn(const char *pMessage, + const QString &rArg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(rArg3)); } + + inline void Logger::warn(const char *pMessage, + const QString &rArg1, + int arg2, + int arg3) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(rArg1).arg(arg2).arg(arg3)); } + + inline void Logger::warn(const char *pMessage, + int arg1, + const QString &rArg2, + const QString &rArg3) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(rArg3)); } + + inline void Logger::warn(const char *pMessage, + int arg1, + const QString &rArg2, + int arg3) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(arg1).arg(rArg2).arg(arg3)); } + + inline void Logger::warn(const char *pMessage, + int arg1, + int arg2, + const QString &rArg3) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(rArg3)); } + + inline void Logger::warn(const char *pMessage, + int arg1, + int arg2, + int arg3) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(arg1).arg(arg2).arg(arg3)); } + + inline void Logger::warn(const char *pMessage, + const QVariant &rArg1, + const QVariant &rArg2, + const QVariant &rArg3) const + { if (isEnabledFor(Level::WARN_INT)) + forcedLog(Level::WARN_INT, QString::fromUtf8(pMessage).arg(rArg1.toString(), rArg2.toString(), rArg3.toString())); } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEinfo(Log4Qt::Logger, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_LOGGER_H diff --git a/src/log4qt/log4qt/loggerrepository.cpp b/src/log4qt/log4qt/loggerrepository.cpp new file mode 100644 index 0000000..b541bb2 --- /dev/null +++ b/src/log4qt/log4qt/loggerrepository.cpp @@ -0,0 +1,75 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: loggerrepository.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/loggerrepository.h" + +#include + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: LoggerRepository + **************************************************************************/ + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, + const LoggerRepository &rLoggerRepository) + { + return rLoggerRepository.debug(debug); + } +#endif // QT_NO_DEBUG_STREAM + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/loggerrepository.h b/src/log4qt/log4qt/loggerrepository.h new file mode 100644 index 0000000..fdf5b5c --- /dev/null +++ b/src/log4qt/log4qt/loggerrepository.h @@ -0,0 +1,129 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: loggerrepository.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_LOGGERREPOSITORY_H +#define LOG4QT_LOGGERREPOSITORY_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#include "log4qt/level.h" +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + class Logger; + + /*! + * \brief The class LoggerRepository is abstract base class for a logger + * repository. + */ + class LIBUKUILOG4QT_EXPORT LoggerRepository + { + public: + // LoggerRepository(); // Use compiler default + // LoggerRepository(const LoggerRepository &rOther); // Use compiler default + // virtual ~LoggerRepository(); // Use compiler default + // LoggerRepository &operator=(const LoggerRepository &rOther); // Use compiler default + + public: + virtual bool exists(const QString &rName) const = 0; + virtual Logger *logger(const QString &rName) = 0; + // JAVA: virtual Logger *logger(const String &rName, LoggerFactory *pFactory); + virtual QList loggers() const = 0; + virtual Logger *rootLogger() const = 0; + virtual Level threshold() const = 0; + virtual void setThreshold(Level level) = 0; + virtual void setThreshold(const QString &rThreshold) = 0; + + virtual bool isDisabled(Level level) = 0; + virtual void resetConfiguration() = 0; + virtual void shutdown() = 0; + + // JAVA: virtual void addHierarchyEventListener(HierarchyEventListener *pEventListener); + // JAVA: virtual void emitNoAppenderWarning(Logger *plogger) const; + // JAVA: virtual void fireAddAppenderEvent(Logger *plogger, Appender *pAppender) const; + + protected: +#ifndef QT_NO_DEBUG_STREAM + /*! + *\relates LoggerRepository + * + * Writes all object member variables to the given debug stream \a rDebug + * and returns the stream. + * + * The member function is used by + * QDebug operator<<(QDebug debug, const LoggerRepository &rLoggerRepository) + * to generate class specific output. + * + * \sa QDebug operator<<(QDebug debug, const LoggerRepository &rLoggerRepository) + */ + virtual QDebug debug(QDebug &rDebug) const = 0; + friend QDebug operator<<(QDebug debug, + const LoggerRepository &rLoggerRepository); +#endif + }; + + + /****************************************************************************** + * Operators, Helper + ******************************************************************************/ + +#ifndef QT_NO_DEBUG_STREAM + /*! + * \relates LoggerRepository + * Writes all object member variables to the given debug stream \a debug + * and returns the stream. + * + * To handle subclassing the function uses the virtual member function + * debug(). This allows each class to generate its own output. + * + * \sa QDebug, debug() + */ + QDebug operator<<(QDebug debug, + const LoggerRepository &rLoggerRepository); +#endif + + + /************************************************************************** + * Inline + **************************************************************************/ + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::LoggerRepository, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_LOGGERREPOSITORY_H diff --git a/src/log4qt/log4qt/loggingevent.cpp b/src/log4qt/log4qt/loggingevent.cpp new file mode 100644 index 0000000..753ede0 --- /dev/null +++ b/src/log4qt/log4qt/loggingevent.cpp @@ -0,0 +1,280 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: loggingevent.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *****************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/loggingevent.h" + +#include +#include +#include +#include +#include +#include +#include "log4qt/helpers/datetime.h" +#include "log4qt/helpers/initialisationhelper.h" +#include "log4qt/logger.h" +#include "log4qt/mdc.h" +#include "log4qt/ndc.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + LOG4QT_GLOBAL_STATIC(QMutex, sequence_guard) + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: LoggingEvent + **************************************************************************/ + + + LoggingEvent::LoggingEvent() : + QEvent(eventId), + mLevel(Level::NULL_INT), + mpLogger(0), + mMessage(), + mNdc(NDC::peek()), + mProperties(MDC::context()), + mSequenceNumber(nextSequenceNumber()), + mThreadName(), + mTimeStamp(DateTime::currentDateTime().toMilliSeconds()) + { + setThreadNameToCurrent(); + } + + + LoggingEvent::LoggingEvent(const Logger *pLogger, + Level level, + const QString &rMessage) : + QEvent(eventId), + mLevel(level), + mpLogger(pLogger), + mMessage(rMessage), + mNdc(NDC::peek()), + mProperties(MDC::context()), + mSequenceNumber(nextSequenceNumber()), + mThreadName(), + mTimeStamp(DateTime::currentDateTime().toMilliSeconds()) + { + setThreadNameToCurrent(); + } + + + LoggingEvent::LoggingEvent(const Logger *pLogger, + Level level, + const QString &rMessage, + qint64 timeStamp) : + QEvent(eventId), + mLevel(level), + mpLogger(pLogger), + mMessage(rMessage), + mNdc(NDC::peek()), + mProperties(MDC::context()), + mSequenceNumber(nextSequenceNumber()), + mThreadName(), + mTimeStamp(timeStamp) + { + setThreadNameToCurrent(); + } + + + LoggingEvent::LoggingEvent(const Logger *pLogger, + Level level, + const QString &rMessage, + const QString &rNdc, + const QHash &rProperties, + const QString &rThreadName, + qint64 timeStamp) : + QEvent(eventId), + mLevel(level), + mpLogger(pLogger), + mMessage(rMessage), + mNdc(rNdc), + mProperties(rProperties), + mSequenceNumber(nextSequenceNumber()), + mThreadName(rThreadName), + mTimeStamp(timeStamp) + { + } + + + QString LoggingEvent::loggerName() const + { + if (mpLogger) + return mpLogger->name(); + else + return QString(); + } + + + QString LoggingEvent::toString() const + { + return level().toString() + QLatin1Char(':') + message(); + } + + + qint64 LoggingEvent::sequenceCount() + { + QMutexLocker locker(sequence_guard()); + + return msSequenceCount; + } + + + qint64 LoggingEvent::startTime() + { + return InitialisationHelper::startTime(); + } + + + void LoggingEvent::setThreadNameToCurrent() + { + if (QThread::currentThread()) { + mThreadName = QThread::currentThread()->objectName(); + if (mThreadName.isEmpty()) { + mThreadName = QString("%1").arg((quint64)QThread::currentThreadId()); + } + } + } + + + qint64 LoggingEvent::nextSequenceNumber() + { + QMutexLocker locker(sequence_guard()); + + return ++msSequenceCount; + } + + + qint64 LoggingEvent::msSequenceCount = 0; + const QEvent::Type LoggingEvent::eventId = static_cast(QEvent::registerEventType()); + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DATASTREAM + QDataStream &operator<<(QDataStream &rStream, const LoggingEvent &rLoggingEvent) + { + QBuffer buffer; + buffer.open(QIODevice::WriteOnly); + QDataStream stream(&buffer); + + // version + quint16 version = 0; + stream << version; + // version 0 data + stream << rLoggingEvent.mLevel + << rLoggingEvent.loggerName() + << rLoggingEvent.mMessage + << rLoggingEvent.mNdc + << rLoggingEvent.mProperties + << rLoggingEvent.mSequenceNumber + << rLoggingEvent.mThreadName + << rLoggingEvent.mTimeStamp; + + buffer.close(); + rStream << buffer.buffer(); + return rStream; + } + + + QDataStream &operator>>(QDataStream &rStream, LoggingEvent &rLoggingEvent) + { + QByteArray array; + rStream >> array; + QBuffer buffer(&array); + buffer.open(QIODevice::ReadOnly); + QDataStream stream(&buffer); + + // version + quint16 version; + stream >> version; + // Version 0 data + QString logger; + stream >> rLoggingEvent.mLevel + >> logger + >> rLoggingEvent.mMessage + >> rLoggingEvent.mNdc + >> rLoggingEvent.mProperties + >> rLoggingEvent.mSequenceNumber + >> rLoggingEvent.mThreadName + >> rLoggingEvent.mTimeStamp; + if (logger.isEmpty()) + rLoggingEvent.mpLogger = 0; + else + rLoggingEvent.mpLogger = Logger::logger(logger); + + buffer.close(); + return rStream; + } +#endif // QT_NO_DATASTREAM + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, + const LoggingEvent &rLoggingEvent) + { + QString logger; + if (rLoggingEvent.logger() != 0) + logger = rLoggingEvent.logger()->name(); + + debug.nospace() << "LoggingEvent(" + << "level:" << rLoggingEvent.level().toString() << " " + << "logger:" << logger << " " + << "message:" << rLoggingEvent.message() << " " + << "sequencenumber:" << rLoggingEvent.sequenceNumber() << " " + << "threadname:" << rLoggingEvent.threadName() << " " + << "timestamp:" << rLoggingEvent.timeStamp() + << "(" << DateTime::fromMilliSeconds(rLoggingEvent.timeStamp()) << ")" + << "sequenceCount:" << rLoggingEvent.sequenceCount() + << ")"; + return debug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/loggingevent.h b/src/log4qt/log4qt/loggingevent.h new file mode 100644 index 0000000..9d20ab1 --- /dev/null +++ b/src/log4qt/log4qt/loggingevent.h @@ -0,0 +1,224 @@ +/****************************************************************************** +* +* package: Log4Qt +* file: loggingevent.h +* created: September 2007 +* author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +******************************************************************************/ + +#ifndef LOG4QT_LOG4QTEVENT_H +#define LOG4QT_LOG4QTEVENT_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#include +#include +#include +#include +#include "log4qt/level.h" +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + class Logger; + + /*! + * \brief The class LoggingEvent is the internal representation of a + * logging event. + * + * The class uses milliseconds since 1970-01-01T00:00:00, Coordinated + * Universal Time for time values. For converstion from and to QDateTime + * use DateTime. + */ + class LIBUKUILOG4QT_EXPORT LoggingEvent : public QEvent + { + public: + static const QEvent::Type eventId; + LoggingEvent(); + LoggingEvent(const Logger *pLogger, + Level level, + const QString &rMessage); + LoggingEvent(const Logger *pLogger, + Level level, + const QString &rMessage, + qint64 timeStamp); + LoggingEvent(const Logger *pLogger, + Level level, + const QString &rMessage, + const QString &rNdc, + const QHash &rProperties, + const QString &rThreadName, + qint64 timeStamp); + // LoggingEvent(const LoggingEvent &LoggingEvent::rOther); // Use compiler default + // virtual ~LoggingEvent(); // Use compiler default + // LoggingEvent &operator=(const LoggingEvent &LoggingEvent::rOther); // Use compiler default + + // JAVA: QString fqnOfLoggerClass() const; + Level level() const; + // LocationInformation locationInformation() const; + const Logger *logger() const; + QString message() const; + QHash mdc() const; + QString ndc() const; + QHash properties() const; + qint64 sequenceNumber() const; + QString threadName() const; + // JAVA: ThrowableInformation throwableInformation() const; + qint64 timeStamp() const; + + // JAVA: bool locationInformationExists() const; + QString loggerName() const; + QString property(const QString &rKey) const; + QStringList propertyKeys() const; + void setProperty(const QString &rKey, const QString &rValue); + // JAVA: QString throwableStrRep() const; + QString toString() const; + static qint64 sequenceCount(); + static qint64 startTime(); + + private: + void setThreadNameToCurrent(); + static qint64 nextSequenceNumber(); + + private: + Level mLevel; + const Logger *mpLogger; + QString mMessage; + QString mNdc; + QHash mProperties; + qint64 mSequenceNumber; + QString mThreadName; + qint64 mTimeStamp; + static qint64 msSequenceCount; + +#ifndef QT_NO_DATASTREAM + // Needs to be friend to stream objects + friend QDataStream &operator<<(QDataStream &rStream, + const LoggingEvent &rLoggingEvent); + friend QDataStream &operator>>(QDataStream &rStream, + LoggingEvent &rLoggingEvent); +#endif // QT_NO_DATASTREAM + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + +#ifndef QT_NO_DATASTREAM + /*! + * \relates LoggingEvent + * + * Writes the given error \a rLoggingEvent to the given stream \a rStream, + * and returns a reference to the stream. + */ + QDataStream &operator<<(QDataStream &rStream, + const LoggingEvent &rLoggingEvent); + + /*! + * \relates LoggingEvent + * + * Reads an error from the given stream \a rStream into the given + * error \a rLoggingEvent, and returns a reference to the stream. + */ + QDataStream &operator>>(QDataStream &rStream, + LoggingEvent &rLoggingEvent); +#endif // QT_NO_DATASTREAM + +#ifndef QT_NO_DEBUG_STREAM + /*! + * \relates LoggingEvent + * + * Writes all object member variables to the given debug stream \a debug and + * returns the stream. + * + * + * %LoggingEvent(level:"WARN" logger:"Log4Qt::Properties" + * message:"Unknown escape sequence '\j' in property starting at line 1" + * sequencenumber:14 threadname:"main" + * timestamp:1194337148937(QDateTime("Tue Nov 6 03:19:08 2007") ) + * sequenceCount: 14 ) + * + * + * \sa QDebug + */ + QDebug operator<<(QDebug debug, + const LoggingEvent &rLoggingEvent); +#endif // QT_NO_DEBUG_STREAM + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline Level LoggingEvent::level() const + { return mLevel; } + + inline const Logger *LoggingEvent::logger() const + { return mpLogger; } + + inline QString LoggingEvent::message() const + { return mMessage; } + + inline QHash LoggingEvent::mdc() const + { return mProperties; } + + inline QString LoggingEvent::ndc() const + { return mNdc; } + + inline QHash LoggingEvent::properties() const + { return mProperties; } + + inline qint64 LoggingEvent::sequenceNumber() const + { return mSequenceNumber; } + + inline QString LoggingEvent::threadName() const + { return mThreadName; } + + inline qint64 LoggingEvent::timeStamp() const + { return mTimeStamp; } + + inline QString LoggingEvent::property(const QString &rKey) const + { return mProperties.value(rKey); } + + inline QStringList LoggingEvent::propertyKeys() const + { return QStringList(mProperties.keys()); } + + inline void LoggingEvent::setProperty(const QString &rKey, const QString &rValue) + { mProperties.insert(rKey, rValue); } + + +} // namespace Log4Qt + + +Q_DECLARE_METATYPE(Log4Qt::LoggingEvent) +Q_DECLARE_TYPEINFO(Log4Qt::LoggingEvent, Q_MOVABLE_TYPE); + + +#endif // LOG4QT_LOG4QTEVENT_H diff --git a/src/log4qt/log4qt/logmanager.cpp b/src/log4qt/log4qt/logmanager.cpp new file mode 100644 index 0000000..f1b478f --- /dev/null +++ b/src/log4qt/log4qt/logmanager.cpp @@ -0,0 +1,511 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: logmanager.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * changes: Sep 2008, Martin Heinrich: + * - Resolved compilation problem with Microsoft Visual Studio 2005 + * Feb 2009, Martin Heinrich + * - Fixed VS 2008 unreferenced formal parameter warning by using + * Q_UNUSED in operator<<. + * + * + * Copyright 2007 - 2009 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/logmanager.h" + +#include +#include +#include +#include +#include +#include +#include "log4qt/consoleappender.h" +#include "log4qt/helpers/datetime.h" +#include "log4qt/helpers/initialisationhelper.h" +#include "log4qt/helpers/optionconverter.h" +#include "log4qt/hierarchy.h" +#include "log4qt/propertyconfigurator.h" +#include "log4qt/ttcclayout.h" +#include "log4qt/varia/denyallfilter.h" +#include "log4qt/varia/levelrangefilter.h" + +#include + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + LOG4QT_DECLARE_STATIC_LOGGER(static_logger, Log4Qt::LogManager) + LOG4QT_GLOBAL_STATIC(QMutex, singleton_guard) + + + + /************************************************************************** + * Class implementation: LogManager + **************************************************************************/ + + + LogManager::LogManager() : + mObjectGuard(QMutex::Recursive), // Recursive for doStartup() to call doConfigureLogLogger() + mpLoggerRepository(new Hierarchy()), + mHandleQtMessages(false), + mOldQtMsgHandler(0) + { + } + + + LogManager::~LogManager() + { + static_logger()->warn("Unexpected destruction of LogManager"); + + // doSetConfigureHandleQtMessages(false); + // delete mpLoggerRepository; + } + + + Logger *LogManager::rootLogger() + { + return instance()->mpLoggerRepository->rootLogger(); + } + + + QList LogManager::loggers() + { + return instance()->mpLoggerRepository->loggers(); + } + + + Level LogManager::threshold() + { + return instance()->mpLoggerRepository->threshold(); + } + + + void LogManager::setThreshold(Level level) + { + instance()->mpLoggerRepository->setThreshold(level); + } + + + bool LogManager::exists(const char *pName) + { + return instance()->mpLoggerRepository->exists(QLatin1String(pName)); + } + + + LogManager *LogManager::instance() + { + // Do not use LOG4QT_GLOBAL_STATIC. The LogManager is rather expensive + // to construct, an exit handler must be set and doStartup must be + // called. + + if (!mspInstance) + { + QMutexLocker locker(singleton_guard()); + if (!mspInstance) + { + mspInstance = new LogManager; + // qAddPostRoutine(shutdown); + atexit(shutdown); + mspInstance->doConfigureLogLogger(); + mspInstance->welcome(); + mspInstance->doStartup(); + } + } + return mspInstance; + } + + + Logger *LogManager::logger(const QString &rName) + { + return instance()->mpLoggerRepository->logger(rName); + } + + + void LogManager::resetConfiguration() + { + setHandleQtMessages(false); + instance()->mpLoggerRepository->resetConfiguration(); + configureLogLogger(); + } + + + const char* LogManager::version() + { + return LOG4QT_VERSION_STR; + } + + + void LogManager::shutdown() + { + instance()->mpLoggerRepository->shutdown(); + } + + + void LogManager::doSetHandleQtMessages(bool handleQtMessages) + { + QMutexLocker locker(&mObjectGuard); + + if (instance()->mHandleQtMessages == handleQtMessages) + return; + + instance()->mHandleQtMessages = handleQtMessages; + if (instance()->mHandleQtMessages) + { + static_logger()->trace("Activate Qt message handling"); +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + instance()->mOldQtMsgHandler = qInstallMsgHandler(qtMessageHandler); +#else + instance()->mOldQtMsgHandler = qInstallMessageHandler(qtMessageHandler); +#endif + } + else + { + static_logger()->trace("Deactivate Qt message handling"); +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + qInstallMsgHandler(instance()->mOldQtMsgHandler); +#else + qInstallMessageHandler(instance()->mOldQtMsgHandler); +#endif + } + } + + + void LogManager::doConfigureLogLogger() + { + QMutexLocker locker(&instance()->mObjectGuard); + + // Level + QString value = InitialisationHelper::setting(QLatin1String("Debug"), + QLatin1String("ERROR")); + logLogger()->setLevel(OptionConverter::toLevel(value, Level::DEBUG_INT)); + + // Common layout + TTCCLayout *p_layout = new TTCCLayout(); + p_layout->setName(QLatin1String("LogLog TTCC")); + p_layout->setContextPrinting(false); + p_layout->activateOptions(); + + // Common deny all filter + Filter *p_denyall = new DenyAllFilter(); + p_denyall->activateOptions(); + + // ConsoleAppender on stdout for all events <= INFO + ConsoleAppender *p_appender; + LevelRangeFilter *p_filter; + p_appender = new ConsoleAppender(p_layout, ConsoleAppender::STDOUT_TARGET); + p_filter = new LevelRangeFilter(); + p_filter->setNext(p_denyall); + p_filter->setLevelMin(Level::NULL_INT); + p_filter->setLevelMax(Level::INFO_INT); + p_filter->activateOptions(); + p_appender->setName(QLatin1String("LogLog stdout")); + p_appender->addFilter(p_filter); + p_appender->activateOptions(); + logLogger()->addAppender(p_appender); + + // ConsoleAppender on stderr for all events >= WARN + p_appender = new ConsoleAppender(p_layout, ConsoleAppender::STDERR_TARGET); + p_filter = new LevelRangeFilter(); + p_filter->setNext(p_denyall); + p_filter->setLevelMin(Level::WARN_INT); + p_filter->setLevelMax(Level::OFF_INT); + p_filter->activateOptions(); + p_appender->setName(QLatin1String("LogLog stderr")); + p_appender->addFilter(p_filter); + p_appender->activateOptions(); + logLogger()->addAppender(p_appender); + } + + + void LogManager::doStartup() + { + QMutexLocker locker(&instance()->mObjectGuard); + + // Override + QString default_value = QLatin1String("false"); + QString value = InitialisationHelper::setting(QLatin1String("DefaultInitOverride"), + default_value); + if (value != default_value) + { + static_logger()->debug("DefaultInitOverride is set. Aborting default initialisation"); + return; + } + + // Configuration using setting Configuration + value = InitialisationHelper::setting(QLatin1String("Configuration")); + if (QFile::exists(value)) + { + static_logger()->debug("Default initialisation configures from file '%1' specified by Configure", value); + PropertyConfigurator::configure(value); + return; + } + + // Configuration using setting + if (QCoreApplication::instance()) + { + const QLatin1String log4qt_group("Log4Qt"); + const QLatin1String properties_group("Properties"); + QSettings s; + s.beginGroup(log4qt_group); + if (s.childGroups().contains(properties_group)) + { + const QString group(QLatin1String("Log4Qt/Properties")); + static_logger()->debug("Default initialisation configures from setting '%1/%2'", log4qt_group, properties_group); + s.beginGroup(properties_group); + PropertyConfigurator::configure(s); + return; + } + } + + // Configuration using default file + const QString default_file(QLatin1String("log4qt.properties")); + if (QFile::exists(default_file)) + { + static_logger()->debug("Default initialisation configures from default file '%1'", default_file); + PropertyConfigurator::configure(default_file); + return; + } + + static_logger()->debug("Default initialisation leaves package unconfigured"); + } + + + void LogManager::welcome() + { + static_logger()->info("Initialising Log4Qt %1", + QLatin1String(LOG4QT_VERSION_STR)); + + // Debug: Info + if (static_logger()->isDebugEnabled()) + { + // Create a nice timestamp with UTC offset + DateTime start_time = DateTime::fromMilliSeconds(InitialisationHelper::startTime()); + QString offset; + { + QDateTime utc = start_time.toUTC(); + QDateTime local = start_time.toLocalTime(); + QDateTime local_as_utc = QDateTime(local.date(), local.time(), Qt::UTC); + int min = utc.secsTo(local_as_utc) / 60; + if (min < 0) + offset += QLatin1Char('-'); + else + offset += QLatin1Char('+'); + min = abs(min); + offset += QString::number(min / 60).rightJustified(2, QLatin1Char('0')); + offset += QLatin1Char(':'); + offset += QString::number(min % 60).rightJustified(2, QLatin1Char('0')); + } + static_logger()->debug("Program startup time is %1 (UTC%2)", + start_time.toString(QLatin1String("ISO8601")), + offset); + static_logger()->debug("Internal logging uses the level %1", + logLogger()->level().toString()); + } + + // Trace: Dump settings + if (static_logger()->isTraceEnabled()) + { + static_logger()->trace("Settings from the system environment:"); + QString entry; + Q_FOREACH (entry, InitialisationHelper::environmentSettings().keys()) + static_logger()->trace(" %1: '%2'", + entry, + InitialisationHelper::environmentSettings().value(entry)); + + static_logger()->trace("Settings from the application settings:"); + if (QCoreApplication::instance()) + { + const QLatin1String log4qt_group("Log4Qt"); + const QLatin1String properties_group("Properties"); + static_logger()->trace(" %1:", log4qt_group); + QSettings s; + s.beginGroup(log4qt_group); + Q_FOREACH (entry, s.childKeys()) + static_logger()->trace(" %1: '%2'", + entry, + s.value(entry).toString()); + static_logger()->trace(" %1/%2:", log4qt_group, properties_group); + s.beginGroup(properties_group); + Q_FOREACH (entry, s.childKeys()) + static_logger()->trace(" %1: '%2'", + entry, + s.value(entry).toString()); + } else + static_logger()->trace(" QCoreApplication::instance() is not available"); + } + } + +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + void LogManager::qtMessageHandler(QtMsgType type, const char *pMessage) + { + Level level; + switch (type) + { + case QtDebugMsg: + level = Level::DEBUG_INT; + break; + case QtWarningMsg: + level = Level::WARN_INT; + break; + case QtInfoMsg: + level = Level::INFO_INT; + break; + case QtCriticalMsg: + level = Level::ERROR_INT; + break; + case QtFatalMsg: + level = Level::FATAL_INT; + break; + default: + level = Level::TRACE_INT; + } + instance()->qtLogger()->log(level, pMessage); + + // Qt fatal behaviour copied from global.cpp qt_message_output() + // begin { + + if ((type == QtFatalMsg) || + ((type == QtWarningMsg) && (!qgetenv("QT_FATAL_WARNINGS").isNull())) ) + { +#if defined(Q_CC_MSVC) && defined(QT_DEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) + // get the current report mode + int reportMode = _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW); + _CrtSetReportMode(_CRT_ERROR, reportMode); + int ret = _CrtDbgReport(_CRT_ERROR, __FILE__, __LINE__, QT_VERSION_STR, pMessage); + if (ret == 0 && reportMode & _CRTDBG_MODE_WNDW) + return; // ignore + else if (ret == 1) + _CrtDbgBreak(); +#endif + +#if defined(Q_OS_UNIX) && defined(QT_DEBUG) + //abort(); // trap; generates core dump +#else + //exit(1); // goodbye cruel world +#endif + } + + // } end + } +#else + void LogManager::qtMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message) + { + Level level; + switch (type) + { + case QtDebugMsg: + level = Level::DEBUG_INT; + break; + case QtWarningMsg: + level = Level::WARN_INT; + break; + case QtInfoMsg: + level = Level::INFO_INT; + break; + case QtCriticalMsg: + level = Level::ERROR_INT; + break; + case QtFatalMsg: + level = Level::FATAL_INT; + break; + default: + level = Level::TRACE_INT; + } + QString newMsg = context.file?QString("|PID:%1|%2:%3(%4)|").arg(getpid()).arg(context.file).arg(context.line).arg(context.function):QString("|PID:%1|").arg(getpid()); + instance()->qtLogger()->log(level, newMsg+message); + + // Qt fatal behaviour copied from global.cpp qt_message_output() + // begin { + + if ((type == QtFatalMsg) || + ((type == QtWarningMsg) && (!qgetenv("QT_FATAL_WARNINGS").isNull())) ) + { +#if defined(Q_CC_MSVC) && defined(QT_DEBUG) && defined(_DEBUG) && defined(_CRT_ERROR) + // get the current report mode + int reportMode = _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW); + _CrtSetReportMode(_CRT_ERROR, reportMode); + int ret = _CrtDbgReport(_CRT_ERROR, __FILE__, __LINE__, QT_VERSION_STR, message.toUtf8().constData()); + if (ret == 0 && reportMode & _CRTDBG_MODE_WNDW) + return; // ignore + else if (ret == 1) + _CrtDbgBreak(); +#endif + +#if defined(Q_OS_UNIX) && defined(QT_DEBUG) + //abort(); // trap; generates core dump +#else + //exit(1); // goodbye cruel world +#endif + } + + // } end + } +#endif + + + + LogManager *LogManager::mspInstance = 0; + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, const LogManager &rLogManager) + { + Q_UNUSED(rLogManager); // To avoid warning C4100 on VS 2008 + QList loggers = rLogManager.loggers(); + debug.nospace() << "LogManager(" + << "loggerrepository:" << *rLogManager.loggerRepository() + << "log-level:" << rLogManager.logLogger()->level().toString() + << "log-appenders:" << rLogManager.logLogger()->appenders().count() + << "qt-level:" << rLogManager.qtLogger()->level().toString() + << "qt-appenders:" << rLogManager.qtLogger()->appenders().count() + << "handleqtmessages:" << rLogManager.handleQtMessages() + << ")"; + return debug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/logmanager.h b/src/log4qt/log4qt/logmanager.h new file mode 100644 index 0000000..7911742 --- /dev/null +++ b/src/log4qt/log4qt/logmanager.h @@ -0,0 +1,341 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: logmanager.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_LOGMANAGER_H +#define LOG4QT_LOGMANAGER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include + +#include +#include +#include +#include +#include "log4qt/level.h" +#include "log4qt/logger.h" +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + class LoggerRepository; + + /*! + * \brief The class LogManager manages Logger in the default + * LoggerRepository. + * + * The LogManager manages logger in a single Hierarchy instance. It + * provides access to special logger over the logLogger(), qtLogger() + * and rootLogger() member functions. + * + * The LogManager is handling the initialisation on startup. The + * initialisation procedure will first attempt to configure the package + * based on environment variables. If the attempt fails it will check for + * the existence of configuration files in several location. For detailed + * description of the initialisation procedure see \ref Init + * "Initialization procedure". + * + * Messages created by qDebug(), qWarning(), qCritical() and qFatal() can + * be can be handled by the LogManager. By default the message handling + * is disabled. It can be enabled by calling setHandleQtMessages(). Once + * enabled all messages are logged using the logger qtLogger(). + * + * The Log4Qt runtime version is accessible over version(). The macros + * \ref Log4Qt::LOG4QT_VERSION "LOG4QT_VERSION" and + * \ref Log4Qt::LOG4QT_VERSION_STR "LOG4QT_VERSION_STR" provide the + * compile time version. + * + * \note All the functions declared in this class are thread-safe. + */ + class LIBUKUILOG4QT_EXPORT LogManager + { + private: + LogManager(); + LogManager(const LogManager &rOther); // Not implemented + virtual ~LogManager(); + LogManager &operator=(const LogManager &rOther); // Not implemented + + public: + /*! + * Returns if the handling of messages created by calls to qDebug(), + * qWarning(), qCritical() and qFatal() is activated. + * + * \sa setHandleQtMessages() + */ + static bool handleQtMessages(); + + static LoggerRepository *loggerRepository(); + + /*! + * Returns the logger used for logging internal messages. See + * \ref LogLog "Logging within the package" for more details. + * + * Calling this function is equivalent to calling logger("Log4Qt"). + */ + static Logger *logLogger(); + + /*! + * Returns a pointer to the logger used for logging messages created by + * calls to qDebug(), qWarning(), qCritical() and qFatal(). + * + * Calling this function is equivalent to calling logger("Qt"). + * + * \sa setHandleQtMessages() + */ + static Logger *qtLogger(); + + static Logger *rootLogger(); + static QList loggers(); + static Level threshold(); + static void setThreshold(Level level); + + /*! + * Activates or deactivates the handling of messages created by calls + * to qDebug(), qWarning(), qCritical() and qFatal() is activated. + * + * If activated, a Qt message handler is installed. Messages are logged + * using the logger returned by qtLogger(). For fatal messages the same + * exit procedure is implemented as for qFatal(). + * + * The following mappping is used from QtMsgType to Level: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    QtMsgType     %Level
QtDebugMsg Level::DEBUG_INT
QtWarningMsg Level::WARN_INT
QtCriticalMsg Level::ERROR_INT
QtFatalMsg Level::FATAL_INT
QtSystemMsg Level::TRACE_INT
+ * + * The default value is false for not handling Qt messages. + * + * \sa handleQtMessages(), qInstallMsgHandler(), qFatal() + */ + static void setHandleQtMessages(bool handleQtMessages); + + /*! + * Configures the logging for the package to its default behaviour. + * + * The logger logLogger() is configured to be not additive. Messages + * with the level Level::ERROR_INT and Level::FATAL_INT are written + * to \c stderr using a ConsoleAppender. The remaining messages are + * written to \c stdout using a second ConsoleAppender. The level is + * read from the system environment or application settings using + * InitialisationHelper::setting() with the key \c Debug. If a level + * value is found, but it is not a valid Level string, + * Level::DEBUG_INT is used. If no level string is found + * Level::ERROR_INT is used. + * + * The function does not remove any appender from the logger + * logLogger(). + * + * \sa \ref LogLog "Logging within the package", + * \ref Env "Environment Variables", + * resetConfiguration(), InitialisationHelper::setting() + */ + static void configureLogLogger(); + + static bool exists(const char *pName); + // JAVA: void fireAddAppenderEvent(Logger *pLogger, Appender *pAppender); + + /*! + * Returns the LogManager instance. + */ + static LogManager *instance(); + + static Logger *logger(const QString &rName); + + /*! + * Reset all values contained in logger repository to their default. + * + * All appenders are removed from all loggers. The loggers are handled + * in no particular order. The last loggers to be reset are qtLogger(), + * logLogger() and rootLogger() in that order. + * + * The handling of messages created by calls to qDebug(), qWarning(), + * qCritical() and qFatal() is deactivated. + * + * The internal logging is initialised to its default bahaviour + * using configureLogLogger(). + * + * \sa LoggerRepository::resetConfiguration(), setHandleQtMessages(), + * configureLogLogger() + */ + static void resetConfiguration(); + + static void shutdown(); + + /*! + * Executes the default initialisation procedure of the package. + * + * The function will test for the setting \c DefaultInitOverride in + * the system environment and application settings using + * \ref InitialisationHelper::setting(). If the value is present and + * set to anything else then \c false, the initialisation is aborted. + *
+ * The system environment and application settings are tested for the + * setting \c Configuration. If it is found and it is a valid path to + * a file, the package is configured with the file using + * \ref PropertyConfigurator::doConfigure(const QString &, LoggerRepository *) + * "PropertyConfigurator::doConfigure()". If the setting + * \c Configuration is not available and a QCoreApplication object is + * present, the application settings are tested for a group + * \c Log4Qt/Properties. If the group exists, the package is configured + * with the setting using the + * \ref PropertyConfigurator::doConfigure(const QSettings &r, LoggerRepository *) + * "PropertyConfiguratordoConfigure()". If neither a configuration + * file nor configuration settings could be found, the current working + * directory is searched for the file \c "log4qt.properties". If it is + * found, the package is configured with the file using + * \ref PropertyConfigurator::doConfigure(const QString &, LoggerRepository *) + * "PropertyConfigurator::doConfigure()". + * + * \sa \ref Init "Initialization procedure", + * \ref Env "Environment Variables", + * InitialisationHelper::setting() + */ + static void startup(); + + /*! + * Returns the version number of Log4Qt at run-time. This may be a + * different version than the version the application was compiled + * against. + * + * \sa \ref Log4Qt::LOG4QT_VERSION "LOG4QT_VERSION", + * \ref Log4Qt::LOG4QT_VERSION_STR "LOG4QT_VERSION_STR" + + */ + static const char* version(); + + private: + void doSetHandleQtMessages(bool handleQtMessages); + void doConfigureLogLogger(); + void doStartup(); + void welcome(); +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + static void qtMessageHandler(QtMsgType type, + const char *pMessage); +#else + static void qtMessageHandler(QtMsgType type, + const QMessageLogContext &context, + const QString &message); +#endif + + + private: + mutable QMutex mObjectGuard; + LoggerRepository *mpLoggerRepository; + Logger *mpNullLogger; + bool mHandleQtMessages; +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + QtMsgHandler mOldQtMsgHandler; +#else + QtMessageHandler mOldQtMsgHandler; +#endif + static LogManager *mspInstance; + }; + + + /*************************************************************************** + * Operators, Helper + ***************************************************************************/ + + #ifndef QT_NO_DEBUG_STREAM + /*! + * \relates LogManager + * + * Writes all object member variables to the given debug stream \a rDebug and + * returns the stream. + * + * + * %LogManager(loggerrepository:Hierarchy(loggers:6 root-level:"DEBUG" + * root-appenders:0 log-level: "NULL" log-appenders:0 + * qt-level: "NULL" qt-appenders:0 handleqtmessages: false ) + * + * \sa QDebug + */ + QDebug operator<<(QDebug debug, + const LogManager &rLogManager); + #endif // QT_NO_DEBUG_STREAM + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline LoggerRepository *LogManager::loggerRepository() + { // QMutexLocker locker(&instance()->mObjectGuard); // Constant for object lifetime + return instance()->mpLoggerRepository; } + + inline bool LogManager::handleQtMessages() + { // QMutexLocker locker(&instance()->mObjectGuard); // Read/Write of bool is safe + return instance()->mHandleQtMessages; } + + inline Logger *LogManager::logLogger() + { // QMutexLocker locker(&instance()->mObjectGuard); // Constant for object lifetime + return logger(QLatin1String("Log4Qt")); } + + inline Logger *LogManager::qtLogger() + { // QMutexLocker locker(&instance()->mObjectGuard); // Constant for object lifetime + return logger(QLatin1String("Qt")); } + + inline void LogManager::setHandleQtMessages(bool handleQtMessages) + { instance()->doSetHandleQtMessages(handleQtMessages); } + + inline void LogManager::configureLogLogger() + { instance()->doConfigureLogLogger(); } + + inline void LogManager::startup() + { instance()->doStartup(); } + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::LogManager, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_LOGMANAGER_H diff --git a/src/log4qt/log4qt/mdc.cpp b/src/log4qt/log4qt/mdc.cpp new file mode 100644 index 0000000..5ba2ba8 --- /dev/null +++ b/src/log4qt/log4qt/mdc.cpp @@ -0,0 +1,116 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: mdc.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * changes Feb 2009, Martin Heinrich + * - Fixed unreferenced formal parameter warning by using + * Q_UNUSED in operator<<. + * + * + * Copyright 2007 - 2009 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *****************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/mdc.h" + +#include +#include +#include +#include "log4qt/helpers/initialisationhelper.h" +#include "log4qt/logger.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: MDC + **************************************************************************/ + + + QString MDC::get(const QString &rKey) + { + if (!instance()->mHash.hasLocalData()) + return QString(); + + return instance()->mHash.localData()->value(rKey); + } + + + QHash MDC::context() + { + if (!instance()->mHash.hasLocalData()) + return QHash(); + + return *instance()->mHash.localData(); + } + + + LOG4QT_IMPLEMENT_INSTANCE(MDC) + + + QHash *MDC::localData() + { + if (!instance()->mHash.hasLocalData()) + instance()->mHash.setLocalData(new QHash); + return instance()->mHash.localData(); + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, const MDC &rMDC) + { + Q_UNUSED(rMDC); // To avoid warning C4100 on VS 2008 + debug.nospace() << "MDC(" + << "thread:" << QThread::currentThread()->objectName() << " " + << "context:" << rMDC.context() + << ")"; + return debug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/mdc.h b/src/log4qt/log4qt/mdc.h new file mode 100644 index 0000000..abed318 --- /dev/null +++ b/src/log4qt/log4qt/mdc.h @@ -0,0 +1,123 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: mdc.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_MDC_H +#define LOG4QT_MDC_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#include +#include +#include "log4qt/log4qt.h" +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + +/*! + * \brief The class MDC implements a mapped diagnostic context. + * + * \note All the functions declared in this class are thread-safe. + */ + class LIBUKUILOG4QT_EXPORT MDC + { + private: + MDC(); + MDC(const MDC &rOther); // Not implemented + // virtual ~MDC(); // Use compiler default + MDC &operator=(const MDC &rOther); // Not implemented + + public: + static QString get(const QString &rKey); + static QHash context(); + + /*! + * Returns the MDC instance. + */ + static MDC *instance(); + + static void put(const QString &rKey, const QString &rValue); + static void remove(const QString &rKey); + + private: + static QHash *localData(); + + private: + QThreadStorage< QHash * > mHash; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + #ifndef QT_NO_DEBUG_STREAM + /*! + * \relates MDC + * + * Writes all object member variables to the given debug stream \a rDebug + * and returns the stream. + * + * + * %MDC(thread:"main" context:QHash(("login", "Peter")("database", "UAT")) ) + * + * \sa QDebug + */ + QDebug operator<<(QDebug debug, + const MDC &rMDC); + #endif // QT_NO_DEBUG_STREAM + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline MDC::MDC() : + mHash() + {} + + inline void MDC::put(const QString &rKey, const QString &rValue) + { localData()->insert(rKey, rValue); } + + inline void MDC::remove(const QString &rKey) + { localData()->remove(rKey); } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::MDC, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_MDC_H diff --git a/src/log4qt/log4qt/ndc.cpp b/src/log4qt/log4qt/ndc.cpp new file mode 100644 index 0000000..17ebd47 --- /dev/null +++ b/src/log4qt/log4qt/ndc.cpp @@ -0,0 +1,154 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: ndc.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * changes Feb 2009, Martin Heinrich + * - Fixed VS 2008 unreferenced formal parameter warning by using + * Q_UNUSED in operator<<. + * + * + * Copyright 2007 - 2009 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *****************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/ndc.h" + +#include +#include +#include +#include "log4qt/helpers/initialisationhelper.h" +#include "log4qt/logger.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + LOG4QT_DECLARE_STATIC_LOGGER(logger, Log4Qt:NDC) + + + + /************************************************************************** + * Class implementation: NDC + **************************************************************************/ + + + void NDC::clear() + { + if (!instance()->mStack.hasLocalData()) + return; + + instance()->mStack.localData()->clear(); + } + + + int NDC::depth() + { + if (!instance()->mStack.hasLocalData()) + return 0; + + return instance()->mStack.localData()->count(); + } + + + LOG4QT_IMPLEMENT_INSTANCE(NDC) + + + QString NDC::pop() + { + if (!instance()->mStack.hasLocalData() || instance()->mStack.localData()->isEmpty()) + { + logger()->warn("Requesting pop from empty NDC stack"); + return QString(); + } + + return instance()->mStack.localData()->pop(); + } + + + void NDC::push(const QString &rMessage) + { + if (!instance()->mStack.hasLocalData()) + instance()->mStack.setLocalData(new QStack); + + instance()->mStack.localData()->push(rMessage); + } + + + void NDC::setMaxDepth(int maxDepth) + { + if (!instance()->mStack.hasLocalData() || + instance()->mStack.localData()->size() <= maxDepth) + return; + + instance()->mStack.localData()->resize(maxDepth); + } + + + QString NDC::peek() + { + if (!instance()->mStack.hasLocalData() || + instance()->mStack.localData()->isEmpty()) + return QString(); + + return instance()->mStack.localData()->top(); + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, + const NDC &rNDC) + { + Q_UNUSED(rNDC); // To avoid warning C4100 on VS 2008 + debug.nospace() << "NDC(" + << "thread:" << QThread::currentThread()->objectName() << " " + << "peek:" << rNDC.peek() << " " + << "depth:" << rNDC.depth() + << ")"; + return debug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/ndc.h b/src/log4qt/log4qt/ndc.h new file mode 100644 index 0000000..87437cc --- /dev/null +++ b/src/log4qt/log4qt/ndc.h @@ -0,0 +1,122 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: ndc.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_NDC_H +#define LOG4QT_NDC_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#include +#include +#include "log4qt/log4qt.h" +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + /*! + * \brief The class NDC implements a nested diagnostic context. + * + * The method remove() is not required. QThreadStorage cleans up on thread + * exit. + * + * \note All the functions declared in this class are thread-safe. + */ + class LIBUKUILOG4QT_EXPORT NDC + { + private: + NDC(); + NDC(const NDC &rOther); // Not implemented + // virtual ~NDC(); // Use compiler default + NDC &operator=(const NDC &rOther); // Not implemented + + public: + static void clear(); + // JAVA: static QStack cloneStack(); + // JAVA: static QString get(); + static int depth(); + // JAVA: inherit(Stack stack) + + /*! + * Returns the NDC instance. + */ + static NDC *instance(); + + static QString pop(); + static void push(const QString &rMessage); + // JAVA: static void remove(); // Not required + static void setMaxDepth(int maxDepth); + static QString peek(); + + private: + QThreadStorage< QStack * > mStack; + }; + + + /****************************************************************************** + * Operators, Helper + ******************************************************************************/ + + #ifndef QT_NO_DEBUG_STREAM + /*! + * \relates NDC + * + * Writes all object member variables to the given debug stream \a rDebug and + * returns the stream. + * + * + * %NDC(thread:"main" peek:"i = 3" depth:4) + * + * \sa QDebug + */ + QDebug operator<<(QDebug debug, + const NDC &rNDC); + #endif // QT_NO_DEBUG_STREAM + + + /****************************************************************************** + * Inline + ******************************************************************************/ + + inline NDC::NDC() : + mStack() + {} + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::NDC, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_NDC_H diff --git a/src/log4qt/log4qt/patternlayout.cpp b/src/log4qt/log4qt/patternlayout.cpp new file mode 100644 index 0000000..a93099f --- /dev/null +++ b/src/log4qt/log4qt/patternlayout.cpp @@ -0,0 +1,147 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: patternlayout.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/patternlayout.h" + +#include +#include "log4qt/helpers/patternformatter.h" +#include "log4qt/loggingevent.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: PatternLayout + **************************************************************************/ + + + PatternLayout::PatternLayout(QObject *pParent) : + Layout(pParent), + mPattern(), + mpPatternFormatter(0) + { + setConversionPattern(DEFAULT_CONVERSION_PATTERN); + } + + + PatternLayout::PatternLayout(const QString &rPattern, + QObject *pParent) : + Layout(pParent), + mPattern(), + mpPatternFormatter(0) + { + setConversionPattern(rPattern); + } + + + PatternLayout::PatternLayout(ConversionPattern conversionPattern, + QObject *pParent) : + Layout(pParent), + mPattern(), + mpPatternFormatter(0) + { + setConversionPattern(conversionPattern); + } + + + PatternLayout::~PatternLayout() + { + delete mpPatternFormatter; + } + + + void PatternLayout::setConversionPattern(ConversionPattern conversionPattern) + { + switch (conversionPattern) + { + case DEFAULT_CONVERSION_PATTERN: + setConversionPattern(QLatin1String("%m%n")); + break; + case TTCC_CONVERSION_PATTERN: + setConversionPattern(QLatin1String("%r [%t] %p %c %x - %m%n")); + break; + default: + Q_ASSERT_X(false, "PatternLayout::setConversionFormat", "Unkown ConversionFormat"); + setConversionPattern(QString()); + } + } + + + QString PatternLayout::format(const LoggingEvent &rEvent) + { + Q_ASSERT_X(mpPatternFormatter, "PatternLayout::format()", "mpPatternConverter must not be null"); + + return mpPatternFormatter->format(rEvent); + } + + + void PatternLayout::updatePatternFormatter() + { + delete mpPatternFormatter; + mpPatternFormatter = new PatternFormatter(mPattern); + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug PatternLayout::debug(QDebug &rDebug) const + { + rDebug.nospace() << "PatternLayout(" + << "name:" << name() << " " + << "pattern:" << conversionPattern() << " " + << "referencecount:" << referenceCount() + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/patternlayout.h b/src/log4qt/log4qt/patternlayout.h new file mode 100644 index 0000000..86dca43 --- /dev/null +++ b/src/log4qt/log4qt/patternlayout.h @@ -0,0 +1,160 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: patternlayout.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_PATTERNLAYOUT_H +#define LOG4QT_PATTERNLAYOUT_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/layout.h" +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + + +namespace Log4Qt +{ + + class PatternFormatter; + + /*! + * \brief The class PatternLayout outputs a logging event based on a + * pattern string. + * + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT PatternLayout : public Layout + { + Q_OBJECT + + /*! + * The property holds the conversion pattern used by the appender. + * + * The default is "%m%n". + * + * \sa conversionPattern(), setConversionPattern() + */ + Q_PROPERTY(QString conversionPattern READ conversionPattern WRITE setConversionPattern) + + public: + /*! + * The enum ConversionPattern defines constants for pattern strings. + * + * \sa setConversionPattern(ConversionPattern); + */ + enum ConversionPattern + { + /*! The default conversion pattern string is "%m,%n". */ + DEFAULT_CONVERSION_PATTERN, + /*! + * The ttcc conversion pattern string is + * "%r [%t] %p %c %x - %m%n". + */ + TTCC_CONVERSION_PATTERN, + }; + Q_ENUMS(ConversionPattern) + + PatternLayout(QObject *pParent = 0); + PatternLayout(const QString &rPattern, + QObject *pParent = 0); + + /*! + * Creates a PatternLayout with the conversion pattern value specified + * by the \a conversionPattern constant. + */ + PatternLayout(ConversionPattern conversionPattern, + QObject *pParent = 0); + + virtual ~PatternLayout(); + private: + PatternLayout(const PatternLayout &rOther); // Not implemented + PatternLayout &operator=(const PatternLayout &rOther); // Not implemented + + public: + QString conversionPattern() const; + void setConversionPattern(const QString &rPattern); + + /*! + * Sets the conversion pattern to the value specified by the + * \a conversionPattern constant. + */ + void setConversionPattern(ConversionPattern conversionPattern); + + virtual QString format(const LoggingEvent &rEvent); + + protected: +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream + * \a rDebug and returns the stream. + * + * + * %PatternLayout(name:"PL" pattern:"%r [%t] %p %c %x - %m%n" + * "referencecount:3") + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; +#endif // QT_NO_DEBUG_STREAM + + private: + void updatePatternFormatter(); + + private: + QString mPattern; + PatternFormatter *mpPatternFormatter; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline QString PatternLayout::conversionPattern() const + { return PatternLayout::mPattern; } + + inline void PatternLayout::setConversionPattern(const QString &rPattern) + { mPattern = rPattern; + updatePatternFormatter(); } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::PatternLayout, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_PATTERNLAYOUT_H diff --git a/src/log4qt/log4qt/propertyconfigurator.cpp b/src/log4qt/log4qt/propertyconfigurator.cpp new file mode 100644 index 0000000..19b7113 --- /dev/null +++ b/src/log4qt/log4qt/propertyconfigurator.cpp @@ -0,0 +1,588 @@ +/****************************************************************************** + * + * package: Logging + * file: propertyconfigurator.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * changes Feb 2009, Martin Heinrich + * - Fixed VS 2008 unreferenced formal parameter warning by using + * Q_UNUSED in operator<<. + * + * + * Copyright 2007 - 2009 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/propertyconfigurator.h" + +#include +#include +#include "log4qt/helpers/configuratorhelper.h" +#include "log4qt/helpers/factory.h" +#include "log4qt/helpers/optionconverter.h" +#include "log4qt/helpers/properties.h" +#include "log4qt/appender.h" +#include "log4qt/layout.h" +#include "log4qt/logger.h" +#include "log4qt/logmanager.h" +#include "log4qt/loggerrepository.h" +#include "log4qt/varia/listappender.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + LOG4QT_DECLARE_STATIC_LOGGER(logger, Log4Qt::PropertyConfigurator) + + + + /************************************************************************** + * Class implementation: PropertyConfigurator + **************************************************************************/ + + + bool PropertyConfigurator::doConfigure(const Properties &rProperties, + LoggerRepository *pLoggerRepository) + { + startCaptureErrors(); + configureFromProperties(rProperties, pLoggerRepository); + return stopCaptureErrors(); + } + + + bool PropertyConfigurator::doConfigure(const QString &rConfigFileName, + LoggerRepository *pLoggerRepository) + { + startCaptureErrors(); + configureFromFile(rConfigFileName, pLoggerRepository); + return stopCaptureErrors(); + } + + + bool PropertyConfigurator::doConfigure(const QSettings &rSettings, + LoggerRepository *pLoggerRepository) + { + startCaptureErrors(); + configureFromSettings(rSettings, pLoggerRepository); + return stopCaptureErrors(); + } + + + bool PropertyConfigurator::configure(const Properties &rProperties) + { + PropertyConfigurator configurator; + return configurator.doConfigure(rProperties); + } + + + bool PropertyConfigurator::configure(const QString &rConfigFilename) + { + PropertyConfigurator configurator; + return configurator.doConfigure(rConfigFilename); + } + + + bool PropertyConfigurator::configure(const QSettings &rSettings) + { + PropertyConfigurator configurator; + return configurator.doConfigure(rSettings); + } + + + bool PropertyConfigurator::configureAndWatch(const QString &rConfigFileName) + { + // Stop an existing watch to avoid a possible concurrent configuration + ConfiguratorHelper::setConfigurationFile(); + if (rConfigFileName.isEmpty()) + return true; + + PropertyConfigurator configurator; + bool result = configurator.doConfigure(rConfigFileName); + ConfiguratorHelper::setConfigurationFile(rConfigFileName, configure); + return result; + } + + + void PropertyConfigurator::configureFromFile(const QString &rConfigFileName, + LoggerRepository *pLoggerRepository) + { + QFile file(rConfigFileName); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + { + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Unable to open property file '%1'"), + CONFIGURATOR_OPENING_FILE_ERROR, + "Log4Qt::PropertyConfigurator"); + e << rConfigFileName; + e.addCausingError(LogError(file.errorString(), file.error())); + logger()->error(e); + return; + } + Properties properties; + properties.load(&file); + if (file.error()) + { + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Unable to read property file '%1'"), + CONFIGURATOR_READING_FILE_ERROR, + "Log4Qt::PropertyConfigurator"); + e << rConfigFileName; + e.addCausingError(LogError(file.errorString(), file.error())); + logger()->error(e); + return; + } + configureFromProperties(properties, pLoggerRepository); + } + + + void PropertyConfigurator::configureFromProperties(const Properties &rProperties, + LoggerRepository *pLoggerRepository) + { + if (!pLoggerRepository) + pLoggerRepository = LogManager::loggerRepository(); + + configureGlobalSettings(rProperties, pLoggerRepository); + configureRootLogger(rProperties, pLoggerRepository); + configureNonRootElements(rProperties, pLoggerRepository); + mAppenderRegistry.clear(); + } + + + void PropertyConfigurator::configureFromSettings(const QSettings &rSettings, + LoggerRepository *pLoggerRepository) + { + Properties properties; + properties.load(rSettings); + configureFromProperties(properties, pLoggerRepository); + } + + + void PropertyConfigurator::configureGlobalSettings(const Properties &rProperties, + LoggerRepository *pLoggerRepository) const + { + Q_ASSERT_X(pLoggerRepository, "PropertyConfigurator::configureGlobalSettings()", "pLoggerRepository must not be null."); + + const QLatin1String key_reset("log4j.reset"); + const QLatin1String key_debug("log4j.Debug"); + const QLatin1String key_config_debug("log4j.configDebug"); + const QLatin1String key_threshold("log4j.threshold"); + const QLatin1String key_handle_qt_messages("log4j.handleQtMessages"); + + // Test each global setting and set it + // - Reset: log4j.reset + // - Debug: log4j.Debug, log4j.configDebug + // - Threshold: log4j.threshold + // - Handle Qt Messages: log4j.handleQtMessages + + // Reset + QString value = rProperties.property(key_reset); + if (!value.isEmpty() && OptionConverter::toBoolean(value, false)) + { + // Use LogManager and not pLoggerRepository to reset internal + // logging. + LogManager::resetConfiguration(); + logger()->debug("Reset configuration"); + } + + // Debug + value = rProperties.property(key_debug); + if (value.isNull()) + { + value = rProperties.property(key_config_debug); + if (!value.isNull()) + logger()->warn("[%1] is deprecated. Use [%2] instead.", key_config_debug, key_debug); + } + if (!value.isNull()) + { + // Don't use OptionConverter::toLevel(). Invalid level string is a valid setting + bool ok; + Level level = Level::fromString(value, &ok); + if (!ok) + level = Level::DEBUG_INT; + LogManager::logLogger()->setLevel(level); + logger()->debug("Set level for Log4Qt logging to %1", + LogManager::logLogger()->level().toString()); + } + + // Threshold + value = rProperties.property(key_threshold); + if (!value.isNull()) + { + pLoggerRepository->setThreshold(OptionConverter::toLevel(value, Level::ALL_INT)); + logger()->debug("Set threshold for LoggerRepository to %1", + pLoggerRepository->threshold().toString()); + } + + // Handle Qt messages + value = rProperties.property(key_handle_qt_messages); + if (!value.isNull()) + { + LogManager::setHandleQtMessages(OptionConverter::toBoolean(value, false)); + logger()->debug("Set handling of Qt messages LoggerRepository to %1", + QVariant(LogManager::handleQtMessages()).toString()); + } + } + + + void PropertyConfigurator::configureNonRootElements(const Properties &rProperties, + LoggerRepository *pLoggerRepository) + { + Q_ASSERT_X(pLoggerRepository, "PropertyConfigurator::configureNonRootElements()", "pLoggerRepository must not be null."); + + const QString logger_prefix = QLatin1String("log4j.logger."); + const QString category_prefix = QLatin1String("log4j.category."); + + // Iterate through all entries: + // - Test for the logger/category prefix + // - Convert JAVA class names to C++ ones + // - Parse logger data (Level, Appender) + // - Parse logger additivity + + QStringList keys = rProperties.propertyNames(); + QString key; + Q_FOREACH(key, keys) + { + QString java_name; + if (key.startsWith(logger_prefix)) + java_name = key.mid(logger_prefix.length()); + else if (key.startsWith(category_prefix)) + java_name = key.mid(category_prefix.length()); + QString cpp_name = OptionConverter::classNameJavaToCpp(java_name); + if (!java_name.isEmpty()) + { + Logger *p_logger = pLoggerRepository->logger(cpp_name); + QString value = OptionConverter::findAndSubst(rProperties, key); + parseLogger(rProperties, p_logger, key, value); + parseAdditivityForLogger(rProperties, p_logger, java_name); + } + } + } + + + void PropertyConfigurator::configureRootLogger(const Properties &rProperties, + LoggerRepository *pLoggerRepository) + { + Q_ASSERT_X(pLoggerRepository, "PropertyConfigurator::configureRootLogger()", "pLoggerRepository must not be null."); + + const QLatin1String key_root_logger("log4j.rootLogger"); + const QLatin1String key_root_category("log4j.rootCategory"); + + // - Test for the logger/category prefix + // - Parse logger data for root logger + + QString key = key_root_logger; + QString value = OptionConverter::findAndSubst(rProperties, key); + if (value.isNull()) + { + key = key_root_category; + value = OptionConverter::findAndSubst(rProperties, key); + if (!value.isNull()) + logger()->warn("[%1] is deprecated. Use [%2] instead.", key_root_category, key_root_logger); + } + + if (value.isNull()) + logger()->debug("Could not find root logger information. Is this correct?"); + else + parseLogger(rProperties, pLoggerRepository->rootLogger(), key, value); + } + + + void PropertyConfigurator::parseAdditivityForLogger(const Properties &rProperties, + Logger *pLogger, + const QString &rLog4jName) const + { + Q_ASSERT_X(pLogger, "parseAdditivityForLogger()", "pLogger must not be null."); + + const QLatin1String additivity_prefix("log4j.additivity."); + + // - Lookup additivity key for logger + // - Set additivity, if specified + + QString key = additivity_prefix + rLog4jName; + QString value = OptionConverter::findAndSubst(rProperties, key); + logger()->debug("Parsing additivity for logger: key '%1', value '%2'", key, value); + if (!value.isEmpty()) + { + bool additivity = OptionConverter::toBoolean(value, true); + logger()->debug("Setting additivity for logger '%1' to '%2'", pLogger->name(), QVariant(value).toString()); + pLogger->setAdditivity(additivity); + } + } + + + LogObjectPtr PropertyConfigurator::parseAppender(const Properties &rProperties, + const QString &rName) + { + // - Test if appender has been parsed before + // - Find appender key + // - Create appender object + // - Set layout, if required by appender + // - Set properties + // - Activate options + // - Add appender to registry + + const QLatin1String appender_prefix("log4j.appender."); + + logger()->debug("Parsing appender named '%1'", rName); + + if (mAppenderRegistry.contains(rName)) + { + logger()->debug("Appender '%1' was already parsed.", rName); + return mAppenderRegistry.value(rName); + } + + QString key = appender_prefix + rName; + QString value = OptionConverter::findAndSubst(rProperties, key); + if (value.isNull()) + { + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Missing appender definition for appender named '%1'"), + CONFIGURATOR_MISSING_APPENDER_ERROR, + "Log4Qt::PropertyConfigurator"); + e << rName; + logger()->error(e); + return 0; + } + LogObjectPtr p_appender = Factory::createAppender(value); + if (!p_appender) + { + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Unable to create appender of class '%1' namd '%2'"), + CONFIGURATOR_UNKNOWN_APPENDER_CLASS_ERROR, + "Log4Qt::PropertyConfigurator"); + e << value << rName; + logger()->error(e); + return 0; + } + p_appender->setName(rName); + + if (p_appender->requiresLayout()) + { + LogObjectPtr p_layout = parseLayout(rProperties, key); + if (p_layout) + p_appender->setLayout(p_layout); + else + return 0; + } + + QStringList exclusions; + exclusions << QLatin1String("layout"); + setProperties(rProperties, key + QLatin1String("."), exclusions, p_appender); + AppenderSkeleton *p_appenderskeleton = qobject_cast(p_appender); + if (p_appenderskeleton) + p_appenderskeleton->activateOptions(); + + mAppenderRegistry.insert(rName, p_appender); + return p_appender; + } + + + LogObjectPtr PropertyConfigurator::parseLayout(const Properties &rProperties, + const QString &rAppenderKey) + { + Q_ASSERT_X(!rAppenderKey.isEmpty(), "PropertyConfigurator::parseLayout()", "rAppenderKey must not be empty."); + + // - Find layout key + // - Create layput object + // - Set properties + // - Activate options + + const QLatin1String layout_suffix(".layout"); + + logger()->debug("Parsing layout for appender named '%1'", rAppenderKey); + + QString key = rAppenderKey + layout_suffix; + QString value = OptionConverter::findAndSubst(rProperties, key); + if (value.isNull()) + { + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Missing layout definition for appender '%1'"), + CONFIGURATOR_MISSING_LAYOUT_ERROR, + "Log4Qt::PropertyConfigurator"); + e << rAppenderKey; + logger()->error(e); + return 0; + } + LogObjectPtr p_layout = Factory::createLayout(value); + if (!p_layout) + { + LogError e = LOG4QT_ERROR(QT_TR_NOOP("Unable to create layoput of class '%1' requested by appender '%2'"), + CONFIGURATOR_UNKNOWN_LAYOUT_CLASS_ERROR, + "Log4Qt::PropertyConfigurator"); + e << value << rAppenderKey; + logger()->error(e); + return 0; + } + + QStringList exclusions; + setProperties(rProperties, key + QLatin1String("."), QStringList(), p_layout); + p_layout->activateOptions(); + + return p_layout; + } + + + void PropertyConfigurator::parseLogger(const Properties &rProperties, + Logger *pLogger, + const QString &rKey, + const QString &rValue) + { + Q_ASSERT_X(pLogger, "PropertyConfigurator::parseLogger()", "pLogger must not be null."); + Q_ASSERT_X(!rKey.isEmpty(), "PropertyConfigurator::parseLogger()", "rKey must not be empty."); + + const QLatin1String keyword_inherited("INHERITED"); + + // - Split value on comma + // - If level value, is specified + // - Test for NULL and INHERITED + // - Ensure root logger is not set to NULL + // - Set level + // - For each entry + // - Create Appender + + logger()->debug("Parsing logger: key '%1', value '%2'", rKey, rValue); + QStringList appenders = rValue.split(QLatin1Char(',')); + QStringListIterator i (appenders); + + // First entry is the level. There will be always one entry, even if the rValue is + // empty or does not contain a comma. + QString value = i.next().trimmed(); + if (!value.isEmpty()) + { + Level level; + if (value.compare(keyword_inherited,Qt::CaseInsensitive) == 0) + level = Level::NULL_INT; + else + level = OptionConverter::toLevel(value, Level::DEBUG_INT); + if (level == Level::NULL_INT && pLogger->name() == QString()) + logger()->warn("The root logger level cannot be set to NULL."); + else + { + pLogger->setLevel(level); + logger()->debug("Set level for logger '%1' to '%2'", + pLogger->name(), pLogger->level().toString()); + } + } + + pLogger->removeAllAppenders(); + while(i.hasNext()) + { + value = i.next().trimmed(); + if(value.isEmpty()) + continue; + LogObjectPtr p_appender = parseAppender(rProperties, value); + if (p_appender) + pLogger->addAppender(p_appender); + } + } + + + void PropertyConfigurator::setProperties(const Properties &rProperties, + const QString &rPrefix, + const QStringList &rExclusions, + QObject *pObject) + { + Q_ASSERT_X(!rPrefix.isEmpty(), "PropertyConfigurator::setProperties()", "rPrefix must not be empty."); + Q_ASSERT_X(pObject, "PropertyConfigurator::setProperties()", "pObject must not be null."); + + // Iterate through all entries: + // - Test for prefix to determine, if setting is for object + // - Skip empty property name + // - Skip property names in exclusion list + // - Set property on object + + logger()->debug("Setting properties for object of class '%1' from keys starting with '%2'", + QLatin1String(pObject->metaObject()->className()), + rPrefix); + + QStringList keys = rProperties.propertyNames(); + QString key; + Q_FOREACH(key, keys) + { + if (!key.startsWith(rPrefix)) + continue; + QString property = key.mid(rPrefix.length()); + if (property.isEmpty()) + continue; + QStringList split_property = property.split(QLatin1Char('.')); + if (rExclusions.contains(split_property.at(0), Qt::CaseInsensitive)) + continue; + QString value = OptionConverter::findAndSubst(rProperties, key); + Factory::setObjectProperty(pObject, property, value); + } + } + + + void PropertyConfigurator::startCaptureErrors() + { + Q_ASSERT_X(!mpConfigureErrors, "PropertyConfigurator::startCaptureErrors()", "mpConfigureErrors must be empty."); + + mpConfigureErrors = new ListAppender; + mpConfigureErrors->setName(QLatin1String("PropertyConfigurator")); + mpConfigureErrors->setConfiguratorList(true); + mpConfigureErrors->setThreshold(Level::ERROR_INT); + LogManager::logLogger()->addAppender(mpConfigureErrors); + } + + + bool PropertyConfigurator::stopCaptureErrors() + { + Q_ASSERT_X(mpConfigureErrors, "PropertyConfigurator::stopCaptureErrors()", "mpConfigureErrors must not be empty."); + + LogManager::logLogger()->removeAppender(mpConfigureErrors); + ConfiguratorHelper::setConfigureError(mpConfigureErrors->list()); + bool result = (mpConfigureErrors->list().count() == 0); + mpConfigureErrors = 0; + return result; + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DEBUG_STREAM + QDebug operator<<(QDebug debug, + const PropertyConfigurator &rPropertyConfigurator) + { + Q_UNUSED(rPropertyConfigurator); + debug.nospace() << "PropertyConfigurator(" + << ")"; + return debug.space(); + } +#endif + + + +} // namespace Logging diff --git a/src/log4qt/log4qt/propertyconfigurator.h b/src/log4qt/log4qt/propertyconfigurator.h new file mode 100644 index 0000000..eff3f55 --- /dev/null +++ b/src/log4qt/log4qt/propertyconfigurator.h @@ -0,0 +1,194 @@ +/****************************************************************************** + * + * package: Logging + * file: propertyconfigurator.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_PROPERTYCONFIGURATOR_H +#define LOG4QT_PROPERTYCONFIGURATOR_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include +#include "log4qt/helpers/logobjectptr.h" +#include "log4qt/log4qt.h" +#include "ukui-logmacros.h" + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +class QSettings; + +namespace Log4Qt +{ + + class Appender; + class Layout; + class ListAppender; + class Logger; + class Properties; + class LoggerRepository; + + /*! + * \brief The class PropertyConfigurator allows the configuration of the + * package from a JAVA properties file. + * + * \note All the functions declared in this class are thread-safe. + */ + class LIBUKUILOG4QT_EXPORT PropertyConfigurator + { + public: + PropertyConfigurator(); + // virtual ~PropertyConfigurator(); // Use compiler default + private: + PropertyConfigurator(const PropertyConfigurator &rOther); // Not implemented + PropertyConfigurator &operator=(const PropertyConfigurator &rOther); // Not implemented + + public: + /*! + * \sa ConfiguratorHelper::configureError() + */ + bool doConfigure(const Properties &rProperties, + LoggerRepository *pLoggerRepository = 0); + + /*! + * \sa ConfiguratorHelper::configureError() + */ + bool doConfigure(const QString &rConfigFileName, + LoggerRepository *pLoggerRepository = 0); + + /*! + * Reads the configuration data from the QSettings object + * \a rSettings. + * + * \sa \ref Properties::load(const QSettings &) "Properties::load()", + * ConfiguratorHelper::configureError() + */ + bool doConfigure(const QSettings &rSettings, + LoggerRepository *pLoggerRepository = 0); + + // JAVA: void doConfigure(const QUrl &rUrl, LoggerRepository *pLoggerRepository); + + /*! + * \sa ConfiguratorHelper::configureError() + */ + static bool configure(const Properties &rProperties); + + /*! + * \sa ConfiguratorHelper::configureError() + */ + static bool configure(const QString &rConfigFilename); + + /*! + * Reads the configuration data from the QSettings object + * \a rSettings. + * + * \sa \ref doConfigure(const QSettings &, LoggerRepository *) "doConfigure()", + * \ref Properties::load(const QSettings &) "Properties::load()", + * ConfiguratorHelper::configureError() + */ + static bool configure(const QSettings &rSettings); + + // JAVA: static void configure(const QUrl &rUrl); + + /*! + * \sa ConfiguratorHelper::configureError(), + * ConfiguratorHelper::configurationFile() + */ + static bool configureAndWatch(const QString &rConfigFilename); + + private: + void configureFromFile(const QString &rConfigFileName, + LoggerRepository *pLoggerRepository); + void configureFromProperties(const Properties &rProperties, + LoggerRepository *pLoggerRepository); + void configureFromSettings(const QSettings &rSettings, + LoggerRepository *pLoggerRepository); + void configureGlobalSettings(const Properties &rProperties, + LoggerRepository *pLoggerRepository) const; + void configureNonRootElements(const Properties &rProperties, + LoggerRepository *pLoggerRepository); + void configureRootLogger(const Properties &rProperties, + LoggerRepository *pLoggerRepository); + void parseAdditivityForLogger(const Properties &rProperties, + Logger *pLogger, + const QString &rLog4jName) const; + LogObjectPtr parseAppender(const Properties &rProperties, + const QString &rName); + LogObjectPtr parseLayout(const Properties &rProperties, + const QString &rAppenderName); + void parseLogger(const Properties &rProperties, + Logger *pLogger, + const QString &rKey, + const QString &rValue); + void setProperties(const Properties &rProperties, + const QString &rPrefix, + const QStringList &rExclusions, + QObject *pObject); + void startCaptureErrors(); + bool stopCaptureErrors(); + + private: + LogObjectPtr mpConfigureErrors; + QHash< QString, LogObjectPtr > mAppenderRegistry; + }; + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + +#ifndef QT_NO_DEBUG_STREAM + /*! + * \relates PropertyConfigurator + * + * Writes all object member variables to the given debug stream \a debug + * and returns the stream. + * + * + * %PropertyConfigurator() + * + * \sa QDebug + */ + QDebug operator<<(QDebug debug, + const PropertyConfigurator &rPropertyConfigurator); +#endif + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline PropertyConfigurator::PropertyConfigurator() + {} + + +} // namspace Logging + + +// Q_DECLARE_TYPEINFO(Log4Qt::PropertyConfigurator, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_PROPERTYCONFIGURATOR_H diff --git a/src/log4qt/log4qt/rollingfileappender.cpp b/src/log4qt/log4qt/rollingfileappender.cpp new file mode 100644 index 0000000..53d527e --- /dev/null +++ b/src/log4qt/log4qt/rollingfileappender.cpp @@ -0,0 +1,202 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: rollingfileappender.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/rollingfileappender.h" + +#include +#include +#include +#include "log4qt/helpers/optionconverter.h" +#include "log4qt/layout.h" +#include "log4qt/loggingevent.h" + + + +namespace Log4Qt +{ + + + /************************************************************************ + Declarations + *************************************************************************/ + + + + /************************************************************************ + C helper functions + *************************************************************************/ + + + + /************************************************************************ + Class implementation: RollingFileAppender + *************************************************************************/ + + + RollingFileAppender::RollingFileAppender(QObject *pParent) : + FileAppender(pParent), + mMaxBackupIndex(1), + mMaximumFileSize(10*1024*1024) + { + } + + + RollingFileAppender::RollingFileAppender(Layout *pLayout, + const QString &rFileName, + QObject *pParent) : + FileAppender(pLayout, rFileName, pParent), + mMaxBackupIndex(1), + mMaximumFileSize(10*1024*1024) + { + } + + + RollingFileAppender::RollingFileAppender(Layout *pLayout, + const QString &rFileName, + bool append, + QObject *pParent) : + FileAppender(pLayout, rFileName, append, pParent), + mMaxBackupIndex(1), + mMaximumFileSize(10*1024*1024) + { + } + + + RollingFileAppender::~RollingFileAppender() + { + close(); + } + + + void RollingFileAppender::setMaxFileSize(const QString &rMaxFileSize) + { + bool ok; + qint64 max_file_size = OptionConverter::toFileSize(rMaxFileSize, &ok); + if (ok) + setMaximumFileSize(max_file_size); + } + + + void RollingFileAppender::append(const LoggingEvent &rEvent) + { + // Q_ASSERT_X(, "RollingFileAppender::append()", "Lock must be held by caller") + + FileAppender::append(rEvent); + #ifndef UKUILOG4QT_EXTRA_ENABLE + if (writer()->device()->size() > this->mMaximumFileSize) + rollOver(); + #endif + } + + void RollingFileAppender::asyncAppend(const LoggingEvent &rEvent) + { + // Q_ASSERT_X(, "RollingFileAppender::asyncAppend()", "Lock must be held by caller") + + FileAppender::asyncAppend(rEvent); + if (writer()->device()->size() > this->mMaximumFileSize) + rollOver(); + } + + + void RollingFileAppender::rollOver() + { + // Q_ASSERT_X(, "RollingFileAppender::rollOver()", "Lock must be held by caller") + + logger()->debug("Rolling over with maxBackupIndex = %1", mMaxBackupIndex); + + closeFile(); + + QFile f; + f.setFileName(file() + QLatin1Char('.') + QString::number(mMaxBackupIndex)); + if (f.exists() && !removeFile(f)) + return; + + QString target_file_name; + int i; + for (i = mMaxBackupIndex - 1; i >=1; i--) + { + f.setFileName(file() + QLatin1Char('.') + QString::number(i)); + if (f.exists()) + { + target_file_name = file() + QLatin1Char('.') + QString::number(i + 1); + if (!renameFile(f, target_file_name)) + return; + } + } + + f.setFileName(file()); + target_file_name = file() + QLatin1String(".1"); + if (!renameFile(f, target_file_name)) + return; + + openFile(); + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug RollingFileAppender::debug(QDebug &rDebug) const + { + QString layout_name; + if (layout()) + layout_name = layout()->name(); + QString codec_name; + if (encoding()) + codec_name = QLatin1String(encoding()->name()); + + rDebug.nospace() << "RollingFileAppender(" + << "name:" << name() << " " + << "appendfile:" << appendFile() << " " + << "bufferedio:" << bufferedIo() << " " + << "encoding:" << codec_name << " " + << "file:" << file() << " " + << "filter:" << firstFilter() << " " + << "immediateflush:" << immediateFlush() << " " + << "isactive:" << isActive() << " " + << "isclosed:" << isClosed() << " " + << "layout:" << layout_name << " " + << "maxbackupindex:" << maxBackupIndex() << " " + << "maximumfilesize:" << maximumFileSize() << " " + << "referencecount:" << referenceCount() << " " + << "threshold:" << threshold().toString() << " " + << "writer:" << writer() + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/rollingfileappender.h b/src/log4qt/log4qt/rollingfileappender.h new file mode 100644 index 0000000..5dafa22 --- /dev/null +++ b/src/log4qt/log4qt/rollingfileappender.h @@ -0,0 +1,165 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: rollingfileappender.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_ROLINGFILEAPPENDER_H +#define LOG4QT_ROLINGFILEAPPENDER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/fileappender.h" +#include "ukui-logmacros.h" + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + /*! + * \brief The class RollingFileAppender extends FileAppender to backup + * the log files when they reach a certain size. + * + * \note All the functions declared in this class are thread-safe. + * + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT RollingFileAppender : public FileAppender + { + Q_OBJECT + + /*! + * The property holds the maximum backup count used by the appender. + * + * The default is 1. + * + * \sa maxBackupIndex(), setMaxBackupIndex() + */ + Q_PROPERTY(int maxBackupIndex READ maxBackupIndex WRITE setMaxBackupIndex) + + /*! + * The property holds the maximum file size used by the appender. + * + * The default is 10 MB (10 * 1024 * 1024). + * + * \sa maximumFileSize(), setMaximumFileSize() + */ + Q_PROPERTY(qint64 maximumFileSize READ maximumFileSize WRITE setMaximumFileSize) + + /*! + * The property sets the maximum file size from a string value. + * + * \sa setMaxFileSize(), maximumFileSize() + */ + Q_PROPERTY(QString maxFileSize WRITE setMaxFileSize) + + public: + RollingFileAppender(QObject *pParent = 0); + RollingFileAppender(Layout *pLayout, + const QString &rFileName, + QObject *pParent = 0); + RollingFileAppender(Layout *pLayout, + const QString &rFileName, + bool append, + QObject *pParent = 0); + virtual ~RollingFileAppender(); + private: + RollingFileAppender(const RollingFileAppender &rOther); // Not implemented + RollingFileAppender &operator=(const RollingFileAppender &rOther); // Not implemented + + public: + int maxBackupIndex() const; + qint64 maximumFileSize() const; + void setMaxBackupIndex(int maxBackupIndex); + void setMaximumFileSize(qint64 maximumFileSize); + void setMaxFileSize(const QString &rMaxFileSize); + + protected: + virtual void append(const LoggingEvent &rEvent); + virtual void asyncAppend(const LoggingEvent &rEvent); + +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream + * \a rDebug and returns the stream. + * + * + * %RollingFileAppender(name:"RFA" appendfile:false bufferedio:true + * encoding:"" file:"/log.txt" filter: 0x0 + * immediateflush:true isactive:true + * isclosed:false layout:"TTCC" maxbackupindex:2 + * maximumfilesize:40 referencecount:1 + * threshold:"NULL" writer:0x4175af8) + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; +#endif // QT_NO_DEBUG_STREAM + + private: + void rollOver(); + + private: + int mMaxBackupIndex; + qint64 mMaximumFileSize; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline int RollingFileAppender::maxBackupIndex() const + { QMutexLocker locker(&mObjectGuard); + return mMaxBackupIndex; } + + inline qint64 RollingFileAppender::maximumFileSize() const + { QMutexLocker locker(&mObjectGuard); + return mMaximumFileSize; } + + inline void RollingFileAppender::setMaxBackupIndex(int maxBackupIndex) + { QMutexLocker locker(&mObjectGuard); + mMaxBackupIndex = maxBackupIndex; } + + inline void RollingFileAppender::setMaximumFileSize(qint64 maximumFileSize) + { QMutexLocker locker(&mObjectGuard); + mMaximumFileSize = maximumFileSize; } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::RollingFileAppender, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_ROLINGFILEAPPENDER_H diff --git a/src/log4qt/log4qt/simplelayout.cpp b/src/log4qt/log4qt/simplelayout.cpp new file mode 100644 index 0000000..a7d5234 --- /dev/null +++ b/src/log4qt/log4qt/simplelayout.cpp @@ -0,0 +1,84 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: simplelayout.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/simplelayout.h" + +#include +#include "log4qt/loggingevent.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: SimpleLayout + **************************************************************************/ + + + QString SimpleLayout::format(const LoggingEvent &rEvent) + { + return rEvent.level().toString() + QLatin1String(" - ") + rEvent.message() + Layout::endOfLine(); + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug SimpleLayout::debug(QDebug &rDebug) const + { + rDebug.nospace() << "SimpleLayout(" + << "name:" << name() << " " + << "referencecount:" << referenceCount() + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/simplelayout.h b/src/log4qt/log4qt/simplelayout.h new file mode 100644 index 0000000..233d188 --- /dev/null +++ b/src/log4qt/log4qt/simplelayout.h @@ -0,0 +1,102 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: simplelayout.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_SIMPLELAYOUT_H +#define LOG4QT_SIMPLELAYOUT_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/layout.h" +#include "ukui-logmacros.h" + +/****************************************************************************** + * Declarations + ******************************************************************************/ + + +namespace Log4Qt +{ + + /*! + * \brief The class SimpleLayout outputs the level and message of a logging + * event. + * + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT SimpleLayout : public Layout + { + Q_OBJECT + + public: + SimpleLayout(QObject *pParent = 0); + // virtual ~SimpleLayout(); // Use compiler default + private: + SimpleLayout(const SimpleLayout &rOther); // Not implemented + SimpleLayout &operator=(const SimpleLayout &rOther); // Not implemented + + public: + virtual QString format(const LoggingEvent &rEvent); + + protected: + +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream + * \a rDebug and returns the stream. + * + * + * %SimpleLayout(name:"SL" referencecount:1) + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; +#endif // QT_NO_DEBUG_STREAM + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline SimpleLayout::SimpleLayout(QObject *pParent) : + Layout(pParent) + {} + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::SimpleLayout, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_SIMPLELAYOUT_H diff --git a/src/log4qt/log4qt/spi/filter.cpp b/src/log4qt/log4qt/spi/filter.cpp new file mode 100644 index 0000000..8f2d10e --- /dev/null +++ b/src/log4qt/log4qt/spi/filter.cpp @@ -0,0 +1,70 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: filter.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/spi/filter.h" + +#include + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: Filter + **************************************************************************/ + + + void Filter::setNext(Filter *pFilter) + { + mpNext = pFilter; + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/spi/filter.h b/src/log4qt/log4qt/spi/filter.h new file mode 100644 index 0000000..7b7e693 --- /dev/null +++ b/src/log4qt/log4qt/spi/filter.h @@ -0,0 +1,125 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: filter.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_FILTER_H +#define LOG4QT_FILTER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/helpers/logobject.h" + +#include "log4qt/helpers/logobjectptr.h" +#include "log4qt/log4qt.h" +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + class LoggingEvent; + + /*! + * \brief The class Filter is the base class for all filters. + * + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT Filter : public LogObject + { + Q_OBJECT + + /*! + * The property holds the next filter of this filter. + * + * The default is 0 for no next filter. + * + * \sa next(), setNext() + */ + Q_PROPERTY(Filter* next READ next WRITE setNext) + + public: + enum Decision + { + ACCEPT, + DENY, + NEUTRAL + }; + Q_ENUMS(Decision); + + public: + Filter(QObject *pObject = 0); + // Filter(const Filter &rOther); // Use compiler default + virtual ~Filter(); + // Filter &operator=(const Filter &rOther); // Use compiler default + + Filter* next() const; + void setNext(Filter *pFilter); + + virtual void activateOptions(); + virtual Decision decide(const LoggingEvent &rEvent) const = 0; + + private: + LogObjectPtr mpNext; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline Filter::Filter(QObject *pObject) : + LogObject(pObject), + mpNext(0) + {} + + inline Filter::~Filter() + {} + + inline Filter* Filter::next() const + { return mpNext; } + + inline void Filter::activateOptions() + {} + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::Filter, Q_COMPLEX_TYPE); // Use default +Q_DECLARE_TYPEINFO(Log4Qt::LogObjectPtr, Q_MOVABLE_TYPE); + + +#endif // LOG4QT_FILTER_H diff --git a/src/log4qt/log4qt/ttcclayout.cpp b/src/log4qt/log4qt/ttcclayout.cpp new file mode 100644 index 0000000..023ba11 --- /dev/null +++ b/src/log4qt/log4qt/ttcclayout.cpp @@ -0,0 +1,182 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: ttcclayout.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/ttcclayout.h" + +#include +#include +#include "log4qt/helpers/datetime.h" +#include "log4qt/helpers/patternformatter.h" +#include "log4qt/logger.h" +#include "log4qt/loggingevent.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: TTCCLayout + **************************************************************************/ + + + TTCCLayout::TTCCLayout(QObject *pParent) : + Layout(pParent), + mCategoryPrefixing(true), + mContextPrinting(true), + mDateFormat(), + mThreadPrinting(true), + mpPatternFormatter(0) + { + setDateFormat(TIME_RELATIVE); + } + + + TTCCLayout::TTCCLayout(const QString &rDateFormat, + QObject *pParent) : + Layout(pParent), + mCategoryPrefixing(true), + mContextPrinting(true), + mDateFormat(rDateFormat), + mThreadPrinting(true), + mpPatternFormatter(0) + { + } + + + TTCCLayout::TTCCLayout(DateFormat dateFormat, + QObject *pParent) : + Layout(pParent), + mCategoryPrefixing(true), + mContextPrinting(true), + mDateFormat(), + mThreadPrinting(true), + mpPatternFormatter(0) + { + setDateFormat(dateFormat); + } + + + TTCCLayout::~TTCCLayout() + { + delete mpPatternFormatter; + } + + + void TTCCLayout::setDateFormat(DateFormat dateFormat) + { + switch (dateFormat) + { + case NONE: + setDateFormat(QLatin1String("NONE")); + break; + case ISO8601: + setDateFormat(QLatin1String("ISO8601")); + break; + case TIME_ABSOLUTE: + setDateFormat(QLatin1String("TIME_ABSOLUTE")); + break; + case DATE: + setDateFormat(QLatin1String("DATE")); + break; + case TIME_RELATIVE: + setDateFormat(QLatin1String("TIME_RELATIVE")); + break; + default: + Q_ASSERT_X(false, "TTCCLayout::setDateFormat", "Unkown DateFormat"); + setDateFormat(QString()); + } + } + + + QString TTCCLayout::format(const LoggingEvent &rEvent) + { + Q_ASSERT_X(mpPatternFormatter, "TTCCLayout::format()", "mpPatternConverter must not be null"); + + return mpPatternFormatter->format(rEvent); + } + + + void TTCCLayout::updatePatternFormatter() + { + QString pattern; + + pattern += QLatin1String("%d{") + mDateFormat + QLatin1String("}"); + if (mThreadPrinting) + pattern += QLatin1String(" [%t]"); + pattern += QLatin1String(" %-5p"); + if (mCategoryPrefixing) + pattern += QLatin1String(" %c"); + if (mContextPrinting) + pattern += QLatin1String(" %x"); + pattern += QLatin1String(" - %m%n"); + + delete mpPatternFormatter; + mpPatternFormatter = new PatternFormatter(pattern); + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug TTCCLayout::debug(QDebug &rDebug) const + { + rDebug.nospace() << "TTCCLayout(" + << "name:" << name() << " " + << "categoryprefixing:" << categoryPrefixing() << " " + << "contextprinting:" << contextPrinting() << " " + << "dateformat:" << dateFormat() << " " + << "referencecount:" << referenceCount() << " " + << "threadprinting:" << threadPrinting() + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/ttcclayout.h b/src/log4qt/log4qt/ttcclayout.h new file mode 100644 index 0000000..247cb9c --- /dev/null +++ b/src/log4qt/log4qt/ttcclayout.h @@ -0,0 +1,235 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: ttcclayout.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_TTCCLAYOUT_H +#define LOG4QT_TTCCLAYOUT_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/layout.h" +#include "ukui-logmacros.h" + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + class LoggingEvent; + class PatternFormatter; + + /*! + * \brief The class TTCCLayout outputs the time, thread, logger and nested + * diagnostic context information of a logging event. + * + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT TTCCLayout : public Layout + { + Q_OBJECT + + /*! + * The property holds if the logger name is part of the formatted output. + * + * The default value is true for including the logger name. + * + * \sa categoryPrefixing(), setCategoryPrefixing() + */ + Q_PROPERTY(bool categoryPrefixing READ categoryPrefixing WRITE setCategoryPrefixing) + + /*! + * The property holds if the nested context information is part of the + * formatted output. + * + * The default value it true for including the nested context information. + * + * \sa contextPrinting(), setContextPrinting() + */ + Q_PROPERTY(bool contextPrinting READ contextPrinting WRITE setContextPrinting) + + /*! + * The property holds the date format used by the layout. + * + * The default date format is "TIME_RELATIVE". + * + * \sa dateFormat(), setDateFormat() + */ + Q_PROPERTY(QString dateFormat READ dateFormat WRITE setDateFormat) + + /*! + * The property holds if the thread name is part of the formatted output. + * + * The default value it true for including the thread name. + * + * \sa threadPrinting(), setThreadPrinting() + */ + Q_PROPERTY(bool threadPrinting READ threadPrinting WRITE setThreadPrinting) + + public: + /*! + * The enum DateFormat defines constants for date formats. + * + * \sa setDateFormat(DateFormat), DateTime::toString() + */ + enum DateFormat + { + /*! The none date format string is "NONE". */ + NONE, + /*! + * The iso8601 date format string is "ISO8601". The date will be + * formatted as yyyy-MM-dd hh:mm:ss.zzz. + */ + ISO8601, + /*! + * The absolute date format string is "TIME_ABSOLUTE". The date will be + * formatted as HH:mm:ss.zzz. + */ + TIME_ABSOLUTE, + /*! + * The date date format string is "DATE". The date will be formatted + * as MMM YYYY HH:mm:ss.zzzz. + */ + DATE, + /*! + * The relative date format string is "TIME_RELATIVE". The date will be + * formatted as milliseconds since start of the program. + */ + TIME_RELATIVE + }; + Q_ENUMS(DateFormat) + + TTCCLayout(QObject *pParent = 0); + TTCCLayout(const QString &rDateFormat, + QObject *pParent = 0); + + /*! + * Creates a TTCCLayout with the date formar value specified by + * the \a dateFormat constant and the parent \a pParent. + */ + TTCCLayout(DateFormat dateFormat, + QObject *pParent = 0); + + virtual ~TTCCLayout(); + private: + TTCCLayout(const TTCCLayout &rOther); // Not implemented + TTCCLayout &operator=(const TTCCLayout &rOther); // Not implemented + + public: + bool categoryPrefixing() const; + bool contextPrinting() const; + QString dateFormat() const; + // JAVA: bool ignoresThrowable() const; + bool threadPrinting() const; + void setCategoryPrefixing(bool categoryPrefixing); + void setContextPrinting(bool contextPrinting); + void setDateFormat(const QString &rDateFormat); + + /*! + * Sets the date format to the value specified by the \a dateFormat + * constant. + */ + void setDateFormat(DateFormat dateFormat); + + // JAVA: setIgnoresThrowable(bool ignoresThrowable); + void setThreadPrinting(bool threadPrinting); + virtual QString format(const LoggingEvent &rEvent); + + protected: +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream + * \a rDebug and returns the stream. + * + * + * %TTCCLayout(name:"TTCC" categoryprefixing:true + * contextprinting:true dateformat:"ISO8601" + * referencecount:1 threadprinting:true) + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; +#endif // QT_NO_DEBUG_STREAM + + private: + void updatePatternFormatter(); + + private: + bool mCategoryPrefixing; + bool mContextPrinting; + QString mDateFormat; + bool mThreadPrinting; + PatternFormatter *mpPatternFormatter; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline bool TTCCLayout::categoryPrefixing() const + { return mCategoryPrefixing; } + + inline bool TTCCLayout::contextPrinting() const + { return mContextPrinting; } + + inline QString TTCCLayout::dateFormat() const + { return mDateFormat; } + + inline bool TTCCLayout::threadPrinting() const + { return mThreadPrinting; } + + inline void TTCCLayout::setCategoryPrefixing(bool categoryPrefixing) + { mCategoryPrefixing = categoryPrefixing; + updatePatternFormatter(); } + + inline void TTCCLayout::setContextPrinting(bool contextPrinting) + { mContextPrinting = contextPrinting; + updatePatternFormatter(); } + + inline void TTCCLayout::setDateFormat(const QString &rDateFormat) + { mDateFormat = rDateFormat; + updatePatternFormatter(); } + + inline void TTCCLayout::setThreadPrinting(bool threadPrinting) + { mThreadPrinting = threadPrinting; + updatePatternFormatter(); } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::TTCCLayout, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_TTCCLAYOUT_H diff --git a/src/log4qt/log4qt/varia/debugappender.cpp b/src/log4qt/log4qt/varia/debugappender.cpp new file mode 100644 index 0000000..c30dac6 --- /dev/null +++ b/src/log4qt/log4qt/varia/debugappender.cpp @@ -0,0 +1,149 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: debugappender.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/varia/debugappender.h" + +#include +#include +#include "log4qt/layout.h" +#include "log4qt/loggingevent.h" +#if defined(Q_WS_WIN) || defined(Q_OS_WIN32) + #include +#endif + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: DebugAppender + **************************************************************************/ + + + DebugAppender::DebugAppender(Layout *pLayout, + QObject *pParent) : + AppenderSkeleton(pParent) + { + setLayout(pLayout); + } + + + bool DebugAppender::requiresLayout() const + { + return true; + } + + + void DebugAppender::append(const LoggingEvent &rEvent) + { + // Q_ASSERT_X(, "DebugAppender::append()", "Lock must be held by caller"); + Q_ASSERT_X(layout(), "DebugAppender::append()", "Layout must not be null"); + + QString message(layout()->format(rEvent)); +#if defined(Q_OS_WIN32) || defined(Q_WS_WIN) + #if (QT_VERSION < 0x050000) + QT_WA({ + OutputDebugStringW(reinterpret_cast(message.utf16())); + }, { + OutputDebugStringA(message.toLocal8Bit().data()); + }); + #else + OutputDebugStringW(reinterpret_cast(message.utf16())); + #endif +#else + fprintf(stderr, "%s", message.toLocal8Bit().data()); + fflush(stderr); +#endif + } + + void DebugAppender::asyncAppend(const LoggingEvent &rEvent) + { + // Q_ASSERT_X(, "DebugAppender::asyncAppend()", "Lock must be held by caller"); + Q_ASSERT_X(layout(), "DebugAppender::asyncAppend()", "Layout must not be null"); + + QString message(layout()->format(rEvent)); +#if defined(Q_OS_WIN32) || defined(Q_WS_WIN) + #if (QT_VERSION < 0x050000) + QT_WA({ + OutputDebugStringW(reinterpret_cast(message.utf16())); + }, { + OutputDebugStringA(message.toLocal8Bit().data()); + }); + #else + OutputDebugStringW(reinterpret_cast(message.utf16())); + #endif +#else + fprintf(stderr, "%s", message.toLocal8Bit().data()); + fflush(stderr); +#endif + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +#ifndef QT_NO_DEBUG_STREAM + QDebug DebugAppender::debug(QDebug &rDebug) const + { + QString layout_name; + if (layout()) + layout_name = layout()->name(); + + rDebug.nospace() << "DebugAppender(" + << "name:" << name() << " " + << "filter:" << firstFilter() << " " + << "isactive:" << isActive() << " " + << "isclosed:" << isClosed() << " " + << "layout:" << layout_name << " " + << "referencecount:" << referenceCount() << " " + << "threshold:" << threshold().toString() + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + +} // namspace Log4Qt diff --git a/src/log4qt/log4qt/varia/debugappender.h b/src/log4qt/log4qt/varia/debugappender.h new file mode 100644 index 0000000..e9479e9 --- /dev/null +++ b/src/log4qt/log4qt/varia/debugappender.h @@ -0,0 +1,135 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: debugappender.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_DEBUGAPPENDER_H +#define LOG4QT_DEBUGAPPENDER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/appenderskeleton.h" +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + /*! + * \brief The class DebugAppender appends logging events to the platform + * specific debug output. + * + * A DebugAppender appends to the Debugger on Windows and to stderr on all + * other systems. + * + * \note All the functions declared in this class are thread-safe. + * + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT DebugAppender : public AppenderSkeleton + { + Q_OBJECT + + public: + /*! + * Creates a DebugAppender. + */ + DebugAppender(QObject *pParent = 0); + + /*! + * Creates a DebugAppender with the specified layout \a pLayout + */ + DebugAppender(Layout *pLayout, + QObject *pParent = 0); + + // virtual ~DebugAppender(); // Use compiler default + private: + DebugAppender(const DebugAppender &rOther); // Not implemented + DebugAppender &operator=(const DebugAppender &rOther); // Not implemented + + public: + /*! + * The DebugAppended requires a layout. The function returns true. + * + * \sa setLayout() + */ + virtual bool requiresLayout() const; + + protected: + /*! + * Appends the specified logging event \a rEvent to the debug output. + * The output is formatted using the appender's layout. + * + * The method is called by the AppenderSkeleton::doAppend() after it + * the entry conditions have been tested and it has been found that the + * logging event needs to be appended. + * + * \sa setLayout(), AppenderSkeleton::doAppend(), checkEntryConditions() + */ + virtual void append(const LoggingEvent &rEvent); + virtual void asyncAppend(const LoggingEvent &rEvent); + +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream \a rDebug + * and returns the stream. + * + * + * %DebugAppender(name:"DA" filter:0x3bee6b8 isactive:true isclosed:false + * layout:"SL" referencecount:1 threshold:"NULL") + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; +#endif // QT_NO_DEBUG_STREAM + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline DebugAppender::DebugAppender(QObject *pParent) : + AppenderSkeleton(pParent) + {} + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::DebugAppender, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_DEBUGAPPENDER_H diff --git a/src/log4qt/log4qt/varia/denyallfilter.cpp b/src/log4qt/log4qt/varia/denyallfilter.cpp new file mode 100644 index 0000000..31d8f64 --- /dev/null +++ b/src/log4qt/log4qt/varia/denyallfilter.cpp @@ -0,0 +1,77 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: denyallfilter.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/varia/denyallfilter.h" + +#include + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: Filter + **************************************************************************/ + + +#ifndef QT_NO_DEBUG_STREAM + QDebug DenyAllFilter::debug(QDebug &rDebug) const + { + rDebug.nospace() << "DenyAllFilter(" + << "next:" << next() + << "referencecount:" << referenceCount() << " " + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/varia/denyallfilter.h b/src/log4qt/log4qt/varia/denyallfilter.h new file mode 100644 index 0000000..dea0312 --- /dev/null +++ b/src/log4qt/log4qt/varia/denyallfilter.h @@ -0,0 +1,105 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: denyallfilter.h + * created: September 2007 + * author: Martin Heinrich + * + * + * changes Feb 2009, Martin Heinrich + * - Fixed a compile error on VS 2008 by using Q_UNUSED(&rEvent) + * instead of Q_UNUSED(rEvent) + * + * + * Copyright 2007 - 2009 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_DENYALLFILTER_H +#define LOG4QT_DENYALLFILTER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/spi/filter.h" +#include "ukui-logmacros.h" + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + /*! + * \brief The class DenyAllFilter drops all logging events + * + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT DenyAllFilter : public Filter + { + Q_OBJECT + + public: + DenyAllFilter(QObject *pParent = 0); + // DenyAllFilter(const DenyAllFilter &rOther); // Use compiler default + // virtual ~DenyAllFilter(); // Use compiler default + // DenyAllFilter &operator=(const DenyAllFilter &rOther); // Use compiler default + + virtual Decision decide(const LoggingEvent &rEvent) const; + + protected: +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream \a rDebug + * and returns the stream. + * + * + * %DenyAllFilter(next:QObject(0x0) referencecount:1 ) + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; +#endif // QT_NO_DEBUG_STREAM + }; + + + /************************************************************************* + * Operators, Helper + *************************************************************************/ + + + /************************************************************************* + * Inline + *************************************************************************/ + + inline DenyAllFilter::DenyAllFilter(QObject *pParent) : + Filter(pParent) + {} + + inline Filter::Decision DenyAllFilter::decide(const LoggingEvent &rEvent) const + { Q_UNUSED(&rEvent); return Filter::DENY; } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::DenyAllFilter, Q_MOVABLE_TYPE); // Use default + + +#endif // LOG4QT_DENYALLFILTER_H diff --git a/src/log4qt/log4qt/varia/levelmatchfilter.cpp b/src/log4qt/log4qt/varia/levelmatchfilter.cpp new file mode 100644 index 0000000..32a3d84 --- /dev/null +++ b/src/log4qt/log4qt/varia/levelmatchfilter.cpp @@ -0,0 +1,100 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: levelmatchfilter.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/varia/levelmatchfilter.h" + +#include +#include "log4qt/loggingevent.h" + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: Filter + **************************************************************************/ + + + LevelMatchFilter::LevelMatchFilter(QObject *pParent) : + Filter(pParent), + mAcceptOnMatch(true), + mLevelToMatch(Level::NULL_INT) + {} + + + Filter::Decision LevelMatchFilter::decide(const LoggingEvent &rEvent) const + { + if (mLevelToMatch == Level::NULL_INT || + rEvent.level() != mLevelToMatch) + return Filter::NEUTRAL; + + if (mAcceptOnMatch) + return Filter::ACCEPT; + else + return Filter::DENY; + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug LevelMatchFilter::debug(QDebug &rDebug) const + { + rDebug.nospace() << "LevelMatchFilter(" + << "acceptonmatch:" << mAcceptOnMatch << " " + << "leveltomatch:" << mLevelToMatch.toString() << " " + << "next:" << next() + << "referencecount:" << referenceCount() << " " + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/varia/levelmatchfilter.h b/src/log4qt/log4qt/varia/levelmatchfilter.h new file mode 100644 index 0000000..fa22549 --- /dev/null +++ b/src/log4qt/log4qt/varia/levelmatchfilter.h @@ -0,0 +1,137 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: levelmatchfilter.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_LEVELMATCHFILTER_H +#define LOG4QT_LEVELMATCHFILTER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/spi/filter.h" +#include "ukui-logmacros.h" +#include "log4qt/level.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + /*! + * \brief The class LevelMatchFilter allows logging events with a specified + * level. + * + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT LevelMatchFilter : public Filter + { + Q_OBJECT + + /*! + * The property holds if an event is accpeted on a match. + * + * The default is true. + * + * \sa acceptOnMatch(), setAcceptOnMatch() + */ + Q_PROPERTY(bool acceptOnMatch READ acceptOnMatch WRITE setAcceptOnMatch) + + /*! + * The property holds the level to match for this filter. + * + * The default is Level::NULL_INT. + * + * \sa levelToMatch(), setLevelToMatch() + */ + Q_PROPERTY(Level levelToMatch READ levelToMatch WRITE setLevelToMatch) + + public: + LevelMatchFilter(QObject *pParent = 0); + // LevelMatchFilter(const LevelMatchFilter &rOther); // Use compiler default + // virtual ~LevelMatchFilter(); // Use compiler default + // LevelMatchFilter &operator=(const LevelMatchFilter &rOther); // Use compiler default + + bool acceptOnMatch() const; + Level levelToMatch() const; + void setAcceptOnMatch(bool accept); + void setLevelToMatch(Level level); + + virtual Decision decide(const LoggingEvent &rEvent) const; + + protected: +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream \a rDebug + * and returns the stream. + * + * + * %LevelMatchFilter(acceptonmatch:true leveltomatch:"WARN" + * next:Log4Qt::DenyAllFilter(0x3bce3a8) + * referencecount:1 ) + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; +#endif // QT_NO_DEBUG_STREAM + + private: + bool mAcceptOnMatch; + Level mLevelToMatch; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline bool LevelMatchFilter::acceptOnMatch() const + { return mAcceptOnMatch; } + + inline Level LevelMatchFilter::levelToMatch() const + { return mLevelToMatch; } + + inline void LevelMatchFilter::setAcceptOnMatch(bool accept) + { mAcceptOnMatch = accept; } + + inline void LevelMatchFilter::setLevelToMatch(Level level) + { mLevelToMatch = level; } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::LevelMatchFilter, Q_MOVABLE_TYPE); // Use default + + +#endif // LOG4QT_LEVELMATCHFILTER_H diff --git a/src/log4qt/log4qt/varia/levelrangefilter.cpp b/src/log4qt/log4qt/varia/levelrangefilter.cpp new file mode 100644 index 0000000..b219cd9 --- /dev/null +++ b/src/log4qt/log4qt/varia/levelrangefilter.cpp @@ -0,0 +1,104 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: levelrangefilter.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/varia/levelrangefilter.h" + +#include +#include "log4qt/loggingevent.h" + + +namespace Log4Qt +{ + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + + + +/****************************************************************************** + * C helper functions + ******************************************************************************/ + + + +/****************************************************************************** + * Class implementation: Filter + ******************************************************************************/ + + +LevelRangeFilter::LevelRangeFilter(QObject *pParent) : + Filter(pParent), + mAcceptOnMatch(true), + mLevelMin(Level::NULL_INT), + mLevelMax(Level::OFF_INT) +{} + + +Filter::Decision LevelRangeFilter::decide(const LoggingEvent &rEvent) const +{ + if (rEvent.level() < mLevelMin) + return Filter::DENY; + + if (rEvent.level() > mLevelMax) + return Filter::DENY; + + if (mAcceptOnMatch) + return Filter::ACCEPT; + else + return Filter::NEUTRAL; +} + + +#ifndef QT_NO_DEBUG_STREAM +QDebug LevelRangeFilter::debug(QDebug &rDebug) const +{ + rDebug.nospace() << "LevelRangeFilter(" + << "acceptonmatch:" << mAcceptOnMatch << " " + << "levelmin:" << mLevelMin.toString() << " " + << "levelmax:" << mLevelMax.toString() << " " + << "next:" << next() + << "referencecount:" << referenceCount() << " " + << ")"; + return rDebug.space(); +} +#endif // QT_NO_DEBUG_STREAM + + + +/****************************************************************************** + * Implementation: Operators, Helper + ******************************************************************************/ + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/varia/levelrangefilter.h b/src/log4qt/log4qt/varia/levelrangefilter.h new file mode 100644 index 0000000..90e8dd9 --- /dev/null +++ b/src/log4qt/log4qt/varia/levelrangefilter.h @@ -0,0 +1,153 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: levelrangefilter.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_LEVELRANGEFILTER_H +#define LOG4QT_LEVELRANGEFILTER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/spi/filter.h" +#include "ukui-logmacros.h" +#include "log4qt/level.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + /*! + * \brief The class LevelMatchFilter allows logging events with levels in a + * specified range. + * + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT LevelRangeFilter : public Filter + { + Q_OBJECT + + /*! + * The property holds if an event is accpeted on a match. + * + * The default is true. + * + * \sa acceptOnMatch(), acceptOnMatch() + */ + Q_PROPERTY(bool acceptOnMatch READ acceptOnMatch WRITE setAcceptOnMatch) + + /*! + * The property holds the maximum level of the range for this filter. + * + * The default is Level::OFF_INT. + * + * \sa levelMax(), setLevelMax() + */ + Q_PROPERTY(Level levelMax READ levelMax WRITE setLevelMax) + + /*! + * The property holds the minimum level of the range for this filter. + * + * The default is Level::NULL_INT. + * + * \sa levelMin(), setLevelMin() + */ + Q_PROPERTY(Level levelMin READ levelMin WRITE setLevelMin) + + public: + LevelRangeFilter(QObject *pParent = 0); + // LevelRangeFilter(const LevelRangeFilter &rOther); // Use compiler default + // virtual ~LevelRangeFilter(); // Use compiler default + // LevelRangeFilter &operator=(const LevelRangeFilter &rOther); // Use compiler default + + bool acceptOnMatch() const; + Level levelMax() const; + Level levelMin() const; + void setAcceptOnMatch(bool accept); + void setLevelMax(Level level); + void setLevelMin(Level level); + + virtual Decision decide(const LoggingEvent &rEvent) const; + + protected: + /*! + * Writes all object member variables to the given debug stream \a rDebug + * and returns the stream. + * + * + * %LevelRangeFilter(acceptonmatch:true levelmin:"ERROR" levelmax:"FATAL" + * next:Log4Qt::LevelMatchFilter(0x3bcd960) + * referencecount:1 ) + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; + + private: + bool mAcceptOnMatch; + Level mLevelMin; + Level mLevelMax; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline bool LevelRangeFilter::acceptOnMatch() const + { return mAcceptOnMatch; } + + inline Level LevelRangeFilter::levelMax() const + { return mLevelMax; } + + inline Level LevelRangeFilter::levelMin() const + { return mLevelMin; } + + inline void LevelRangeFilter::setAcceptOnMatch(bool accept) + { mAcceptOnMatch = accept; } + + inline void LevelRangeFilter::setLevelMax(Level level) + { mLevelMax = level; } + + inline void LevelRangeFilter::setLevelMin(Level level) + { mLevelMin = level; } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::LevelRangeFilter, Q_MOVABLE_TYPE); // Use default + + +#endif // LOG4QT_LEVELRANGEFILTER_H diff --git a/src/log4qt/log4qt/varia/listappender.cpp b/src/log4qt/log4qt/varia/listappender.cpp new file mode 100644 index 0000000..169c6b3 --- /dev/null +++ b/src/log4qt/log4qt/varia/listappender.cpp @@ -0,0 +1,161 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: listappender.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/varia/listappender.h" + +#include + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: ListAppender + **************************************************************************/ + + + ListAppender::ListAppender(QObject *pParent) : + AppenderSkeleton(pParent), + mConfiguratorList(false), + mList(), + mMaxCount(0) + { + } + + + ListAppender::~ListAppender() + { + } + + + QList ListAppender::list() const + { + QMutexLocker locker(&mObjectGuard); + + return mList; + } + + + void ListAppender::setMaxCount(int n) + { + QMutexLocker locker(&mObjectGuard); + + if (n < 0) + { + logger()->warn("Attempt to set maximum count for appender '%1' to %2. Using zero instead", name(), n); + n = 0; + } + mMaxCount = n; + ensureMaxCount(); + } + + + QList ListAppender::clearList() + { + QMutexLocker locker(&mObjectGuard); + + QList result = mList; + mList.clear(); + return result; + } + + + // bool ListAppender::requiresLayout() const; + + + void ListAppender::append(const LoggingEvent &rEvent) + { + // Q_ASSERT_X(, "ListAppender::append()", "Lock must be held by caller") + + if ((mMaxCount <= 0) || (mList.size() < mMaxCount)) + mList << rEvent; + } + + void ListAppender::asyncAppend(const LoggingEvent &rEvent) + { + // Q_ASSERT_X(, "ListAppender::asyncAppend()", "Lock must be held by caller") + + if ((mMaxCount <= 0) || (mList.size() < mMaxCount)) + mList << rEvent; + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug ListAppender::debug(QDebug &rDebug) const + { + rDebug.nospace() << "ListAppender(" + << "name:" << name() << " " + << "count:" << list().count() << " " + << "filter:" << firstFilter() << " " + << "isactive:" << isActive() << " " + << "isclosed:" << isClosed() << " " + << "maxcount:" << maxCount() << " " + << "referencecount:" << referenceCount() << " " + << "threshold:" << threshold().toString() + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + void ListAppender::ensureMaxCount() + { + // Q_ASSERT_X(, "ListAppender::ensureMaxCount()", "Lock must be held by caller") + + if (mMaxCount <= 0) + return; + + while (mList.size() > mMaxCount) + mList.removeFirst(); + } + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/varia/listappender.h b/src/log4qt/log4qt/varia/listappender.h new file mode 100644 index 0000000..54e6ae0 --- /dev/null +++ b/src/log4qt/log4qt/varia/listappender.h @@ -0,0 +1,175 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: listappender.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_LISTAPPENDER_H +#define LOG4QT_LISTAPPENDER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/appenderskeleton.h" +#include "ukui-logmacros.h" +#include +#include +#include "log4qt/loggingevent.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + /*! + * \brief The class ListAppender appends logging events to a list for later + * processing. + * + * \note All the functions declared in this class are thread-safe. + * + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT ListAppender : public AppenderSkeleton + { + Q_OBJECT + + /*! + * The property holds, if the Appender is used by a configurator. + * + * The default value is false for not being a configurator list. + * + * \sa configuratorList(), setConfiguratorList() + */ + Q_PROPERTY(bool configuratorList READ configuratorList WRITE setConfiguratorList) + + /*! + * The property holds the maximum count used by the appender. + * + * The default maximum count is -1 for unlimited. + * + * \sa maxCount(), setMaxCount() + */ + Q_PROPERTY(int maxCount READ maxCount WRITE setMaxCount) + + public: + ListAppender(QObject *pParent = 0); + virtual ~ListAppender(); + private: + ListAppender(const ListAppender &rOther); // Not implemented + ListAppender &operator=(const ListAppender &rOther); // Not implemented + + public: + /*! + * Returns true, if the appender is used by a configurator. Otherweise it returns + * false. + * + * \sa setConfiguratorList() + */ + bool configuratorList() const; + + QList list() const; + int maxCount() const; + + /*! + * Sets that the appender is used by a configurator. If set to true, the appender + * will not be removed from a Logger when Logger::removeAllAppenders()is called. + * This way the appender can collect events raised during the configuration process. + * + * \sa configuratorList(), BasicConfigurator, PropertyConfigurator, + * ConfiguratorHelper::configureError() + */ + void setConfiguratorList(bool isConfiguratorList); + + void setMaxCount(int n); + + QList clearList(); + virtual bool requiresLayout() const; + + protected: + virtual void append(const LoggingEvent &rEvent); + virtual void asyncAppend(const LoggingEvent &rEvent); + +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream + * \a rDebug and returns the stream. + * + * + * %ListAppender(name:"LA" count:1 filter:0x41fa488 isactive:true + * isclosed:false maxcount:170 referencecount:1 + * threshold:"TRACE_SET") + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; +#endif // QT_NO_DEBUG_STREAM + + /*! + * Ensures that the count of events is less or equal then the maxium + * count. If the list contains too many items, items are deleted from + * the begin of the list. + */ + void ensureMaxCount(); + + private: + volatile bool mConfiguratorList; + QList mList; + volatile int mMaxCount; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline bool ListAppender::configuratorList() const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mConfiguratorList; } + + inline int ListAppender::maxCount() const + { return mMaxCount; } + + inline void ListAppender::setConfiguratorList(bool isConfiguratorList) + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + mConfiguratorList = isConfiguratorList; } + + inline bool ListAppender::requiresLayout() const + { return false; } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::ListAppender, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_LISTAPPENDER_H diff --git a/src/log4qt/log4qt/varia/nullappender.cpp b/src/log4qt/log4qt/varia/nullappender.cpp new file mode 100644 index 0000000..351a1a6 --- /dev/null +++ b/src/log4qt/log4qt/varia/nullappender.cpp @@ -0,0 +1,109 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: nullappender.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/varia/nullappender.h" + +#include +#include "log4qt/layout.h" +#include "log4qt/loggingevent.h" + + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: NullAppender + **************************************************************************/ + + + NullAppender::NullAppender(QObject *pParent) : + AppenderSkeleton(false, pParent) + { + } + + + NullAppender::~NullAppender() + { + close(); + } + + + void NullAppender::append(const LoggingEvent &rEvent) + { + Q_UNUSED(rEvent); + } + + void NullAppender::asyncAppend(const LoggingEvent &rEvent) + { + Q_UNUSED(rEvent); + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug NullAppender::debug(QDebug &rDebug) const + { + QString layout_name; + if (layout()) + layout_name = layout()->name(); + + rDebug.nospace() << "NullAppender(" + << "name:" << name() << " " + << "isactive:" << isActive() << " " + << "isclosed:" << isClosed() << " " + << "layout:" << layout_name << " " + << "threshold:" << threshold().toString() << " " + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/varia/nullappender.h b/src/log4qt/log4qt/varia/nullappender.h new file mode 100644 index 0000000..d9697b6 --- /dev/null +++ b/src/log4qt/log4qt/varia/nullappender.h @@ -0,0 +1,103 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: nullappender.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_NULLAPPENDER_H +#define LOG4QT_NULLAPPENDER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/appenderskeleton.h" +#include "ukui-logmacros.h" + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + +/*! + * \brief The class NullAppender ignores all requests to append. + * + * \note All the functions declared in this class are thread-safe. + * + * \note The ownership and lifetime of objects of this class are managed. See + * \ref Ownership "Object ownership" for more details. + */ +class LIBUKUILOG4QT_EXPORT NullAppender : public AppenderSkeleton +{ + Q_OBJECT + +public: + NullAppender(QObject *pParent = 0); + virtual ~NullAppender(); +private: + NullAppender(const NullAppender &rOther); // Not implemented + NullAppender &operator=(const NullAppender &rOther); // Not implemented + +public: + virtual bool requiresLayout() const; + +protected: + virtual void append(const LoggingEvent &rEvent); + virtual void asyncAppend(const LoggingEvent &rEvent); + +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream \a rDebug and + * returns the stream. + * + * + * %NullAppender() + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; +#endif // QT_NO_DEBUG_STREAM +}; + + +/****************************************************************************** + * Operators, Helper + ******************************************************************************/ + + +/****************************************************************************** + * Inline + ******************************************************************************/ + +inline bool NullAppender::requiresLayout() const +{ return false; } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::NullAppender, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_NULLAPPENDER_H diff --git a/src/log4qt/log4qt/varia/stringmatchfilter.cpp b/src/log4qt/log4qt/varia/stringmatchfilter.cpp new file mode 100644 index 0000000..e660b21 --- /dev/null +++ b/src/log4qt/log4qt/varia/stringmatchfilter.cpp @@ -0,0 +1,101 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: stringmatchfilter.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/varia/stringmatchfilter.h" + +#include +#include "log4qt/loggingevent.h" + + +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: Filter + **************************************************************************/ + + + StringMatchFilter::StringMatchFilter(QObject *pParent) : + Filter(pParent), + mAcceptOnMatch(true), + mStringToMatch() + {} + + + Filter::Decision StringMatchFilter::decide(const LoggingEvent &rEvent) const + { + if (rEvent.message().isEmpty() || + mStringToMatch.isEmpty() || + rEvent.message().indexOf(mStringToMatch) < 0) + return Filter::NEUTRAL; + + if (mAcceptOnMatch) + return Filter::ACCEPT; + else + return Filter::DENY; + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug StringMatchFilter::debug(QDebug &rDebug) const + { + rDebug.nospace() << "StringMatchFilter(" + << "acceptonmatch:" << mAcceptOnMatch << " " + << "referencecount:" << referenceCount() << " " + << "stringtomatch:" << mStringToMatch << " " + << "next:" << next() + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + + /************************************************************************** + * Implementation: Operators, Helper + **************************************************************************/ + + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/varia/stringmatchfilter.h b/src/log4qt/log4qt/varia/stringmatchfilter.h new file mode 100644 index 0000000..db33e6a --- /dev/null +++ b/src/log4qt/log4qt/varia/stringmatchfilter.h @@ -0,0 +1,133 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: stringmatchfilter.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_STRINGMATCHFILTER_H +#define LOG4QT_STRINGMATCHFILTER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/spi/filter.h" +#include "ukui-logmacros.h" + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +namespace Log4Qt +{ + + /*! + * \brief The class StringMatchFilter allows logging events with a + * specified level. + * + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT StringMatchFilter : public Filter + { + Q_OBJECT + + /*! + * The property holds if an event is accpeted on a match. + * + * The default is true. + * + * \sa acceptOnMatch(), acceptOnMatch() + */ + Q_PROPERTY(bool acceptOnMatch READ acceptOnMatch WRITE setAcceptOnMatch) + + /*! + * The property holds the string to match for this filter. + * + * \sa stringToMatch(), setStringToMatch() + */ + Q_PROPERTY(QString stringToMatch READ stringToMatch WRITE setStringToMatch) + + public: + StringMatchFilter(QObject *pParent = 0); + // StringMatchFilter(const StringMatchFilter &rOther); // Use compiler default + // virtual ~StringMatchFilter(); // Use compiler default + // StringMatchFilter &operator=(const StringMatchFilter &rOther); // Use compiler default + + bool acceptOnMatch() const; + QString stringToMatch() const; + void setAcceptOnMatch(bool accept); + void setStringToMatch(const QString &rString); + + virtual Decision decide(const LoggingEvent &rEvent) const; + + protected: +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream + * \a rDebug and returns the stream. + * + * + * %StringMatchFilter(acceptonmatch:true referencecount:1 + * stringtomatch:"LDAP_STRONG_AUTH_REQUIRED" + * next:Log4Qt::LevelMatchFilter(0x3bdd960) ) + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject) + */ + virtual QDebug debug(QDebug &rDebug) const; +#endif // QT_NO_DEBUG_STREAM + + private: + bool mAcceptOnMatch; + QString mStringToMatch; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline bool StringMatchFilter::acceptOnMatch() const + { return mAcceptOnMatch; } + + inline QString StringMatchFilter::stringToMatch() const + { return mStringToMatch; } + + inline void StringMatchFilter::setAcceptOnMatch(bool accept) + { mAcceptOnMatch = accept; } + + inline void StringMatchFilter::setStringToMatch(const QString &rString) + { mStringToMatch = rString; } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::StringMatchFilter, Q_MOVABLE_TYPE); // Use default + + +#endif // LOG4QT_STRINGMATCHFILTER_H diff --git a/src/log4qt/log4qt/writerappender.cpp b/src/log4qt/log4qt/writerappender.cpp new file mode 100644 index 0000000..f1be768 --- /dev/null +++ b/src/log4qt/log4qt/writerappender.cpp @@ -0,0 +1,320 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: writerappender.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + + +#include "log4qt/writerappender.h" + +#include +#include +#include +#include +#include +#include "log4qt/layout.h" +#include "log4qt/loggingevent.h" +#include "log4qt/helpers/asyncdispatcher.h" + +extern pid_t g_MainProcPid; +namespace Log4Qt +{ + + + /************************************************************************** + * Declarations + **************************************************************************/ + + + + /************************************************************************** + * C helper functions + **************************************************************************/ + + + + /************************************************************************** + * Class implementation: WriterAppender + **************************************************************************/ + + + WriterAppender::WriterAppender(QObject *pParent) : + AppenderSkeleton(false, pParent), + mpEncoding(0), + mpWriter(0), + mImmediateFlush(true) + { + } + + + WriterAppender::WriterAppender(Layout *pLayout, + QObject *pParent) : + AppenderSkeleton(false, pParent), + mpEncoding(0), + mpWriter(0), + mImmediateFlush(true) + { + setLayout(pLayout); + } + + + WriterAppender::WriterAppender(Layout *pLayout, + QTextStream *pTextStream, + QObject *pParent) : + AppenderSkeleton(false, pParent), + mpEncoding(0), + mpWriter(pTextStream), + mImmediateFlush(true) + { + setLayout(pLayout); + } + + + WriterAppender::~WriterAppender() + { + close(); + } + + + void WriterAppender::setEncoding(QTextCodec *pEncoding) + { + QMutexLocker locker(&mObjectGuard); + + if (mpEncoding == pEncoding) + return; + + mpEncoding = pEncoding; + if (mpWriter) + { + if (mpEncoding) + mpWriter->setCodec(mpEncoding); + else + mpWriter->setCodec(QTextCodec::codecForLocale()); + } + } + + + void WriterAppender::setWriter(QTextStream *pTextStream) + { + QMutexLocker locker(&mObjectGuard); + + closeWriter(); + + mpWriter = pTextStream; + if (mpEncoding && mpWriter) + mpWriter->setCodec(mpEncoding); + writeHeader(); + } + + + void WriterAppender::activateOptions() + { + QMutexLocker locker(&mObjectGuard); + + if (!writer()) + { + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Activation of Appender '%1' that requires writer and has no writer set"), + APPENDER_ACTIVATE_MISSING_WRITER_ERROR); + e << name(); + logger()->error(e); + return; + } + + AppenderSkeleton::activateOptions(); + } + + + void WriterAppender::close() + { + QMutexLocker locker(&mObjectGuard); + + if (isClosed()) + return; + + closeInternal(); + AppenderSkeleton::close(); + closeWriter(); + } + + void WriterAppender::closeInternal() + { + if (isClosed()) + return; + } + + bool WriterAppender::requiresLayout() const + { + return true; + } + + + void WriterAppender::append(const LoggingEvent &rEvent) + { + // Q_ASSERT_X(, "WriterAppender::append()", "Lock must be held by caller"); + Q_ASSERT_X(layout(), "WriterAppender::append()", "Layout must not be null"); + QString message(layout()->format(rEvent)); + + if (!mpWriter) + return; + + *mpWriter << message; + if (handleIoErrors()) + return; + + if (immediateFlush()) + { + mpWriter->flush(); + if (handleIoErrors()) + return; + } + } + + void WriterAppender::asyncAppend(const LoggingEvent &rEvent) + { + // Q_ASSERT_X(, "WriterAppender::asyncAppend()", "Lock must be held by caller"); + Q_ASSERT_X(layout(), "WriterAppender::asyncAppend()", "Layout must not be null"); + QString message(layout()->format(rEvent)); + + if (!mpWriter) + return; + + *mpWriter << message; + if (handleIoErrors()) + return; + + if (immediateFlush()) + { + mpWriter->flush(); + if (handleIoErrors()) + return; + } + } + + + bool WriterAppender::checkEntryConditions() const + { + // Q_ASSERT_X(, "WriterAppender::checkEntryConditions()", "Lock must be held by caller") + + if (!writer()) + { + LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of appender '%1' without a writer set"), + APPENDER_USE_MISSING_WRITER_ERROR); + e << name(); + logger()->error(e); + return false; + } + + return AppenderSkeleton::checkEntryConditions(); + } + + + void WriterAppender::closeWriter() + { + // Q_ASSERT_X(, "WriterAppender::closeWriter()", "Lock must be held by caller") + + if (!mpWriter) + return; + + writeFooter(); + mpWriter = 0; + } + + +#ifndef QT_NO_DEBUG_STREAM + QDebug WriterAppender::debug(QDebug &rDebug) const + { + QString layout_name; + if (layout()) + layout_name = layout()->name(); + QString codec_name; + if (encoding()) + codec_name = QLatin1String(encoding()->name()); + + rDebug.nospace() << "WriterAppender(" + << "name:" << name() << " " + << "encoding:" << codec_name << " " + << "filter:" << firstFilter() + << "immediateFlush:" << immediateFlush() + << "isactive:" << isActive() + << "isclosed:" << isClosed() + << "layout:" << layout_name + << "referencecount:" << referenceCount() << " " + << "threshold:" << threshold().toString() + << "writer:" << writer() + << ")"; + return rDebug.space(); + } +#endif // QT_NO_DEBUG_STREAM + + + bool WriterAppender::handleIoErrors() const + { + return false; + } + + + void WriterAppender::writeFooter() const + { + // Q_ASSERT_X(, "WriterAppender::writeFooter()", "Lock must be held by caller") + + if (!layout() || !mpWriter) + return; + + QString footer = layout()->footer(); + if (footer.isEmpty()) + return; + + *mpWriter << footer << Layout::endOfLine(); + if (handleIoErrors()) + return; + } + + + void WriterAppender::writeHeader() const + { + // Q_ASSERT_X(, "WriterAppender::writeHeader()", "Lock must be held by caller") + + if (!layout() || !mpWriter) + return; + + QString header = layout()->header(); + if (header.isEmpty()) + return; + + *mpWriter << header << Layout::endOfLine(); + if (handleIoErrors()) + return; + } + + + + /****************************************************************************** + * Implementation: Operators, Helper + ******************************************************************************/ + + +} // namespace Log4Qt diff --git a/src/log4qt/log4qt/writerappender.h b/src/log4qt/log4qt/writerappender.h new file mode 100644 index 0000000..9961c5e --- /dev/null +++ b/src/log4qt/log4qt/writerappender.h @@ -0,0 +1,204 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: writerappender.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_WRITERAPPENDER_H +#define LOG4QT_WRITERAPPENDER_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qt/appenderskeleton.h" +#include "ukui-logmacros.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +class QTextCodec; +class QTextStream; + +namespace Log4Qt +{ + class AsyncDispatcher; + + /*! + * \brief The class WriterAppender appends log events to a QTextStream. + * + * \note All the functions declared in this class are thread-safe. + *   + * \note The ownership and lifetime of objects of this class are managed. + * See \ref Ownership "Object ownership" for more details. + */ + class LIBUKUILOG4QT_EXPORT WriterAppender : public AppenderSkeleton + { + Q_OBJECT + + /*! + * The property holds the codec the appender uses. + * + * The default is null to use the codec the writer has set. + * + * \sa encoding(), setEncoding() + */ + Q_PROPERTY(QTextCodec* encoding READ encoding WRITE setEncoding) + + /*! + * The property holds the writer the appender uses. + * + * \sa writer(), setWriter() + */ + Q_PROPERTY(QTextStream* writer READ writer WRITE setWriter) + + /*! + * The property holds, if the writer flushes after all write operations. + * + * The default is true for flushing. + * + * \sa immediateFlush(), setImmediateFlush() + */ + Q_PROPERTY(bool immediateFlush READ immediateFlush WRITE setImmediateFlush) + + public: + WriterAppender(QObject *pParent = 0); + WriterAppender(Layout *pLayout, + QObject *pParent = 0); + WriterAppender(Layout *pLayout, + QTextStream *pTextStream, + QObject *pParent = 0); + virtual ~WriterAppender(); + private: + WriterAppender(const WriterAppender &rOther); // Not implemented + WriterAppender &operator=(const WriterAppender &rOther); // Not implemented + void closeInternal(); + + public: + virtual bool requiresLayout() const; + QTextCodec *encoding() const; + bool immediateFlush() const; + QTextStream *writer() const; + + /*! + * Sets the codec used by the writer to \a pTextCoded. + * + * If a codec is set with setEncoding, it will overwrite the codec set + * in the text stream. A subsequent call with \a pTextCoded equals null + * will resets the codec to the default QTextCodec::codecForLocale(). + * + * \sa encoding(), QTextSream::setCodec(), QTextCodec::codecForLocale() + */ + void setEncoding(QTextCodec *pTextCodec); + void setImmediateFlush(bool immediateFlush); + void setWriter(QTextStream *pTextStream); + + virtual void activateOptions(); + virtual void close(); + + protected: + virtual void append(const LoggingEvent &rEvent); + virtual void asyncAppend(const LoggingEvent &rEvent); + + /*! + * Tests if all entry conditions for using append() in this class are + * met. + * + * If a conditions is not met, an error is logged and the function + * returns false. Otherwise the result of + * AppenderSkeleton::checkEntryConditions() is returned. + * + * The checked conditions are: + * - A writer has been set (APPENDER_USE_MISSING_WRITER_ERROR) + * + * The function is called as part of the checkEntryConditions() chain + * started by AppenderSkeleton::doAppend(). + * + * \sa AppenderSkeleton::doAppend(), + * AppenderSkeleton::checkEntryConditions() + */ + virtual bool checkEntryConditions() const; + + void closeWriter(); + +#ifndef QT_NO_DEBUG_STREAM + /*! + * Writes all object member variables to the given debug stream + * \a rDebug and returns the stream. + * + * + * %WriterAppender(name:"WA" encoding:"" immediateFlush:true + * isactive:false isclosed:false layout:"TTCC" + * referencecount:1 threshold:"NULL" + * writer:0x0) + * + * \sa QDebug, operator<<(QDebug debug, const LogObject &rLogObject ) + */ + virtual QDebug debug(QDebug &rDebug) const; +#endif // QT_NO_DEBUG_STREAM + + virtual bool handleIoErrors() const; + void writeFooter() const; + void writeHeader() const; + + private: + QTextCodec *mpEncoding; + QTextStream *mpWriter; + volatile bool mImmediateFlush; + }; + + + /************************************************************************** + * Operators, Helper + **************************************************************************/ + + + /************************************************************************** + * Inline + **************************************************************************/ + + inline QTextCodec *WriterAppender::encoding() const + { QMutexLocker locker(&mObjectGuard); + return mpEncoding; } + + inline bool WriterAppender::immediateFlush() const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mImmediateFlush; } + + inline QTextStream *WriterAppender::writer() const + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + return mpWriter; } + + inline void WriterAppender::setImmediateFlush(bool immediateFlush) + { // QMutexLocker locker(&mObjectGuard); // Read/Write of int is safe + mImmediateFlush = immediateFlush; } + + +} // namespace Log4Qt + + +// Q_DECLARE_TYPEINFO(Log4Qt::WriterAppender, Q_COMPLEX_TYPE); // Use default + + +#endif // LOG4QT_WRITERAPPENDER_H diff --git a/src/log4qt/org.ukui.log4qt-test.gschema.xml b/src/log4qt/org.ukui.log4qt-test.gschema.xml new file mode 100644 index 0000000..6f23845 --- /dev/null +++ b/src/log4qt/org.ukui.log4qt-test.gschema.xml @@ -0,0 +1,39 @@ + + + + "true" + hook qt messages + Control if hook qt messages + + + "DEBUG,console,daily" + config rootLogger's level and appenders + config rootLogger's level and appenders:"level,appender" + + + ".yyyy-MM-dd" + daily log file pattern + set daily log file pattern format:one day + + + "%d{yyyy-MM-dd HH:mm:ss,zzz}(%-4r)[%t]|%-5p| - %m%n" + set log message's format + set log message's format + + + 3600 + set check log files delay time + set check log files delay time + + + 3 + set log files count + set log files count,unit s + + + 512 + set log files total size + set log files total size, unit M + + + diff --git a/src/log4qt/org.ukui.log4qt.gschema.xml b/src/log4qt/org.ukui.log4qt.gschema.xml new file mode 100644 index 0000000..c7bdb66 --- /dev/null +++ b/src/log4qt/org.ukui.log4qt.gschema.xml @@ -0,0 +1,49 @@ + + + + "true" + reset all log4j config + Control if reset all log4j config + + + "INFO" + config logLogger's output level + config logLogger's output level: DEBUG/INFO/WARN/ERROR + + + "true" + hook qt messages + Control if hook qt messages + + + "INFO,daily" + config rootLogger's level and appenders + config rootLogger's level and appenders:"level,appender" + + + ".yyyy-MM-dd" + daily log file pattern + set daily log file pattern format:one day + + + "%d{yyyy-MM-dd HH:mm:ss,zzz}(%-4r)[%t]|%-5p| - %m%n" + set log message's format + set log message's format + + + 3600 + set check log files delay time + set check log files delay time + + + 3 + set log files count + set log files count,unit s + + + 512 + set log files total size + set log files total size, unit M + + + diff --git a/src/log4qt/tests/log4qttest.cpp b/src/log4qt/tests/log4qttest.cpp new file mode 100644 index 0000000..ce47234 --- /dev/null +++ b/src/log4qt/tests/log4qttest.cpp @@ -0,0 +1,2082 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: log4qttest.cpp + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include "log4qttest.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "log4qt/basicconfigurator.h" +#include "log4qt/consoleappender.h" +#include "log4qt/dailyrollingfileappender.h" +#include "log4qt/fileappender.h" +#include "log4qt/helpers/configuratorhelper.h" +#include "log4qt/helpers/datetime.h" +#include "log4qt/helpers/factory.h" +#include "log4qt/helpers/initialisationhelper.h" +#include "log4qt/helpers/optionconverter.h" +#include "log4qt/helpers/patternformatter.h" +#include "log4qt/helpers/properties.h" +#include "log4qt/logmanager.h" +#include "log4qt/loggerrepository.h" +#include "log4qt/patternlayout.h" +#include "log4qt/propertyconfigurator.h" +#include "log4qt/rollingfileappender.h" +#include "log4qt/simplelayout.h" +#include "log4qt/ttcclayout.h" +#include "log4qt/varia/denyallfilter.h" +#include "log4qt/varia/levelmatchfilter.h" +#include "log4qt/varia/levelrangefilter.h" +#include "log4qt/varia/stringmatchfilter.h" + + + +using namespace Log4Qt; + + +/****************************************************************************** + *Declarations + ******************************************************************************/ + + + +/****************************************************************************** + * C helper functions + ******************************************************************************/ + + +QTEST_MAIN(Log4QtTest) +LOG4QT_DECLARE_STATIC_LOGGER(test_logger, Test::TestLog4Qt) + + + +/****************************************************************************** + * Class implementation: Log4QtTest + ******************************************************************************/ + + + +Log4QtTest::Log4QtTest() : +QObject(), +mSkipLongTests(false), +mTemporaryDirectory(), +mpLoggingEvents(0), +mDefaultProperties(), +mProperties(&mDefaultProperties) +{ + // mSkipLongTests = true; +} + + +Log4QtTest::~Log4QtTest() +{ +} + + + +/****************************************************************************** + * log4qt/helpers */ + +void Log4QtTest::initTestCase() +{ + // Logging + LogManager::resetConfiguration(); + + // File system + QString name = QDir::tempPath() + "/Log4QtTest_" + + QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss"); + if (!mTemporaryDirectory.mkdir(name)) + QFAIL("Creation of temporary directory failed"); + mTemporaryDirectory.setPath(name); + qDebug() << "Using temporaray directory: " << mTemporaryDirectory.path(); + + // Appender to track events generated by Log4Qt + mpLoggingEvents = new Log4Qt::ListAppender(this); + mpLoggingEvents->retain(); + mpLoggingEvents->setName("Log4QtTest"); + mpLoggingEvents->setConfiguratorList(true); + resetLogging(); +} + + +void Log4QtTest::cleanupTestCase() +{ + LogManager::resetConfiguration(); + + if (!deleteDirectoryTree(mTemporaryDirectory.path())) + QFAIL("Cleanup of temporary directory failed"); + mpLoggingEvents->release(); +} + + +void Log4QtTest::DateTime_compability_data() +{ + QTest::addColumn("pattern"); + + QTest::newRow("date d") << "d"; + QTest::newRow("date dd") << "dd"; + QTest::newRow("date ddd") << "ddd"; + QTest::newRow("date dddd") << "dddd"; + QTest::newRow("date M") << "M"; + QTest::newRow("date MM") << "MM"; + QTest::newRow("date MMM") << "MMM"; + QTest::newRow("date MMMM") << "MMMM"; + QTest::newRow("date YY") << "YY"; + QTest::newRow("date YYYY") << "YYYY"; + QTest::newRow("time h") << "h"; + QTest::newRow("time hh") << "hh"; + QTest::newRow("time H") << "H"; + QTest::newRow("time HH") << "HH"; + QTest::newRow("time m") << "m"; + QTest::newRow("time mm") << "mm"; + QTest::newRow("time s") << "s"; + QTest::newRow("time ss") << "ss"; + QTest::newRow("time z") << "z"; + QTest::newRow("time zz") << "zz"; + QTest::newRow("time a") << "a"; + QTest::newRow("time ap") << "ap"; + QTest::newRow("time A") << "A"; + QTest::newRow("time AP") << "AP"; + QTest::newRow("datetime") << ""; + QTest::newRow("datetime HHh") << "HHh"; + QTest::newRow("datetime 'M'M'd'd'y'yyhh:mm:ss") << "'M'M'd'd'y'yyhh:mm:ss"; + QTest::newRow("datetime M.d.s") << "M.d.s"; + QTest::newRow("datetime YYYY-MM-ddTHH:mm:ss") << "YYYY-MM-ddTHH:mm:ss"; + QTest::newRow("datetime YYYY-MM-ddTHH:mm:ss.zzz") << "YYYY-MM-ddTHH:mm:ss.zzz"; + QTest::newRow("datetime yyyy-MM-dd HH:mm:ss,zzz") << "yyyy-MM-dd HH:mm:ss,zzz"; + QTest::newRow("datetime dd MMM yyyy HH:mm:ss.zzz") << "dd MMM yyyy HH:mm:ss.zzz"; + QTest::newRow("datetime HH:mm:ss.zzz") << "HH:mm:ss.zzz"; + // Quotes are not handled like in JAVA. 'x''x' -> xx not x'x + QTest::newRow("datetime 'This is a'''' test'") << "'This is a'''' test'"; + // Qt does not ignore literals outside of quotes x'x' -> xx not x + QTest::newRow("datetime This 'is a'''' test'") << "This 'is a'''' test'"; + // HH is handled by toString even if not documented + QTest::newRow("datetime HH:mm AP") << "HH:mm AP"; +} + + +void Log4QtTest::DateTime_compability() +{ + QDateTime reference = QDateTime(QDate(2001, 9, 7), QTime(15, 7, 5, 9)); + QDateTime q_date_time(reference); + DateTime date_time(reference); + + QFETCH(QString, pattern); + QCOMPARE(date_time.toString(pattern), q_date_time.toString(pattern)); +} + + +void Log4QtTest::DateTime_week_data() +{ + QTest::addColumn("datetime"); + QTest::addColumn("pattern"); + QTest::addColumn("result"); + + QTest::newRow("week 6") << QDateTime(QDate(2001,2,9), QTime(15,7,5,9)) << "w" << "6"; + QTest::newRow("week 06") << QDateTime(QDate(2001,2,9), QTime(15,7,5,9)) << "ww" << "06"; + QTest::newRow("week 36") << QDateTime(QDate(2001,9,7), QTime(15,7,5,9)) << "w" << "36"; +} + + +void Log4QtTest::DateTime_week() +{ + QFETCH(QDateTime, datetime); + QFETCH(QString, pattern); + QFETCH(QString, result); + + QCOMPARE(static_cast(datetime).toString(pattern), result); +} + + +void Log4QtTest::DateTime_milliseconds_data() +{ + QTest::addColumn("datetime"); + QTest::addColumn("milliseconds"); + + QTest::newRow("2001-09-07 15:07:05.009") << QDateTime(QDate(2001,9,7), QTime(15,7,5,9), Qt::UTC) << Q_INT64_C(999875225009); +} + + +void Log4QtTest::DateTime_milliseconds() +{ + QFETCH(QDateTime, datetime); + QFETCH(qint64, milliseconds); + + QCOMPARE(DateTime(datetime).toMilliSeconds(), milliseconds); + QCOMPARE(DateTime::fromMilliSeconds(milliseconds).toUTC(), datetime); +} + + +void Log4QtTest::PatternFormatter_data() +{ + QTest::addColumn("event"); + QTest::addColumn("pattern"); + QTest::addColumn("result"); + QTest::addColumn("event_count"); + + // Create end of line + QString eol; +#ifdef Q_OS_WIN32 + eol = QLatin1String("\r\n"); +#else + eol = QLatin1String("\n"); +#endif // Q_OS_WIN32 + // Prepare event data + int relative_offset = 17865; + qint64 relative_timestamp = InitialisationHelper::startTime() + relative_offset; + QString relative_string = QString::number(relative_offset); + qint64 absolute_timestamp = + DateTime(QDateTime(QDate(2001,9,7), QTime(15,7,5,9))).toMilliSeconds(); + QHash properties; + properties.insert("A", "a"); + properties.insert("B", "b"); + properties.insert("C", "c"); + + QTest::newRow("Default conversion") + << LoggingEvent(test_logger(), + Level(Level::DEBUG_INT), + "This is the message") + << "%m%n" + << "This is the message" + eol + << 0; + QTest::newRow("TTCC conversion") + << LoggingEvent(test_logger(), + Level(Level::DEBUG_INT), + "This is the message", + "NDC", + properties, + "main", + relative_timestamp) + << "%r [%t] %p %c %x - %m%n" + << relative_string + " [main] DEBUG Test::TestLog4Qt NDC - This is the message" + eol + << 0; + QTest::newRow("Java class documentation example 1") + << LoggingEvent(test_logger(), + Level(Level::WARN_INT), + "This is the message", + "NDC", + properties, + "main", + relative_timestamp) + << "%-5p [%t]: %m%n" + << "WARN [main]: This is the message" + eol + << 0; + QTest::newRow("Java class documentation example 2") + << LoggingEvent(test_logger(), + Level(Level::INFO_INT), + "This is the message", + "NDC", + properties, + "main", + relative_timestamp) + << "%r [%t] %-5p %c %x - %m%n" + << relative_string + " [main] INFO Test::TestLog4Qt NDC - This is the message" + eol + << 0; + QTest::newRow("Java class documentation example 2") + << LoggingEvent(test_logger(), + Level(Level::INFO_INT), + "This is the message", + "NDC", + properties, + "main", + relative_timestamp) + << "%-6r [%15.15t] %-5p %30.30c %x - %m%n" + << relative_string + " [ main] INFO Test::TestLog4Qt NDC - This is the message" + eol + << 0; + QTest::newRow("Java class documentation example 2, truncating") + << LoggingEvent(test_logger(), + Level(Level::INFO_INT), + "This is the message", + "NDC", + properties, + "threadwithextralongname", + relative_timestamp) + << "%-6r [%15.15t] %-5p %30.30c %x - %m%n" + << relative_string + " [threadwithextra] INFO Test::TestLog4Qt NDC - This is the message" + eol + << 0; + QTest::newRow("TTCC with ISO date") + << LoggingEvent(test_logger(), + Level(Level::DEBUG_INT), + "This is the message", + "NDC", + properties, + "main", + absolute_timestamp) + << "%d{ISO8601} [%t] %p %c %x - %m%n" + << "2001-09-07 15:07:05.009 [main] DEBUG Test::TestLog4Qt NDC - This is the message" + eol + << 0; + + resetLogging(); +} + + +void Log4QtTest::PatternFormatter() +{ + QFETCH(LoggingEvent, event); + QFETCH(QString, pattern); + QFETCH(QString, result); + QFETCH(int, event_count); + + Log4Qt::PatternFormatter pattern_formatter(pattern); + QCOMPARE(pattern_formatter.format(event), result); + + QCOMPARE(mpLoggingEvents->list().count(), event_count); +} + + +void Log4QtTest::Properties_default_data() +{ + mDefaultProperties.clear(); + mDefaultProperties.setProperty("X", "x"); + + mProperties.clear(); + mProperties.setProperty("A", "a"); + mProperties.setProperty("B", ""); + mProperties.setProperty("C", QString()); + + QTest::addColumn("key"); + QTest::addColumn("value"); + + QTest::newRow("Existing value") << "A" << "a"; + QTest::newRow("Empty value") << "B" << ""; + QTest::newRow("Null value") << "C" << ""; + QTest::newRow("Default value") << "X" << "x"; + QTest::newRow("Non existing value") << "D" << QString(); +} + + +void Log4QtTest::Properties_default() +{ + QFETCH(QString, key); + QFETCH(QString, value); + + QCOMPARE(mProperties.property(key), value); +} + + +void Log4QtTest::Properties_names() +{ + mDefaultProperties.clear(); + mDefaultProperties.setProperty("X", "x"); + + mProperties.clear(); + mProperties.setProperty("A", "a"); + mProperties.setProperty("B", ""); + + QStringList property_names = mProperties.propertyNames(); + QCOMPARE(property_names.count(), 3); + QVERIFY(property_names.contains("A")); + QVERIFY(property_names.count("B")); + QVERIFY(property_names.count("X")); +} + + +void Log4QtTest::Properties_load_device_data() +{ + QTest::addColumn("buffer"); + QTest::addColumn("property_count"); + QTest::addColumn("key"); + QTest::addColumn("value"); + QTest::addColumn("event_count"); + + QByteArray buffer; + QBuffer device(&buffer); + QTextStream stream(&device); + + buffer.clear(); + device.open(QIODevice::WriteOnly); + stream << "Truth = Beauty" << endl; + device.close(); + QTest::newRow("Java class documentation example 1a") + << buffer << 1 << "Truth" << "Beauty" << 0; + + buffer.clear(); + device.open(QIODevice::WriteOnly); + stream << " Truth:Beauty" << endl; + device.close(); + QTest::newRow("Java class documentation example 1b") + << buffer << 1 << "Truth" << "Beauty" << 0; + + buffer.clear(); + device.open(QIODevice::WriteOnly); + stream << "Truth :Beauty" << endl; + device.close(); + QTest::newRow("Java class documentation example 1c") + << buffer << 1 << "Truth" << "Beauty" << 0; + + buffer.clear(); + device.open(QIODevice::WriteOnly); + stream << "fruits apple, banana, pear, \\" << endl; + stream << " cantaloupe, watermelon, \\" << endl; + stream << " kiwi, mango" << endl; + device.close(); + QTest::newRow("Java class documentation example 2") + << buffer << 1 << "fruits" + << "apple, banana, pear, cantaloupe, watermelon, kiwi, mango" << 0; + + buffer.clear(); + device.open(QIODevice::WriteOnly); + stream << "cheese" << endl; + device.close(); + QTest::newRow("Java class documentation example 3") + << buffer << 1 << "cheese" << "" << 0; + + buffer.clear(); + device.open(QIODevice::WriteOnly); + stream << "K\\ e\\=\\:y Value" << endl; + device.close(); + QTest::newRow("Key escape sequences") + << buffer << 1 << "K e=:y" << "Value" << 0; + + buffer.clear(); + device.open(QIODevice::WriteOnly); + stream << "Key V\\t\\n\\ra\\\\l\\\"u\\\'e" << endl; + device.close(); + QTest::newRow("Value escape sequences") + << buffer << 1 << "Key" << "V\t\n\ra\\l\"u\'e" << 0; + + buffer.clear(); + device.open(QIODevice::WriteOnly); + stream << "Key\\t Value\\j" << endl; + device.close(); + QTest::newRow("Invalid escape sequences") + << buffer << 1 << "Keyt" << "Valuej" << 2; + + buffer.clear(); + device.open(QIODevice::WriteOnly); + stream << "Key Valu\\u006fe" << endl; + device.close(); + QTest::newRow("Unicode escape sequence") + << buffer << 1 << "Key" << "Valuoe" << 0; + + buffer.clear(); + device.open(QIODevice::WriteOnly); + stream << "Key Value\\u6f" << endl; + device.close(); + QTest::newRow("Unicode escape sequence at the end") + << buffer << 1 << "Key" << "Valueo" << 0; + + buffer.clear(); + device.open(QIODevice::WriteOnly); + stream << ": Value" << endl; + device.close(); + QTest::newRow("Empty key") + << buffer << 1 << "" << "Value" << 1; + + resetLogging(); +} + + +void Log4QtTest::Properties_load_device() +{ + QFETCH(QByteArray, buffer); + QFETCH(int, property_count); + QFETCH(QString, key); + QFETCH(QString, value); + QFETCH(int, event_count); + + mpLoggingEvents->clearList(); + + QBuffer device(&buffer); + QTextStream stream(&device); + device.open(QIODevice::ReadOnly); + + Properties properties; + properties.load(&device); + + QCOMPARE(properties.count(), property_count); + QVERIFY(properties.contains(key)); + QCOMPARE(properties.value(key), value); + QCOMPARE(mpLoggingEvents->list().count(), event_count); +} + + +void Log4QtTest::Properties_load_settings() +{ + QSettings settings(mTemporaryDirectory.path() + + "/PropetiesLoadSettings.ini", QSettings::IniFormat); + QBitArray bit_array(5, true); + + settings.setValue("A", "a"); + settings.setValue("Group/B", "b"); + settings.setValue("Group/C", true); + settings.setValue("Group/D", bit_array); + settings.setValue("Group/Subgroup/E", "e"); + + settings.beginGroup("Group"); + Properties properties; + properties.load(settings); + + QCOMPARE(properties.count(), 3); + QVERIFY(properties.contains("B")); + QCOMPARE(properties.value("B"), QString("b")); + QVERIFY(properties.contains("C")); + QCOMPARE(properties.value("C"), QString("true")); + QVERIFY(properties.contains("D")); + QCOMPARE(properties.value("D"), QString()); +} + + + +/****************************************************************************** + * OptionConverter requires Properties */ + + +void Log4QtTest::OptionConverter_boolean_data() +{ + QTest::addColumn("value"); + QTest::addColumn("default_value"); + QTest::addColumn("result"); + QTest::addColumn("event_count"); + + QTest::newRow("true") << "true" << false << true << 0; + QTest::newRow("enabled") << "enabled" << false << true << 0; + QTest::newRow("1") << "1" << false << true << 0; + QTest::newRow("false") << "false" << true << false << 0; + QTest::newRow("disabled") << "disabled" << true << false << 0; + QTest::newRow("0") << "0" << true << false << 0; + QTest::newRow("Case") << "tRuE" << false << true << 0; + QTest::newRow("Trim") << " true " << false << true << 0; + QTest::newRow("No Boolean") << "NoBool" << false << false << 1; + + resetLogging(); +} + + +void Log4QtTest::OptionConverter_boolean() +{ + QFETCH(QString, value); + QFETCH(bool, default_value); + QFETCH(bool, result); + QFETCH(int, event_count); + + mpLoggingEvents->clearList(); + QCOMPARE(OptionConverter::toBoolean(value, default_value), result); + QCOMPARE(mpLoggingEvents->list().count(), event_count); +} + + +void Log4QtTest::OptionConverter_filesize_data() +{ + QTest::addColumn("value"); + QTest::addColumn("result_ok"); + QTest::addColumn("result"); + QTest::addColumn("event_count"); + + QTest::newRow("Int") + << "135" << true << Q_INT64_C(135) << 0; + QTest::newRow("Trim") + << " 135 " << true << Q_INT64_C(135) << 0; + QTest::newRow("KB") + << "2KB" << true << Q_INT64_C(2048) << 0; + QTest::newRow("KB case") + << "2kb" << true << Q_INT64_C(2048) << 0; + QTest::newRow("KB trim") + << " 2KB " << true << Q_INT64_C(2048) << 0; + QTest::newRow("MB") + << "100MB" << true << Q_INT64_C(104857600) << 0; + QTest::newRow("GB") + << "2GB" << true << Q_INT64_C(2147483648) << 0; + QTest::newRow("Invalid negative") + << "-1" << false << Q_INT64_C(0) << 1; + QTest::newRow("Invalid character") + << "x" << false << Q_INT64_C(0) << 1; + QTest::newRow("Invalid character with unit") + << "xkb" << false << Q_INT64_C(0) << 1; + QTest::newRow("Invalid additional text") + << "2KBx" << false << Q_INT64_C(0) << 1; + + resetLogging(); +} + + +void Log4QtTest::OptionConverter_filesize() +{ + QFETCH(QString, value); + QFETCH(bool, result_ok); + QFETCH(qint64, result); + QFETCH(int, event_count); + + mpLoggingEvents->clearList(); + bool ok; + QCOMPARE(OptionConverter::toFileSize(value, &ok), result); + QCOMPARE(ok, result_ok); + QCOMPARE(mpLoggingEvents->list().count(), event_count); +} + + +void Log4QtTest::OptionConverter_int_data() +{ + QTest::addColumn("value"); + QTest::addColumn("result_ok"); + QTest::addColumn("result"); + QTest::addColumn("event_count"); + + QTest::newRow("Positive") << "12" << true << 12 << 0; + QTest::newRow("Negative") << "-1" << true << -1 << 0; + QTest::newRow("Trim") << " 12 " << true << 12 << 0; + QTest::newRow("No integer") << "12x" << false << 0 << 1; + + resetLogging(); +} + + +void Log4QtTest::OptionConverter_int() +{ + QFETCH(QString, value); + QFETCH(bool, result_ok); + QFETCH(int, result); + QFETCH(int, event_count); + + mpLoggingEvents->clearList(); + bool ok; + QCOMPARE(OptionConverter::toInt(value, &ok), result); + QCOMPARE(ok, result_ok); + QCOMPARE(mpLoggingEvents->list().count(), event_count); +} + + +void Log4QtTest::OptionConverter_level_data() +{ + QTest::addColumn("value"); + QTest::addColumn("default_value"); + QTest::addColumn("result"); + QTest::addColumn("event_count"); + + QTest::newRow("Case") + << "WaRn" + << Log4Qt::Level(Log4Qt::Level::ERROR_INT) + << Log4Qt::Level(Log4Qt::Level::WARN_INT) + << 0; + QTest::newRow("Trim") + << " warn " + << Log4Qt::Level(Log4Qt::Level::ERROR_INT) + << Log4Qt::Level(Log4Qt::Level::WARN_INT) + << 0; + QTest::newRow("Default") + << "NoLevel" + << Log4Qt::Level(Log4Qt::Level::ERROR_INT) + << Log4Qt::Level(Log4Qt::Level::ERROR_INT) + << 2; // One from Level + one from OptionConverter + + resetLogging(); +} + + +void Log4QtTest::OptionConverter_level() +{ + QFETCH(QString, value); + QFETCH(Log4Qt::Level, default_value); + QFETCH(Log4Qt::Level, result); + QFETCH(int, event_count); + + mpLoggingEvents->clearList(); + QCOMPARE(OptionConverter::toLevel(value, default_value), result); + QCOMPARE(mpLoggingEvents->list().count(), event_count); +} + + +void Log4QtTest::OptionConverter_substitution_data() +{ + mDefaultProperties.clear(); + mProperties.clear(); + + QTest::addColumn("key"); + QTest::addColumn("value"); + QTest::addColumn("result"); + QTest::addColumn("event_count"); + + QTest::newRow("Existing value") + << "A" << "a" << "a" << 0; + QTest::newRow("Existing value") + << "B" << "b" << "b" << 0; + QTest::newRow("Empty value") + << "C" << "" << "" << 0; + QTest::newRow("Null value") + << "D" << QString() << "" << 0; + QTest::newRow("Substitution") + << "S1" << "begin${A}end" << "beginaend" << 0; + QTest::newRow("Substitution with two values") + << "S2" << "begin${A}end${B}" << "beginaendb" << 0; + QTest::newRow("Substitution recursive") + << "S3" << "${S1}" << "beginaend" << 0; + QTest::newRow("Substitution missing bracket") + << "S4" << "begin${end" << "begin" << 1; + QTest::newRow("Substitution spare brackets") + << "S5" << "begin}${A}}end" << "begin}a}end" << 0; +} + + +void Log4QtTest::OptionConverter_substitution() +{ + QFETCH(QString, key); + QFETCH(QString, value); + QFETCH(QString, result); + QFETCH(int, event_count); + + mpLoggingEvents->clearList(); + mProperties.setProperty(key, value); + QCOMPARE(OptionConverter::findAndSubst(mProperties, key), result); + QCOMPARE(mpLoggingEvents->list().count(), event_count); +} + + +void Log4QtTest::OptionConverter_target_data() +{ + QTest::addColumn("value"); + QTest::addColumn("result_ok"); + QTest::addColumn("result"); + QTest::addColumn("event_count"); + + QTest::newRow("stdout cpp") + << "STDOUT_TARGET" << true << (int)ConsoleAppender::STDOUT_TARGET << 0; + QTest::newRow("stdout java") + << "System.out" << true << (int)ConsoleAppender::STDOUT_TARGET << 0; + QTest::newRow("stderr cpp") + << "STDERR_TARGET" << true << (int)ConsoleAppender::STDERR_TARGET << 0; + QTest::newRow("stderr java") + << "System.err" << true << (int)ConsoleAppender::STDERR_TARGET << 0; + QTest::newRow("trim") + << " STDOUT_TARGET " << true << (int)ConsoleAppender::STDOUT_TARGET << 0; + QTest::newRow("error") + << "Hello" << false << (int)ConsoleAppender::STDOUT_TARGET << 1; +} + + +void Log4QtTest::OptionConverter_target() +{ + QFETCH(QString, value); + QFETCH(bool, result_ok); + QFETCH(int, result); + QFETCH(int, event_count); + + mpLoggingEvents->clearList(); + bool ok; + QCOMPARE(OptionConverter::toTarget(value, &ok), result); + QCOMPARE(ok, result_ok); + QCOMPARE(mpLoggingEvents->list().count(), event_count); +} + + + +/****************************************************************************** + * Factory requires OptionConverter */ + + +void Log4QtTest::Factory_createAppender_data() +{ + QTest::addColumn("classname"); + QTest::addColumn("result"); + QTest::addColumn("event_count"); + + QTest::newRow("ConsoleAppender java") + << "org.apache.log4j.ConsoleAppender" << "Log4Qt::ConsoleAppender" << 0; + QTest::newRow("ConsoleAppender cpp") + << "Log4Qt::ConsoleAppender" << "Log4Qt::ConsoleAppender" << 0; + QTest::newRow("DailyRollingFileAppender java") + << "org.apache.log4j.DailyRollingFileAppender" << "Log4Qt::DailyRollingFileAppender" << 0; + QTest::newRow("DailyRollingFileAppender cpp") + << "Log4Qt::DailyRollingFileAppender" << "Log4Qt::DailyRollingFileAppender" << 0; + QTest::newRow("DebugAppender java") + << "org.apache.log4j.varia.DebugAppender" << "Log4Qt::DebugAppender" << 0; + QTest::newRow("DebugAppender cpp") + << "Log4Qt::DebugAppender" << "Log4Qt::DebugAppender" << 0; + QTest::newRow("FileAppender java") + << "org.apache.log4j.FileAppender" << "Log4Qt::FileAppender" << 0; + QTest::newRow("FileAppender cpp") + << "Log4Qt::FileAppender" << "Log4Qt::FileAppender" << 0; + QTest::newRow("ListAppender java") + << "org.apache.log4j.varia.ListAppender" << "Log4Qt::ListAppender" << 0; + QTest::newRow("ListAppender cpp") + << "Log4Qt::ListAppender" << "Log4Qt::ListAppender" << 0; + QTest::newRow("NullAppender java") + << "org.apache.log4j.varia.NullAppender" << "Log4Qt::NullAppender" << 0; + QTest::newRow("NullAppender cpp") + << "Log4Qt::NullAppender" << "Log4Qt::NullAppender" << 0; + QTest::newRow("RollingFileAppender java") + << "org.apache.log4j.RollingFileAppender" << "Log4Qt::RollingFileAppender" << 0; + QTest::newRow("RollingFileAppender cpp") + << "Log4Qt::RollingFileAppender" << "Log4Qt::RollingFileAppender" << 0; +} + + +void Log4QtTest::Factory_createAppender() +{ + QFETCH(QString, classname); + QFETCH(QString, result); + QFETCH(int, event_count); + + mpLoggingEvents->clearList(); + QObject *p_object = Factory::createAppender(classname); + QVERIFY(p_object != 0); + QCOMPARE(QString::fromLatin1(p_object->metaObject()->className()), result); + delete p_object; + QCOMPARE(mpLoggingEvents->list().count(), event_count); +} + + +void Log4QtTest::Factory_createFilter_data() +{ + QTest::addColumn("classname"); + QTest::addColumn("result"); + QTest::addColumn("event_count"); + + QTest::newRow("DenyAllFilter java") + << "org.apache.log4j.varia.DenyAllFilter" << "Log4Qt::DenyAllFilter" << 0; + QTest::newRow("DenyAllFilter cpp") + << "Log4Qt::DenyAllFilter" << "Log4Qt::DenyAllFilter" << 0; + QTest::newRow("LevelMatchFilter java") + << "org.apache.log4j.varia.LevelMatchFilter" << "Log4Qt::LevelMatchFilter" << 0; + QTest::newRow("LevelMatchFilter cpp") + << "Log4Qt::LevelMatchFilter" << "Log4Qt::LevelMatchFilter" << 0; + QTest::newRow("LevelRangeFilter java") + << "org.apache.log4j.varia.LevelRangeFilter" << "Log4Qt::LevelRangeFilter" << 0; + QTest::newRow("LevelRangeFilter cpp") + << "Log4Qt::LevelRangeFilter" << "Log4Qt::LevelRangeFilter" << 0; + QTest::newRow("StringMatchFilter java") + << "org.apache.log4j.varia.StringMatchFilter" << "Log4Qt::StringMatchFilter" << 0; + QTest::newRow("StringMatchFilter cpp") + << "Log4Qt::StringMatchFilter" << "Log4Qt::StringMatchFilter" << 0; +} + + +void Log4QtTest::Factory_createFilter() +{ + QFETCH(QString, classname); + QFETCH(QString, result); + QFETCH(int, event_count); + + mpLoggingEvents->clearList(); + QObject *p_object = Factory::createFilter(classname); + QVERIFY(p_object != 0); + QCOMPARE(QString::fromLatin1(p_object->metaObject()->className()), result); + delete p_object; + QCOMPARE(mpLoggingEvents->list().count(), event_count); +} + + +void Log4QtTest::Factory_createLayout_data() +{ + QTest::addColumn("classname"); + QTest::addColumn("result"); + QTest::addColumn("event_count"); + + QTest::newRow("PatternLayout java") + << "org.apache.log4j.PatternLayout" << "Log4Qt::PatternLayout" << 0; + QTest::newRow("PatternLayout cpp") + << "Log4Qt::PatternLayout" << "Log4Qt::PatternLayout" << 0; + QTest::newRow("SimpleLayout java") + << "org.apache.log4j.SimpleLayout" << "Log4Qt::SimpleLayout" << 0; + QTest::newRow("SimpleLayout cpp") + << "Log4Qt::SimpleLayout" << "Log4Qt::SimpleLayout" << 0; + QTest::newRow("TTCCLayout java") + << "org.apache.log4j.TTCCLayout" << "Log4Qt::TTCCLayout" << 0; + QTest::newRow("TTCCLayout cpp") + << "Log4Qt::TTCCLayout" << "Log4Qt::TTCCLayout" << 0; +} + + +void Log4QtTest::Factory_createLayout() +{ + QFETCH(QString, classname); + QFETCH(QString, result); + QFETCH(int, event_count); + + mpLoggingEvents->clearList(); + QObject *p_object = Factory::createLayout(classname); + QVERIFY(p_object != 0); + QCOMPARE(QString::fromLatin1(p_object->metaObject()->className()), result); + delete p_object; + QCOMPARE(mpLoggingEvents->list().count(), event_count); +} + + +void Log4QtTest::Factory_setObjectProperty_data() +{ + QTest::addColumn("appenderclass"); + QTest::addColumn("property"); + QTest::addColumn("value"); + QTest::addColumn("result_value"); + QTest::addColumn("event_count"); + + QTest::newRow("Bool") + << "Log4Qt::FileAppender" + << "immediateFlush" << "false" + << "false" << 0; + QTest::newRow("Int") + << "Log4Qt::ListAppender" + << "maxCount" << "10" + << "10" << 0; + QTest::newRow("QString") + << "Log4Qt::FileAppender" + << "file" << "C:\\tmp\\mylog.txt" + << "C:\\tmp\\mylog.txt" << 0; + QTest::newRow("Null object") + << "Log4Qt::NullAppender" + << "maxCount" << "10" + << "" << 1; + QTest::newRow("Empty property string") + << "Log4Qt::NullAppender" + << "" << "10" + << "" << 1; + QTest::newRow("Property does not exist") + << "Log4Qt::NullAppender" + << "Colour" << "10" + << "" << 1; + QTest::newRow("Property not writable") + << "Log4Qt::NullAppender" + << "isClosed" << "10" + << "" << 1; + QTest::newRow("Property of wrong type") + << "Log4Qt::RollingFileAppender" + << "maximumFileSize" << "7" + << "" << 1; +} + + +void Log4QtTest::Factory_setObjectProperty() +{ + QFETCH(QString, appenderclass); + QFETCH(QString, property); + QFETCH(QString, value); + QFETCH(QString, result_value); + QFETCH(int, event_count); + + mpLoggingEvents->clearList(); + QObject *p_object = Factory::createAppender(appenderclass); + + Factory::setObjectProperty(p_object, property, value); + QCOMPARE(mpLoggingEvents->list().count(), event_count); + if (mpLoggingEvents->list().count() == 0) + QCOMPARE(p_object->property(property.toLatin1()).toString(), result_value); + + delete p_object; +} + + + +/****************************************************************************** + * log4qt/varia */ + + +void Log4QtTest::ListAppender() +{ + Log4Qt::ListAppender appender; + + // Store messages + QCOMPARE(appender.list().count(), 0); + appender.doAppend(LoggingEvent(test_logger(), Level::WARN_INT, "Message1")); + appender.doAppend(LoggingEvent(test_logger(), Level::WARN_INT, "Message2")); + appender.doAppend(LoggingEvent(test_logger(), Level::WARN_INT, "Message3")); + QCOMPARE(appender.list().count(), 3); + + // Delete oldest, if max is set + appender.setMaxCount(2); + QCOMPARE(appender.list().count(), 2); + QCOMPARE(appender.list().at(0).message(), QString("Message2")); + QCOMPARE(appender.list().at(1).message(), QString("Message3")); + + // Ignore new ones added + appender.doAppend(LoggingEvent(test_logger(), Level::WARN_INT, "Message4")); + QCOMPARE(appender.list().count(), 2); + QCOMPARE(appender.list().at(0).message(), QString("Message2")); + QCOMPARE(appender.list().at(1).message(), QString("Message3")); + + // Clear + appender.clearList(); + QCOMPARE(appender.list().count(), 0); +} + + +void Log4QtTest::DenyAllFilter() +{ + Log4Qt::DenyAllFilter filter; + LoggingEvent event(test_logger(), Level::WARN_INT, "Message"); + QCOMPARE(filter.decide(event), Filter::DENY); +} + + +void Log4QtTest::LevelMatchFilter_data() +{ + QTest::addColumn("filter_level"); + QTest::addColumn("accept_on_match"); + QTest::addColumn("event_level"); + QTest::addColumn("result"); + + QTest::newRow("No match, No accept") << "WARN" << false << "TRACE" << "NEUTRAL"; + QTest::newRow("No match, Accept") << "WARN" << true << "TRACE" << "NEUTRAL"; + QTest::newRow("Match, No accept") << "WARN" << false << "WARN" << "DENY"; + QTest::newRow("Match, Accept") << "WARN" << true << "WARN" << "ACCEPT"; +} + + +void Log4QtTest::LevelMatchFilter() +{ + QFETCH(QString, filter_level); + QFETCH(bool, accept_on_match); + QFETCH(QString, event_level); + QFETCH(QString, result); + + Log4Qt::LevelMatchFilter filter; + filter.setLevelToMatch(Level::fromString(filter_level)); + filter.setAcceptOnMatch(accept_on_match); + LoggingEvent + event(test_logger(), Level::fromString(event_level), + "Message"); + + QString decision = + enumValueToKey(&filter, "Decision", filter.decide(event)); + QCOMPARE(decision, result); +} + + +void Log4QtTest::LevelRangeFilter_data() +{ + QTest::addColumn("filter_min_level"); + QTest::addColumn("filter_max_level"); + QTest::addColumn("accept_on_match"); + QTest::addColumn("event_level"); + QTest::addColumn("result"); + + QTest::newRow("Too low, No accept") << "DEBUG" << "ERROR" << false << "TRACE" << "DENY"; + QTest::newRow("Too high, No accept") << "DEBUG" << "ERROR" << false << "FATAL" << "DENY"; + QTest::newRow("Min, No accept") << "DEBUG" << "ERROR" << false << "DEBUG" << "NEUTRAL"; + QTest::newRow("Inside, No accept") << "DEBUG" << "ERROR" << false << "WARN" << "NEUTRAL"; + QTest::newRow("Max, No accept") << "DEBUG" << "ERROR" << false << "ERROR" << "NEUTRAL"; + QTest::newRow("Min not initialised, No accept") << "" << "ERROR" << false << "TRACE" << "NEUTRAL"; + QTest::newRow("Max not initialised, No accept") << "DEBUG" << "" << false << "FATAL" << "NEUTRAL"; + QTest::newRow("Too low, Accept") << "DEBUG" << "ERROR" << true << "TRACE" << "DENY"; + QTest::newRow("Too high, Accept") << "DEBUG" << "ERROR" << true << "FATAL" << "DENY"; + QTest::newRow("Min, Accept") << "DEBUG" << "ERROR" << true << "DEBUG" << "ACCEPT"; + QTest::newRow("Inside, Accept") << "DEBUG" << "ERROR" << true << "WARN" << "ACCEPT"; + QTest::newRow("Max, Accept") << "DEBUG" << "ERROR" << true << "ERROR" << "ACCEPT"; + QTest::newRow("Min not initialised, Accept") << "" << "ERROR" << true << "TRACE" << "ACCEPT"; + QTest::newRow("Max not initialised, Accept") << "DEBUG" << "" << true << "FATAL" << "ACCEPT"; +} + + +void Log4QtTest::LevelRangeFilter() +{ + QFETCH(QString, filter_min_level); + QFETCH(QString, filter_max_level); + QFETCH(bool, accept_on_match); + QFETCH(QString, event_level); + QFETCH(QString, result); + + Log4Qt::LevelRangeFilter filter; + if (!filter_min_level.isEmpty()) + filter.setLevelMin(Level::fromString(filter_min_level)); + if (!filter_max_level.isEmpty()) + filter.setLevelMax(Level::fromString(filter_max_level)); + filter.setAcceptOnMatch(accept_on_match); + LoggingEvent + event(test_logger(), Level::fromString(event_level), + "Message"); + + QString decision = + enumValueToKey(&filter, "Decision", filter.decide(event)); + QCOMPARE(decision, result); +} + + +void Log4QtTest::StringMatchFilter_data() +{ + QTest::addColumn("filter_string"); + QTest::addColumn("accept_on_match"); + QTest::addColumn("event_string"); + QTest::addColumn("result"); + + QTest::newRow("No match, No accept") << "MESSAGE" << false << "This is a message" << "NEUTRAL"; + QTest::newRow("Match, No accept") << "This" << false << "This is a message" << "DENY"; + QTest::newRow("No match, Accept") << "MESSAGE" << true << "This is a message" << "NEUTRAL"; + QTest::newRow("Match, Accept") << "This" << true << "This is a message" << "ACCEPT"; + QTest::newRow("Empty message, No accept") << "This" << false << "" << "NEUTRAL"; + QTest::newRow("Empty message, Accept") << "This" << true << "" << "NEUTRAL"; + QTest::newRow("Empty filter, No accept") << "" << false << "This is a message" << "NEUTRAL"; + QTest::newRow("Empty filter, Accept") << "" << true << "This is a message" << "NEUTRAL"; +} + + +void Log4QtTest::StringMatchFilter() +{ + QFETCH(QString, filter_string); + QFETCH(bool, accept_on_match); + QFETCH(QString, event_string); + QFETCH(QString, result); + + Log4Qt::StringMatchFilter filter; + filter.setStringToMatch(filter_string); + filter.setAcceptOnMatch(accept_on_match); + LoggingEvent event(test_logger(), Level::WARN_INT, event_string); + + QString decision = + enumValueToKey(&filter, "Decision", filter.decide(event)); + QCOMPARE(decision, result); +} + + + +/****************************************************************************** + * log4qt */ + + +void Log4QtTest::AppenderSkeleton_threshold() +{ + resetLogging(); + + Log4Qt::ListAppender *p_appender = new Log4Qt::ListAppender(); + Log4Qt::Logger *p_logger = test_logger(); + p_logger->addAppender(p_appender); + + // Threshold + p_appender->setThreshold(Level::ERROR_INT); + p_appender->doAppend(LoggingEvent(p_logger, Level::WARN_INT, "Warn")); + p_appender->doAppend(LoggingEvent(p_logger, Level::ERROR_INT, "Error")); + p_appender->doAppend(LoggingEvent(p_logger, Level::FATAL_INT, "Fatal")); + QCOMPARE(p_appender->list().count(), 2); + QCOMPARE(p_appender->list().at(0).level(), Level(Level::ERROR_INT)); + QCOMPARE(p_appender->list().at(1).level(), Level(Level::FATAL_INT)); +} + + +void Log4QtTest::AppenderSkeleton_filter_data() +{ + resetLogging(); + + QTest::addColumn("filter1_level"); + QTest::addColumn("filter1_accept"); + QTest::addColumn("filter2_level"); + QTest::addColumn("filter2_accept"); + QTest::addColumn("event_level"); + QTest::addColumn("event_count"); + + QTest::newRow("Single filter, NEUTRAL") + << "WARN" << true << "" << true << "TRACE" << 1; + QTest::newRow("Single filter, ACCEPT") + << "WARN" << true << "" << true << "WARN" << 1; + QTest::newRow("Single filter, DENY") + << "WARN" << false << "" << true << "WARN" << 0; + + QTest::newRow("Double filter, NEUTRAL NEUTRAL") + << "WARN" << true << "WARN" << true << "TRACE" << 1; + QTest::newRow("Double filter, NEUTRAL ACCEPT") + << "WARN" << true << "TRACE" << true << "TRACE" << 1; + QTest::newRow("Double filter, NEUTRAL DENY") + << "WARN" << true << "TRACE" << false << "TRACE" << 0; + + QTest::newRow("Double filter, ACCEPT NEUTRAL") + << "WARN" << true << "TRACE" << true << "WARN" << 1; + QTest::newRow("Double filter, ACCEPT ACCEPT") + << "WARN" << true << "WARN" << true << "WARN" << 1; + QTest::newRow("Double filter, ACCEPT DENY") + << "WARN" << true << "WARN" << false << "WARN" << 1; + + QTest::newRow("Double filter, DENY NEUTRAL") + << "WARN" << false << "TRACE" << true << "WARN" << 0; + QTest::newRow("Double filter, DENY ACCEPT") + << "WARN" << false << "WARN" << true << "WARN" << 0; + QTest::newRow("Double filter, DENY DENY") + << "WARN" << false << "WARN" << false << "WARN" << 0; +} + + +void Log4QtTest::AppenderSkeleton_filter() +{ + QFETCH(QString, filter1_level); + QFETCH(bool, filter1_accept); + QFETCH(QString, filter2_level); + QFETCH(bool, filter2_accept); + QFETCH(QString, event_level); + QFETCH(int, event_count); + + Log4Qt::ListAppender appender; + + if (!filter1_level.isEmpty()) + { + Log4Qt::LevelMatchFilter *p_filter = new Log4Qt::LevelMatchFilter(); + p_filter->setLevelToMatch(Level::fromString(filter1_level)); + p_filter->setAcceptOnMatch(filter1_accept); + appender.addFilter(p_filter); + } + if (!filter2_level.isEmpty()) + { + Log4Qt::LevelMatchFilter *p_filter = new Log4Qt::LevelMatchFilter(); + p_filter->setLevelToMatch(Level::fromString(filter2_level)); + p_filter->setAcceptOnMatch(filter2_accept); + appender.addFilter(p_filter); + } + + appender.doAppend(LoggingEvent(test_logger(), + Level::fromString(event_level), "Message")); + QCOMPARE(appender.list().count(), event_count); +} + + +void Log4QtTest::BasicConfigurator() +{ + LogManager::resetConfiguration(); + resetLogging(); + QVERIFY(Log4Qt::BasicConfigurator::configure()); + + Logger *p_logger = LogManager::rootLogger(); + QCOMPARE(p_logger->appenders().count(), 1); + ConsoleAppender *p_appender = + qobject_cast(p_logger->appenders().at(0)); + QCOMPARE(p_appender != 0, true); + QVERIFY(p_appender->isActive()); + QVERIFY(!p_appender->isClosed()); + QCOMPARE(p_appender->target(), QString::fromLatin1("STDOUT_TARGET")); + PatternLayout *p_layout = + qobject_cast(p_appender->layout()); + QVERIFY(p_layout != 0); + QCOMPARE(p_layout->conversionPattern(), QString("%r [%t] %p %c %x - %m%n")); + + // Log4Qt::Logger *logger = LogManager::rootLogger(); + // logger->trace("Trace message"); //Disabled by default + // logger->debug("Debug message"); + // logger->info("Info message"); + // logger->warn("Warn message"); + // logger->error("Error message"); + // logger->fatal("Fatal message"); +} + + +void Log4QtTest::FileAppender() +{ + resetLogging(); + + QString dir(mTemporaryDirectory.path() + "/FileAppender"); + QString file("/log"); + + Log4Qt::FileAppender appender1(new SimpleLayout(), dir + file, false); + appender1.setName("Fileappender1"); + appender1.activateOptions(); + appender1.doAppend(LoggingEvent(test_logger(), Level::DEBUG_INT, + QString("Message 0"))); + appender1.doAppend(LoggingEvent(test_logger(), Level::DEBUG_INT, + QString("Message 1"))); + appender1.close(); + QStringList expected; + QString result; + expected << "log"; + if (!validateDirContents(dir, expected, result)) + QFAIL(qPrintable(result)); + expected.clear(); + expected << "DEBUG - Message 0" << "DEBUG - Message 1"; + if (!validateFileContents(dir + file, expected, result)) + QFAIL(qPrintable(result)); + + Log4Qt::FileAppender appender2(new SimpleLayout(), dir + file, false); + appender2.setName("Fileappender2"); + appender2.activateOptions(); + appender2.doAppend(LoggingEvent(test_logger(), Level::DEBUG_INT, + QString("Message 2"))); + appender2.doAppend(LoggingEvent(test_logger(), Level::DEBUG_INT, + QString("Message 3"))); + appender2.close(); + expected.clear(); + expected << "log"; + if (!validateDirContents(dir, expected, result)) + QFAIL(qPrintable(result)); + expected.clear(); + expected << "DEBUG - Message 2" << "DEBUG - Message 3"; + if (!validateFileContents(dir + file, expected, result)) + QFAIL(qPrintable(result)); + + Log4Qt::FileAppender appender3(new SimpleLayout(), dir + file, true); + appender3.setName("Fileappender3"); + appender3.activateOptions(); + appender3.doAppend(LoggingEvent(test_logger(), Level::DEBUG_INT, + QString("Message 4"))); + appender3.doAppend(LoggingEvent(test_logger(), Level::DEBUG_INT, + QString("Message 5"))); + appender3.close(); + expected.clear(); + expected << "log"; + if (!validateDirContents(dir, expected, result)) + QFAIL(qPrintable(result)); + expected.clear(); + expected + << "DEBUG - Message 2" << "DEBUG - Message 3" + << "DEBUG - Message 4" << "DEBUG - Message 5"; + if (!validateFileContents(dir + file, expected, result)) + QFAIL(qPrintable(result)); + + QCOMPARE(mpLoggingEvents->list().count(), 0); +} + + +void Log4QtTest::DailyRollingFileAppender() +{ + resetLogging(); + + if (mSkipLongTests) +#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) + QSKIP("Skipping long running test"); +#else + QSKIP("Skipping long running test", SkipSingle); +#endif + qDebug() << "The test is time based and takes approximately 3 minutes ..."; + + QString dir(mTemporaryDirectory.path() + "/DailyRollingFileAppender"); + QString file("/log"); + + // Using a RollingFileAppender with 2 files history and 3 messages per file + Log4Qt::DailyRollingFileAppender appender; + appender.setName("DailyRollingFileAppender"); + appender.setFile(dir + file); + appender.setLayout(new SimpleLayout()); + appender.setDatePattern(DailyRollingFileAppender::MINUTELY_ROLLOVER); + + // Start on a full minute + QDateTime now = QDateTime::currentDateTime(); + QTest::qSleep((60 - now.time().second()) * 1000); + appender.activateOptions(); + + qDebug() << " 1 / 7"; + appender.doAppend(LoggingEvent(test_logger(), Level::DEBUG_INT, + QString("Message 0"))); + int i; + for (i = 1; i < 7; i++) + { + QTest::qSleep(21 * 1000); + qDebug() << " " << i + 1 << "/" << 7; + appender.doAppend(LoggingEvent(test_logger(), Level::DEBUG_INT, + QString("Message %1").arg(i))); + } + + QCOMPARE(mpLoggingEvents->list().count(), 0); + + // Validate directory + QStringList expected; + QString result; + expected << "log" << "log" + + dailyRollingFileAppenderSuffix(now.addSecs(60)) << "log" + + dailyRollingFileAppenderSuffix(now.addSecs(120)); + if (!validateDirContents(dir, expected, result)) + QFAIL(qPrintable(result)); + + // Validate files + expected.clear(); + expected << "DEBUG - Message 6"; + if (!validateFileContents(dir + file, expected, result)) + QFAIL(qPrintable(result)); + expected.clear(); + expected << "DEBUG - Message 0" << "DEBUG - Message 1" + << "DEBUG - Message 2"; + if (!validateFileContents(dir + file + + dailyRollingFileAppenderSuffix(now.addSecs(60)), + expected, result)) + QFAIL(qPrintable(result)); + expected.clear(); + expected << "DEBUG - Message 3" << "DEBUG - Message 4" + << "DEBUG - Message 5"; + if (!validateFileContents(dir + file + + dailyRollingFileAppenderSuffix(now.addSecs(120)), + expected, result)) + QFAIL(qPrintable(result)); +} + + +void Log4QtTest::LoggingEvent_stream_data() +{ + QTest::addColumn("original"); + + qint64 timestamp = + DateTime(QDateTime(QDate(2001,9,7), QTime(15,7,5,9))).toMilliSeconds(); + QHash properties; + properties.insert("A", "a"); + properties.insert("B", "b"); + properties.insert("C", "c"); + + QTest::newRow("Empty logging event") + << LoggingEvent(); + QTest::newRow("Logging event") + << LoggingEvent(test_logger(), + Level(Level::WARN_INT), + "This is a message", + "NDC", + properties, + "main", + timestamp); + QTest::newRow("Logging no logger") + << LoggingEvent(0, + Level(Level::WARN_INT), + "This is a message", + "NDC", + properties, + "main", + timestamp); + + resetLogging(); +} + + +void Log4QtTest::LoggingEvent_stream() +{ + QFETCH(LoggingEvent, original); + + QByteArray array; + QBuffer buffer(&array); + buffer.open(QIODevice::WriteOnly); + QDataStream stream(&buffer); + stream << original; + buffer.close(); + + buffer.open(QIODevice::ReadOnly); + LoggingEvent streamed; + stream >> streamed; + buffer.close(); + + QCOMPARE(original.level(), streamed.level()); + QCOMPARE(original.loggerName(), streamed.loggerName()); + QCOMPARE(original.message(), streamed.message()); + QCOMPARE(original.ndc(), streamed.ndc()); + QCOMPARE(original.properties().count(), streamed.properties().count()); + QStringList keys = original.properties().keys(); + QString key; + Q_FOREACH(key, keys) + { + QVERIFY(streamed.properties().contains(key)); + QCOMPARE(original.properties().value(key), + streamed.properties().value(key)); + } + QCOMPARE(original.sequenceNumber(), streamed.sequenceNumber()); + QCOMPARE(original.threadName(), streamed.threadName()); + QCOMPARE(original.timeStamp(), streamed.timeStamp()); + + QCOMPARE(mpLoggingEvents->list().count(), 0); +} + + +void Log4QtTest::LogManager_configureLogLogger() +{ + resetLogging(); + LogManager::logLogger()->removeAppender(mpLoggingEvents); + + LogManager::resetConfiguration(); + Log4Qt::Logger *p_logger = LogManager::logLogger(); + QCOMPARE(p_logger->appenders().count(), 2); + ConsoleAppender *p_appender; + TTCCLayout *p_layout; + + p_appender = qobject_cast(p_logger->appenders().at(0)); + QCOMPARE(p_appender != 0, true); + QVERIFY(p_appender->isActive()); + QVERIFY(!p_appender->isClosed()); + QCOMPARE(p_appender->target(), QString::fromLatin1("STDOUT_TARGET")); + p_layout = qobject_cast(p_appender->layout()); + QVERIFY(p_layout != 0); + + p_appender = qobject_cast(p_logger->appenders().at(1)); + QCOMPARE(p_appender != 0, true); + QVERIFY(p_appender->isActive()); + QVERIFY(!p_appender->isClosed()); + QCOMPARE(p_appender->target(), QString::fromLatin1("STDERR_TARGET")); + p_layout = qobject_cast(p_appender->layout()); + QVERIFY(p_layout != 0); + +} + + +void Log4QtTest::PropertyConfigurator_missing_appender() +{ + LogManager::resetConfiguration(); + resetLogging(); + mDefaultProperties.clear(); + mProperties.clear(); + + mProperties.setProperty("log4j.logger.MissingAppender", + "INHERITED, A"); + QVERIFY(!PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 1); + QCOMPARE(mpLoggingEvents->list().count(), 1); +} + + +void Log4QtTest::PropertyConfigurator_unknown_appender_class() +{ + LogManager::resetConfiguration(); + resetLogging(); + mDefaultProperties.clear(); + mProperties.clear(); + + mProperties.setProperty("log4j.logger.UnknownAppender", + "INHERITED, A"); + mProperties.setProperty("log4j.appender.A", + "org.apache.log4j.UnknownAppender"); + QVERIFY(!PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 1); + QCOMPARE(mpLoggingEvents->list().count(), 2); // Warning from Factory, Error PropertyConfigurator +} + + +void Log4QtTest::PropertyConfigurator_missing_layout() +{ + resetLogging(); + mDefaultProperties.clear(); + mProperties.clear(); + + mProperties.setProperty("log4j.logger.MissingLayout", + "INHERITED, A"); + mProperties.setProperty("log4j.appender.A", + "org.apache.log4j.ConsoleAppender"); + QVERIFY(!PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 1); + QCOMPARE(mpLoggingEvents->list().count(), 1); +} + + +void Log4QtTest::PropertyConfigurator_unknown_layout_class() +{ + resetLogging(); + mDefaultProperties.clear(); + mProperties.clear(); + + mProperties.setProperty("log4j.logger.UnknownLayout", + "INHERITED, A"); + mProperties.setProperty("log4j.appender.A", + "org.apache.log4j.ConsoleAppender"); + mProperties.setProperty("log4j.appender.A.layout", + "org.apache.log4j.UnknownLayout"); + QVERIFY(!PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 1); + QCOMPARE(mpLoggingEvents->list().count(), 2); // Warning from Factory, Error PropertyConfigurator +} + + +void Log4QtTest::PropertyConfigurator_reset() +{ + resetLogging(); + mDefaultProperties.clear(); + mProperties.clear(); + + // - Create a logger with an appender + // - If the reset flag is not set, configure must leave the appender + // - If the reset flag is set to an invalid value, configure must raise an + // error and leave the appender + // - If the reset flag is set, configure must remove the appender + + const QLatin1String key_reset("log4j.reset"); + test_logger()->addAppender(new Log4Qt::ListAppender); + mProperties.setProperty(key_reset, + "false"); + QVERIFY(PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 0); + QCOMPARE(mpLoggingEvents->list().count(), 0); + QCOMPARE(test_logger()->appenders().count(), 1); + + mProperties.setProperty(key_reset, + "No boolean"); + QVERIFY(!PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 1); + QCOMPARE(mpLoggingEvents->list().count(), 1); + QCOMPARE(test_logger()->appenders().count(), 1); + + resetLogging(); + mProperties.setProperty(key_reset, + "true"); + QVERIFY(PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 0); + QCOMPARE(mpLoggingEvents->list().count(), 0); + QCOMPARE(test_logger()->appenders().count(), 0); +} + + +void Log4QtTest::PropertyConfigurator_debug() +{ + resetLogging(); + mDefaultProperties.clear(); + mProperties.clear(); + + // - Set the log logger level to INFO + // - If debug is not set, configure must leave the log logger level + // unaltered + // - If debug is set, but with no valid level string, configure must set + // the log logger level to DEBUG + // - If debug is set to the level TRACE, configure must set the log logger + // level to TRACE + + const QLatin1String key_debug("log4j.Debug"); + Logger *p_logger = LogManager::logLogger(); + p_logger->setLevel(Level::INFO_INT); + + QVERIFY(PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 0); + QCOMPARE(mpLoggingEvents->list().count(), 0); + QCOMPARE(p_logger->level(), Level(Level::INFO_INT)); + + mProperties.setProperty(key_debug, + "true"); + QVERIFY(PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 0); + // QCOMPARE(mpLoggingEvents->list().count(), 1); // Warning from Level::fromString() & several debug messages + QCOMPARE(p_logger->level(), Level(Level::DEBUG_INT)); + + mpLoggingEvents->clearList(); + mProperties.setProperty(key_debug, + "TRACE"); + QVERIFY(PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 0); + // QCOMPARE(mpLoggingEvents->list().count(), 1); // Warning from PropertyConfigurator & several debug/trace messages + QCOMPARE(p_logger->level(), Level(Level::TRACE_INT)); +} + + +void Log4QtTest::PropertyConfigurator_threshold() +{ + resetLogging(); + mDefaultProperties.clear(); + mProperties.clear(); + + // - Set the repository threshold to INFO + // - If the threshold is not set, configure must leave the repository + // threshold unaltered + // - If the threshold is set to an invalid value, configure must raise an + // error and set the threshold to ALL + // - If the threshold is set to WARN, configure must set the repository + // threshold to WARN + + const QLatin1String key_threshold("log4j.threshold"); + LogManager::loggerRepository()->setThreshold(Level::INFO_INT); + + QVERIFY(PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 0); + QCOMPARE(mpLoggingEvents->list().count(), 0); + QCOMPARE(LogManager::loggerRepository()->threshold(), Level(Level::INFO_INT)); + + mProperties.setProperty(key_threshold, + "Not a value"); + QVERIFY(!PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 1); + QCOMPARE(mpLoggingEvents->list().count(), 2); // Warning by Level, Error from OptionConverter + QCOMPARE(LogManager::loggerRepository()->threshold(), Level(Level::ALL_INT)); + + mpLoggingEvents->clearList(); + mProperties.setProperty(key_threshold, + "WARN"); + QVERIFY(PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 0); + QCOMPARE(mpLoggingEvents->list().count(), 0); + QCOMPARE(LogManager::loggerRepository()->threshold(), Level(Level::WARN_INT)); +} + + +void Log4QtTest::PropertyConfigurator_handleQtMessages() +{ + resetLogging(); + mDefaultProperties.clear(); + mProperties.clear(); + + // - Set handle Qt messages to true + // - If handle Qt messages is not set, configure must leave handle Qt + // messages unaltered + // - If handle Qt messages is set to an invalid value, configure must raise + // an error and set handle Qt messages to false + // - If handle Qt messages is true, configure must set handle Qt messages + // to true + + const QLatin1String key_handle_qt_messages("log4j.handleQtMessages"); + LogManager::setHandleQtMessages(true); + + QVERIFY(PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 0); + QCOMPARE(mpLoggingEvents->list().count(), 0); + QCOMPARE(LogManager::handleQtMessages(), true); + + mProperties.setProperty(key_handle_qt_messages, + "No boolean"); + QVERIFY(!PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 1); + QCOMPARE(mpLoggingEvents->list().count(), 1); + QCOMPARE(LogManager::handleQtMessages(), false); + + mpLoggingEvents->clearList(); + mProperties.setProperty(key_handle_qt_messages, + "true"); + QVERIFY(PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 0); + QCOMPARE(mpLoggingEvents->list().count(), 0); + QCOMPARE(LogManager::handleQtMessages(), true); +} + + +void Log4QtTest::PropertyConfigurator_example() +{ + LogManager::resetConfiguration(); + resetLogging(); + mDefaultProperties.clear(); + mProperties.clear(); + + QString file(mTemporaryDirectory.path() + "/RollingFileAppender/log"); + + // Based on the JavaDoc example: + // - A1: JavaDoc uses SyslogAppender, which is not available on all platforms + // - A2: JavaDoc does not set a file, which causes error on activation + // - A2: JavaDoc uses default values for file size and backup index. Use + // different values. + // - A2 Layout: ContextPrinting uses default enabled. Use disabled instead. + // - root: JavaDoc uses default level DEBUG. Use INFO instead. + // - SECURITY: JavaDoc uses INHERIT. Use INHERITED instead + // - log4j.logger.class.of.the.day: JavaDoc uses INHERIT. Use INHERITED + // instead + + // Appender A1: ConsoleAppender with PatternLayout + mProperties.setProperty("log4j.appender.A1", + "org.apache.log4j.ConsoleAppender"); + mProperties.setProperty("log4j.appender.A1.Target", "System.Out"); + mProperties.setProperty("log4j.appender.A1.layout", + "org.apache.log4j.PatternLayout"); + mProperties.setProperty("log4j.appender.A1.layout.ConversionPattern", + "%-4r %-5p %c{2} %M.%L %x - %m\n"); + // Appender A2: RollingFileAppender with TTCCLayout + mProperties.setProperty("log4j.appender.A2", + "org.apache.log4j.RollingFileAppender"); + mProperties.setProperty("log4j.appender.A2.File", file); + mProperties.setProperty("log4j.appender.A2.MaxFileSize", "13MB"); + mProperties.setProperty("log4j.appender.A2.MaxBackupIndex", "7"); + mProperties.setProperty("log4j.appender.A2.layout", + "org.apache.log4j.TTCCLayout"); + mProperties.setProperty("log4j.appender.A2.layout.ContextPrinting", + "disabled"); + mProperties.setProperty("log4j.appender.A2.layout.DateFormat", "ISO8601"); + // Root Logger: Uses A2 + mProperties.setProperty("log4j.rootLogger", "INFO, A2"); + // Logger SECURITY: Uses A1 + mProperties.setProperty("log4j.logger.SECURITY", "INHERITED, A1"); + mProperties.setProperty("log4j.additivity.SECURITY", "false"); + // Logger SECURITY.access: + mProperties.setProperty("log4j.logger.SECURITY.access", "WARN"); + // Logger class.of.the.day: + mProperties.setProperty("log4j.logger.class.of.the.day", "INHERITED"); + + // No warnings, no errors expected + QVERIFY(PropertyConfigurator::configure(mProperties)); + QCOMPARE(ConfiguratorHelper::configureError().count(), 0); + QCOMPARE(mpLoggingEvents->list().count(), 0); + + // Root logger + Logger *p_logger; + p_logger = LogManager::rootLogger(); + QCOMPARE(p_logger->level(), Level(Level::INFO_INT)); + QCOMPARE(p_logger->appenders().count(), 1); + Log4Qt::RollingFileAppender *p_a2 = + qobject_cast(p_logger->appenders().at(0)); + QVERIFY(p_a2 != 0); + QCOMPARE(p_a2->file(), file); + QCOMPARE(p_a2->maximumFileSize(), Q_INT64_C(13*1024*1024)); + QCOMPARE(p_a2->maxBackupIndex(), 7); + Log4Qt::TTCCLayout *p_a2layout = + qobject_cast(p_a2->layout()); + QVERIFY(p_a2layout != 0); + QCOMPARE(p_a2layout->contextPrinting(), false); + QCOMPARE(p_a2layout->dateFormat(), QString::fromLatin1("ISO8601")); + + // Logger SECURITY + QVERIFY(LogManager::exists("SECURITY")); + p_logger = LogManager::logger("SECURITY"); + QCOMPARE(p_logger->level(), Level(Level::NULL_INT)); + QCOMPARE(p_logger->appenders().count(), 1); + Log4Qt::ConsoleAppender *p_a1 = + qobject_cast(p_logger->appenders().at(0)); + QVERIFY(p_a1 != 0); + QCOMPARE(p_a1->target(), QString::fromLatin1("STDOUT_TARGET")); + Log4Qt::PatternLayout *p_a1layout = + qobject_cast(p_a1->layout()); + QVERIFY(p_a1layout != 0); + QCOMPARE(p_a1layout->conversionPattern(), QString::fromLatin1("%-4r %-5p %c{2} %M.%L %x - %m\n")); + + // Logger SECURITY::access + QVERIFY(LogManager::exists("SECURITY::access")); + p_logger = LogManager::logger("SECURITY::access"); + QCOMPARE(p_logger->level(), Level(Level::WARN_INT)); + + // Logger class::of::the::day + QVERIFY(LogManager::exists("class::of::the::day")); +} + + +void Log4QtTest::RollingFileAppender() +{ + resetLogging(); + + QString dir(mTemporaryDirectory.path() + "/RollingFileAppender"); + QString file("/log"); + + // Using a RollingFileAppender with 2 files history and 3 messages per file + Log4Qt::RollingFileAppender appender; + appender.setName("RollingFileAppender"); + appender.setFile(dir + file); + appender.setLayout(new SimpleLayout()); + appender.setMaxBackupIndex(2); + appender.setMaximumFileSize(40); + appender.activateOptions(); + + // Output 9 messages + int i; + for (i = 0; i < 10; i++) + appender.doAppend(LoggingEvent(test_logger(), Level::DEBUG_INT, + QString("Message %1").arg(i))); + + // No warnings or errors expected + QCOMPARE(mpLoggingEvents->list().count(), 0); + + // Validate diretcory + QStringList expected; + QString result; + expected << "log" << "log.1" << "log.2"; + if (!validateDirContents(dir, expected, result)) + QFAIL(qPrintable(result)); + + // Validate files + expected.clear(); + expected << "DEBUG - Message 9"; + if (!validateFileContents(dir + file, expected, result)) + QFAIL(qPrintable(result)); + expected.clear(); + expected << "DEBUG - Message 6" << "DEBUG - Message 7" + << "DEBUG - Message 8"; + if (!validateFileContents(dir + file + ".1", expected, result)) + QFAIL(qPrintable(result)); + expected.clear(); + expected << "DEBUG - Message 3" << "DEBUG - Message 4" + << "DEBUG - Message 5"; + if (!validateFileContents(dir + file + ".2", expected, result)) + QFAIL(qPrintable(result)); + + QCOMPARE(mpLoggingEvents->list().count(), 0); +} + + +QString Log4QtTest::dailyRollingFileAppenderSuffix(const QDateTime &rDateTime) +{ + QString result("."); + result += QString::number(rDateTime.date().year()).rightJustified(4, '0'); + result += '-'; + result += QString::number(rDateTime.date().month()).rightJustified(2, '0'); + result += '-'; + result += QString::number(rDateTime.date().day()).rightJustified(2, '0'); + result += '-'; + result += QString::number(rDateTime.time().hour()).rightJustified(2, '0'); + result += '-'; + result += QString::number(rDateTime.time().minute()).rightJustified(2, '0'); + return result; +} + + +QString Log4QtTest::enumValueToKey(QObject *pObject, + const char* pEnumeration, + int value) +{ + Q_ASSERT(pObject); + Q_ASSERT(!QString(pEnumeration).isEmpty()); + + int i = pObject->metaObject()->indexOfEnumerator(pEnumeration); + Q_ASSERT(i >= 0); + QMetaEnum enumerator = pObject->metaObject()->enumerator(i); + Q_ASSERT(enumerator.isValid()); + QString result = enumerator.valueToKey(value); + Q_ASSERT(!result.isNull()); + return result; +} + + +void Log4QtTest::resetLogging() +{ + Log4Qt::Logger *p_logger; + + // Log4Qt logger + p_logger = LogManager::logLogger(); + p_logger->setAdditivity(false); + p_logger->setLevel(Level::WARN_INT); + p_logger->removeAllAppenders(); + + // Log4QtTest appender + p_logger->addAppender(mpLoggingEvents); + mpLoggingEvents->clearList(); + mpLoggingEvents->clearFilters(); + mpLoggingEvents->setThreshold(Level::WARN_INT); + + // Test logger + p_logger = test_logger(); + p_logger->setAdditivity(true); + p_logger->setLevel(Level::NULL_INT); +} + + +bool Log4QtTest::compareStringLists(const QStringList &rActual, + const QStringList &rExpected, + const QString &rEntry, + const QString &rEntries, + QString &rResult) +{ + QString tab(" "); + QString eol("\n"); + + // Generate content string + QString content; + int i; + content += tab + "Actual: " + rEntries + ": " + + QString::number(rActual.count()) + eol; + for (i = 0; i < rActual.count(); i++) + content += tab + tab + '\'' + rActual.at(i) + '\'' + eol; + content += tab + "Expected: " + rEntries + ": " + + QString::number(rExpected.count()) + eol; + for (i = 0; i < rExpected.count(); i++) + content += tab + tab + '\'' + rExpected.at(i) + '\'' + eol; + + // Check count + if (rActual.count() != rExpected.count()) + { + rResult = tab + "Compared " + rEntry + " counts are not the same" + eol; + rResult += content; + return false; + } + + // Check entries + for (i = 0; i < rActual.count(); i++) + { + if (rActual.at(i) != rExpected.at(i)) + { + rResult = tab + rEntry + " " + QString::number(i + 1) + + " is not the same" + eol; + rResult += content; + return false; + } + } + + rResult.clear(); + return true; +} + + +bool Log4QtTest::deleteDirectoryTree(const QString &rName) +{ + QFileInfo file_info(rName); + if (!file_info.exists()) + return true; + if (file_info.isDir()) + { + QDir d(rName); + QStringList members = d.entryList(QDir::Dirs | QDir::Files + | QDir::NoDotAndDotDot | QDir::NoSymLinks + | QDir::Hidden, QDir::Name | QDir::DirsFirst); + QString member; + Q_FOREACH(member, members) + if (!deleteDirectoryTree(rName + '/' + member)) + return false; + if (d.rmdir(rName)) + return true; + qDebug() << "Unable to remove directory: " << rName; + return false; + } + else + { + QFile f(rName); + if (f.remove()) + return true; + qDebug() << "Unable to remove file: " << rName << "(" + << f.errorString() << ")"; + return false; + } +} + + +bool Log4QtTest::validateDirContents(const QString &rName, + const QStringList &rExpected, + QString &rResult) +{ + QDir dir(rName); + if (!dir.exists()) + { + rResult = QString("The dir '%1' does not exist").arg(rName); + return false; + } + + QStringList actual = dir.entryList(QDir::Dirs | QDir::Files + | QDir::NoDotAndDotDot | QDir::NoSymLinks | QDir::Hidden, + QDir::Name | QDir::DirsFirst); + if (!compareStringLists(actual, rExpected, "Entry", "Entries", rResult)) + { + QString error = + "The directory contents validation failed.\n '%1'\n%2"; + rResult = error.arg(rName, rResult); + return false; + } + + return true; +} + + +bool Log4QtTest::validateFileContents(const QString &rName, + const QStringList &rExpected, + QString &rResult) +{ + QFile file(rName); + if (!file.exists()) + { + rResult = QString("The expected file '%1' does not exist (%2)").arg(rName).arg(file.errorString()); + return false; + } + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) + { + rResult = QString("The expected file '%1' cannot be opened (%2)").arg(rName).arg(file.errorString()); + return false; + } + + QStringList actual; + QTextStream textstream(&file); + QString line = textstream.readLine(); + while (!line.isNull()) + { + actual << line; + line = textstream.readLine(); + } + if (!compareStringLists(actual, rExpected, "Line", "Lines", rResult)) + { + QString error = "The file contents validation failed.\n '%1'\n%2"; + rResult = error.arg(rName, rResult); + return false; + } + + return true; +} + + + +/****************************************************************************** + * Implementation: Operators, Helper + ******************************************************************************/ + + diff --git a/src/log4qt/tests/log4qttest.h b/src/log4qt/tests/log4qttest.h new file mode 100644 index 0000000..dcddf3a --- /dev/null +++ b/src/log4qt/tests/log4qttest.h @@ -0,0 +1,177 @@ +/****************************************************************************** + * + * package: Log4Qt + * file: loggingtest.h + * created: September 2007 + * author: Martin Heinrich + * + * + * Copyright 2007 Martin Heinrich + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +#ifndef LOG4QT_LOG4QTTEST_H +#define LOG4QT_LOG4QTTEST_H + + +/****************************************************************************** + * Dependencies + ******************************************************************************/ + +#include +#include + +#include "log4qt/helpers/properties.h" +#include "log4qt/logger.h" +#include "log4qt/varia/listappender.h" + + +/****************************************************************************** + * Declarations + ******************************************************************************/ + +/*! + * \brief The class Log4QtTest provides a unit test for the package Log4Qt. + * + * The class Log4QtTest implements a unit test based on th Qt testing framework. + */ +class Log4QtTest : public QObject +{ + Q_OBJECT + +public: + Log4QtTest(); + virtual ~Log4QtTest(); +private: + Log4QtTest(const Log4QtTest &rOther); // Not implemented + Log4QtTest &operator=(const Log4QtTest &rOther); // Not implemented + +private slots: + void initTestCase(); + void cleanupTestCase(); + + // log4qt/helpers + void DateTime_compability_data(); + void DateTime_compability(); + void DateTime_week_data(); + void DateTime_week(); + void DateTime_milliseconds_data(); + void DateTime_milliseconds(); + void PatternFormatter_data(); + void PatternFormatter(); + void Properties_default_data(); + void Properties_default(); + void Properties_names(); + void Properties_load_device_data(); + void Properties_load_device(); + void Properties_load_settings(); + + // OptionConverter requires Properties + void OptionConverter_boolean_data(); + void OptionConverter_boolean(); + void OptionConverter_filesize_data(); + void OptionConverter_filesize(); + void OptionConverter_int_data(); + void OptionConverter_int(); + void OptionConverter_level_data(); + void OptionConverter_level(); + void OptionConverter_substitution_data(); + void OptionConverter_substitution(); + void OptionConverter_target_data(); + void OptionConverter_target(); + + // Factory requires OptionConverter + void Factory_createAppender_data(); + void Factory_createAppender(); + void Factory_createFilter_data(); + void Factory_createFilter(); + void Factory_createLayout_data(); + void Factory_createLayout(); + void Factory_setObjectProperty_data(); + void Factory_setObjectProperty(); + + // log4qt/varia + void ListAppender(); + void DenyAllFilter(); + void LevelMatchFilter_data(); + void LevelMatchFilter(); + void LevelRangeFilter_data(); + void LevelRangeFilter(); + void StringMatchFilter_data(); + void StringMatchFilter(); + + // log4qt + void AppenderSkeleton_threshold(); + void AppenderSkeleton_filter_data(); + void AppenderSkeleton_filter(); + void BasicConfigurator(); + void FileAppender(); + void DailyRollingFileAppender(); + void LoggingEvent_stream_data(); + void LoggingEvent_stream(); + void LogManager_configureLogLogger(); + void PropertyConfigurator_missing_appender(); + void PropertyConfigurator_unknown_appender_class(); + void PropertyConfigurator_missing_layout(); + void PropertyConfigurator_unknown_layout_class(); + void PropertyConfigurator_reset(); + void PropertyConfigurator_debug(); + void PropertyConfigurator_threshold(); + void PropertyConfigurator_handleQtMessages(); + void PropertyConfigurator_example(); + void RollingFileAppender(); + +private: + QString dailyRollingFileAppenderSuffix(const QDateTime &rDateTime); + QString enumValueToKey(QObject *pObject, + const char* pEnumeration, + int value); + void resetLogging(); + static bool compareStringLists(const QStringList &rActual, + const QStringList &rExpected, + const QString &rEntry, + const QString &rEntries, + QString &rResult); + static bool deleteDirectoryTree(const QString &rName); + static bool validateDirContents(const QString &rName, + const QStringList &rExpected, + QString &rResult); + static bool validateFileContents(const QString &rName, + const QStringList &rExpected, + QString &rResult); + +private: + bool mSkipLongTests; + QDir mTemporaryDirectory; + Log4Qt::ListAppender *mpLoggingEvents; + Log4Qt::Properties mDefaultProperties; + Log4Qt::Properties mProperties; +}; + + +/****************************************************************************** + * Operators, Helper + ******************************************************************************/ + + +/****************************************************************************** + * Inline + ******************************************************************************/ + + +// Q_DECLARE_TYPEINFO(Log4Qt::Log4QtTest, Q_COMPLEX_TYPE); // use default + + +#endif // LOG4QT_LOG4QTTEST_H diff --git a/src/log4qt/tests/log4qttest.pro b/src/log4qt/tests/log4qttest.pro new file mode 100644 index 0000000..16fe8a6 --- /dev/null +++ b/src/log4qt/tests/log4qttest.pro @@ -0,0 +1,42 @@ +# ******************************************************************************* +# +# package: Log4Qt +# file: log4qttest.pro +# created: September 2007 +# author: Martin Heinrich +# +# +# Copyright 2007 Martin Heinrich +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ******************************************************************************* + +TEMPLATE = app + +isEqual(QT_MAJOR_VERSION, 5) { + QT += testlib +} else { # if not Qt5 + CONFIG += qtestlib +} + +DEFINES -= \ + QT_NO_CAST_FROM_ASCII \ + QT_NO_CAST_TO_ASCII + +include(../src/log4qt/log4qt.pri) + +HEADERS += log4qttest.h +SOURCES += log4qttest.cpp + + diff --git a/src/log4qt/ukui-log4qt.cpp b/src/log4qt/ukui-log4qt.cpp new file mode 100644 index 0000000..a87be26 --- /dev/null +++ b/src/log4qt/ukui-log4qt.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#include "ukui-logconfigurator.h" + +// 初始化ukui-log4qt库,传入application名称 +int initUkuiLog4qt(QString strAppName) +{ + if (strAppName.isEmpty()){ + return -1; + } + // 检查纠正名称格式 小写+'-'+数字 + strAppName = strAppName.toLower(); + // 非数字和小写字母以'-'代替 + strAppName.replace(QRegExp("[^a-z0-9]+"),"-"); + // 多个'-'以一个'-'代替 + strAppName.replace(QRegExp("[-]+"),"-"); + // 去掉头部的非字母串和尾部的'-'’ + strAppName.replace(QRegExp("(^[^a-z]+|-$)"),""); + // 初始化log4qt配置 + return UkuiLog4qtConfig::instance()->init(strAppName); +} diff --git a/src/log4qt/ukui-log4qt.h b/src/log4qt/ukui-log4qt.h new file mode 100644 index 0000000..5744586 --- /dev/null +++ b/src/log4qt/ukui-log4qt.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 + +//输出debug级别日志 +#define KyDebug QMessageLogger(__FILE__, __LINE__, __FUNCTION__).debug + +//输出info级别日志 +#define KyInfo QMessageLogger(__FILE__, __LINE__, __FUNCTION__).info + +//输出warning级别日志 +#define KyWarning QMessageLogger(__FILE__, __LINE__, __FUNCTION__).warning + +//输出critical级别日志 +#define KyCritical QMessageLogger(__FILE__, __LINE__, __FUNCTION__).critical + +//输出fatal级别日志 +#define KyFatal QMessageLogger(__FILE__, __LINE__, __FUNCTION__).fatal + +// 初始化ukui-log4qt库,传入application名称 +int initUkuiLog4qt(QString strAppName); + +#endif // __UKUILOG4QT_H__ diff --git a/src/log4qt/ukui-log4qt.pro b/src/log4qt/ukui-log4qt.pro new file mode 100644 index 0000000..0fdcc49 --- /dev/null +++ b/src/log4qt/ukui-log4qt.pro @@ -0,0 +1,52 @@ +QT -= gui + +TEMPLATE = lib +DEFINES += LIBUKUILOG4QT_LIBRARY UKUILOG4QT_EXTRA_ENABLE + +CONFIG += link_pkgconfig \ + c++11 + +PKGCONFIG += gsettings-qt + +# The following define makes your compiler emit warnings if you use +# any Qt feature that has been marked deprecated (the exact warnings +# depend on your compiler). Please consult the documentation of the +# deprecated API in order to know how to port your code away from it. +DEFINES += QT_DEPRECATED_WARNINGS + +# You can also make your code fail to compile if it uses deprecated APIs. +# In order to do so, uncomment the following line. +# You can also select to disable deprecated APIs only up to a certain version of Qt. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +#log4qt +include($$PWD/log4qt/log4qt.pri) + +SOURCES += \ + ukui-logconfigurator.cpp \ + ukui-logrolling.cpp \ + ukui-log4qt.cpp + +HEADERS += \ + ukui-logmacros.h \ + ukui-logconfigurator.h \ + ukui-logrolling.h \ + ukui-log4qt.h + +# Default rules for deployment. +unix { + target.path = /usr/lib +} +!isEmpty(target.path): INSTALLS += target + +schemes.files += org.ukui.log4qt.gschema.xml +schemes.path = /usr/share/glib-2.0/schemas/ + +headers_main.path = /usr/include +headers_main.files += ukui-log4qt.h + +INSTALLS += schemes \ + headers_main + +DISTFILES += \ + log4qt.conf diff --git a/src/log4qt/ukui-logconfigurator.cpp b/src/log4qt/ukui-logconfigurator.cpp new file mode 100644 index 0000000..a7a0f5b --- /dev/null +++ b/src/log4qt/ukui-logconfigurator.cpp @@ -0,0 +1,385 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include + + +LOG4QT_GLOBAL_STATIC(QMutex, single_config) +UkuiLog4qtConfig *UkuiLog4qtConfig::mInstance = nullptr; +pid_t g_MainProcPid = -1; + +UkuiLog4qtConfig::UkuiLog4qtConfig(QObject *parent) : + QObject(parent), + m_threadCheckFile(nullptr), + m_isInited(false), + m_gsLog4qtGlobal(nullptr), + m_gsLog4qtSpecial(nullptr) +{ + m_log4qtProperties.clear(); + m_uMaxFileCount = 0; + m_uMaxFileSize = 0; + m_timeCheckFile = 60; + g_MainProcPid = getpid(); +} + +UkuiLog4qtConfig::~UkuiLog4qtConfig() +{ + if (m_gsLog4qtGlobal) { + delete m_gsLog4qtGlobal; + m_gsLog4qtGlobal = nullptr; + } + if (m_gsLog4qtSpecial) { + delete m_gsLog4qtSpecial; + m_gsLog4qtSpecial = nullptr; + } +} + +UkuiLog4qtConfig *UkuiLog4qtConfig::instance() +{ + if (!mInstance) + { + QMutexLocker locker(single_config()); + if (!mInstance) + { + mInstance = new UkuiLog4qtConfig; + } + } + return mInstance; +} + +int UkuiLog4qtConfig::init(QString strAppName) +{ + QMutexLocker locker(single_config()); + if (m_isInited) { + return true; + } + //全局设置 + m_log4qtProperties.clear(); + //是否重置所有配置,恢复全局设置默认值 + m_log4qtProperties.setProperty(UKUILOG4QT_RESET, "true"); + //设置日志sdk内部记录器级别 + m_log4qtProperties.setProperty(UKUILOG4QT_DEBUG, "INFO"); + //日志记录器仓库的阈值 + const QLatin1String key_threshold("log4j.threshold"); + m_log4qtProperties.setProperty(key_threshold, "NULL"); + //设置是否监听QDebug输出的字符串 + m_log4qtProperties.setProperty(UKUILOG4QT_HANDLEQT, "true"); + + //设置根Logger的输出log等级和输出目的地 + m_log4qtProperties.setProperty(UKUILOG4QT_ROOTLOGGER, "DEBUG,daily"); + + //设置终端打印记录器 + //记录器类别 --控制台输出 + const QLatin1String key_appender_console("log4j.appender.console"); + m_log4qtProperties.setProperty(key_appender_console, "org.apache.log4j.ConsoleAppender"); + //记录器输出目标 + const QLatin1String key_appender_console_target("log4j.appender.console.target"); + m_log4qtProperties.setProperty(key_appender_console_target, "STDOUT_TARGET"); + //记录器输出布局 + const QLatin1String key_appender_console_layout("log4j.appender.console.layout"); + m_log4qtProperties.setProperty(key_appender_console_layout, "org.apache.log4j.TTCCLayout"); + //记录器布局日期格式 + const QLatin1String key_appender_console_layout_dateformat("log4j.appender.console.layout.dateFormat"); + m_log4qtProperties.setProperty(key_appender_console_layout_dateformat, "yyy-MM-dd hh:mm:ss.zzz"); + //记录器布局包含上下文 + const QLatin1String key_appender_console_layout_contextprinting("log4j.appender.console.layout.contextPrinting"); + m_log4qtProperties.setProperty(key_appender_console_layout_contextprinting, "false"); + //记录器布局包含当前类目 + const QLatin1String key_appender_console_layout_categoryprefixing("log4j.appender.console.layout.categoryPrefixing"); + m_log4qtProperties.setProperty(key_appender_console_layout_categoryprefixing, "false"); + + + //设置定期文件滚动打印记录器 + //记录器类别 + const QLatin1String key_appender_daily("log4j.appender.daily"); + m_log4qtProperties.setProperty(key_appender_daily, "org.apache.log4j.DailyRollingFileAppender"); + //记录器输出文件路径 + const QLatin1String key_appender_daily_file("log4j.appender.daily.file"); + QStringList homePath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation); + if (homePath.size() <= 0) { + return -1; + } + QString strLogFilePath = homePath[0]+UKUILOG4QT_ROOTPATH+strAppName+".log"; + m_log4qtProperties.setProperty(key_appender_daily_file, strLogFilePath); + //记录器追加文件内容 + const QLatin1String key_appender_daily_appendfile("log4j.appender.daily.appendFile"); + m_log4qtProperties.setProperty(key_appender_daily_appendfile, "true"); + //记录器是否直接写入文件 + const QLatin1String key_appender_daily_immediateflush("log4j.appender.daily.immediateFlush"); + m_log4qtProperties.setProperty(key_appender_daily_immediateflush, "true"); + //记录器文件名日期后缀 按天 + m_log4qtProperties.setProperty(UKUILOG4QT_DAILY_DATEPATTERN, ".yyyy-MM-dd"); + //记录器布局分隔符 + const QLatin1String key_appender_daily_layout("log4j.appender.daily.layout"); + m_log4qtProperties.setProperty(key_appender_daily_layout, "org.apache.log4j.PatternLayout"); + //记录器日志输出格式 + m_log4qtProperties.setProperty(UKUILOG4QT_DAILY_CONVERSIONPATTERN, "%d{yyyy-MM-dd HH:mm:ss,zzz}(%-4r)[%t]|%-5p| - %m%n"); + + // 从gsettings获取属性值 + initSettings(strAppName, m_log4qtProperties); + + // 根据配置属性初始化rootlogger + if (!Log4Qt::PropertyConfigurator::configure(m_log4qtProperties)) { + return -2; + } + // 注册程序销毁回调函数 + atexit(shutdown); + // 启动检查日志文件数量和大小线程 + m_threadCheckFile = new UkuiLog4qtRolling(strLogFilePath, m_uMaxFileCount, m_uMaxFileSize, m_timeCheckFile); + m_threadCheckFile->start(); + // 更新已初始化状态 + m_isInited = true; + return 0; +} + +void UkuiLog4qtConfig::shutdown() +{ + QMutexLocker locker(single_config()); + if (mInstance) { + if (mInstance->m_threadCheckFile) { + mInstance->m_threadCheckFile->stop(); + mInstance->m_threadCheckFile->wait(); + delete mInstance->m_threadCheckFile; + mInstance->m_threadCheckFile = nullptr; + } + delete mInstance; + mInstance = nullptr; + } +} + +void UkuiLog4qtConfig::initSettings(QString strAppName, Log4Qt::Properties &properties) +{ + //读取全局gsettings配置 + const QByteArray gid(UKUILOG4QT_SETTINGS); + if(QGSettings::isSchemaInstalled(gid)) + { + m_gsLog4qtGlobal = new QGSettings(gid); + connect(m_gsLog4qtGlobal,&QGSettings::changed,[=](QString key) + { + QMutexLocker locker(single_config()); + QVariant gValue; + bool bLogConfigChange = false; + bool bLogRollingChange = false; + if (UKUILOG4QT_SETTINGS_RESET == key) { + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_RESET); + if (gValue.isValid()) { + m_log4qtProperties.setProperty(UKUILOG4QT_RESET, gValue.toString()); + bLogConfigChange = true; + } + } else if (UKUILOG4QT_SETTINGS_DEBUG == key) { + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_DEBUG); + if (gValue.isValid()) { + m_log4qtProperties.setProperty(UKUILOG4QT_DEBUG, gValue.toString()); + bLogConfigChange = true; + } + } else if (UKUILOG4QT_SETTINGS_HANDLEQT == key) { + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_HANDLEQT); + if (gValue.isValid()) { + m_log4qtProperties.setProperty(UKUILOG4QT_HANDLEQT, gValue.toString()); + bLogConfigChange = true; + } + } else if (UKUILOG4QT_SETTINGS_ROOTLOGGER == key) { + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_ROOTLOGGER); + if (gValue.isValid()) { + m_log4qtProperties.setProperty(UKUILOG4QT_ROOTLOGGER, gValue.toString()); + bLogConfigChange = true; + } + } else if (UKUILOG4QT_SETTINGS_DAILY_DATEPATTERN == key) { + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_DAILY_DATEPATTERN); + if (gValue.isValid()) { + m_log4qtProperties.setProperty(UKUILOG4QT_DAILY_DATEPATTERN, gValue.toString()); + bLogConfigChange = true; + } + } else if (UKUILOG4QT_SETTINGS_DAILY_CONVERSIONPATTERN == key) { + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_DAILY_CONVERSIONPATTERN); + if (gValue.isValid()) { + m_log4qtProperties.setProperty(UKUILOG4QT_DAILY_CONVERSIONPATTERN, gValue.toString()); + bLogConfigChange = true; + } + } + if (bLogConfigChange) { + Log4Qt::PropertyConfigurator::configure(m_log4qtProperties); + } + if (UKUILOG4QT_SETTINGS_ROLLINGCHECK_DELAYTIME == key) { + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_ROLLINGCHECK_DELAYTIME); + if (gValue.isValid()) { + m_timeCheckFile = gValue.toULongLong(); + bLogRollingChange = true; + } + } else if (UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILECOUNT == key) { + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILECOUNT); + if (gValue.isValid()) { + m_uMaxFileCount = gValue.toUInt(); + bLogRollingChange = true; + } + } else if (UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILESIZE == key) { + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILESIZE); + if (gValue.isValid()) { + m_uMaxFileSize = gValue.toULongLong(); + bLogRollingChange = true; + } + } + if (bLogRollingChange && m_threadCheckFile) { + m_threadCheckFile->setFileCheckLimit(m_uMaxFileCount, m_uMaxFileSize, m_timeCheckFile); + } + }); + } + if (m_gsLog4qtGlobal) { + QVariant gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_RESET); + if (gValue.isValid()) { + properties.setProperty(UKUILOG4QT_RESET, gValue.toString()); + } + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_DEBUG); + if (gValue.isValid()) { + properties.setProperty(UKUILOG4QT_DEBUG, gValue.toString()); + } + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_HANDLEQT); + if (gValue.isValid()) { + properties.setProperty(UKUILOG4QT_HANDLEQT, gValue.toString()); + } + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_ROOTLOGGER); + if (gValue.isValid()) { + properties.setProperty(UKUILOG4QT_ROOTLOGGER, gValue.toString()); + } + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_DAILY_DATEPATTERN); + if (gValue.isValid()) { + properties.setProperty(UKUILOG4QT_DAILY_DATEPATTERN, gValue.toString()); + } + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_DAILY_CONVERSIONPATTERN); + if (gValue.isValid()) { + properties.setProperty(UKUILOG4QT_DAILY_CONVERSIONPATTERN, gValue.toString()); + } + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_ROLLINGCHECK_DELAYTIME); + if (gValue.isValid()) { + m_timeCheckFile = gValue.toULongLong(); + } + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILECOUNT); + if (gValue.isValid()) { + m_uMaxFileCount = gValue.toUInt(); + } + gValue = m_gsLog4qtGlobal->get(UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILESIZE); + if (gValue.isValid()) { + m_uMaxFileSize = gValue.toULongLong(); + } + } + //读取特例gsettings配置 + QString strSpecialSetting = QString("%1-%2").arg(UKUILOG4QT_SETTINGS).arg(strAppName); + const QByteArray sid = strSpecialSetting.toUtf8(); + if(QGSettings::isSchemaInstalled(sid)) + { + m_gsLog4qtSpecial = new QGSettings(sid); + connect(m_gsLog4qtSpecial,&QGSettings::changed,[=](QString key) + { + QMutexLocker locker(single_config()); + QVariant gValue; + bool bLogConfigChange = false; + bool bLogRollingChange = false; + if (UKUILOG4QT_SETTINGS_HANDLEQT == key) { + gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_HANDLEQT); + if (gValue.isValid()) { + m_log4qtProperties.setProperty(UKUILOG4QT_HANDLEQT, gValue.toString()); + bLogConfigChange = true; + } + }else if (UKUILOG4QT_SETTINGS_ROOTLOGGER == key) { + gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_ROOTLOGGER); + if (gValue.isValid()) { + m_log4qtProperties.setProperty(UKUILOG4QT_ROOTLOGGER, gValue.toString()); + bLogConfigChange = true; + } + } else if (UKUILOG4QT_SETTINGS_DAILY_DATEPATTERN == key) { + gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_DAILY_DATEPATTERN); + if (gValue.isValid()) { + m_log4qtProperties.setProperty(UKUILOG4QT_DAILY_DATEPATTERN, gValue.toString()); + bLogConfigChange = true; + } + } else if (UKUILOG4QT_SETTINGS_DAILY_CONVERSIONPATTERN == key) { + gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_DAILY_CONVERSIONPATTERN); + if (gValue.isValid()) { + m_log4qtProperties.setProperty(UKUILOG4QT_DAILY_CONVERSIONPATTERN, gValue.toString()); + bLogConfigChange = true; + } + } + if (bLogConfigChange) { + Log4Qt::PropertyConfigurator::configure(m_log4qtProperties); + } + if (UKUILOG4QT_SETTINGS_ROLLINGCHECK_DELAYTIME == key) { + gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_ROLLINGCHECK_DELAYTIME); + if (gValue.isValid()) { + m_timeCheckFile = gValue.toULongLong(); + bLogRollingChange = true; + } + } else if (UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILECOUNT == key) { + gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILECOUNT); + if (gValue.isValid()) { + m_uMaxFileCount = gValue.toUInt(); + bLogRollingChange = true; + } + } else if (UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILESIZE == key) { + gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILESIZE); + if (gValue.isValid()) { + m_uMaxFileSize = gValue.toULongLong(); + bLogRollingChange = true; + } + } + if (bLogRollingChange && m_threadCheckFile) { + m_threadCheckFile->setFileCheckLimit(m_uMaxFileCount, m_uMaxFileSize, m_timeCheckFile); + } + }); + } + if (m_gsLog4qtSpecial) { + QVariant gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_ROOTLOGGER); + if (gValue.isValid()) { + properties.setProperty(UKUILOG4QT_ROOTLOGGER, gValue.toString()); + } + gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_HANDLEQT); + if (gValue.isValid()) { + properties.setProperty(UKUILOG4QT_HANDLEQT, gValue.toString()); + } + gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_DAILY_DATEPATTERN); + if (gValue.isValid()) { + properties.setProperty(UKUILOG4QT_DAILY_DATEPATTERN, gValue.toString()); + } + gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_DAILY_CONVERSIONPATTERN); + if (gValue.isValid()) { + properties.setProperty(UKUILOG4QT_DAILY_CONVERSIONPATTERN, gValue.toString()); + } + gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_ROLLINGCHECK_DELAYTIME); + if (gValue.isValid()) { + m_timeCheckFile = gValue.toULongLong(); + } + gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILECOUNT); + if (gValue.isValid()) { + m_uMaxFileCount = gValue.toUInt(); + } + gValue = m_gsLog4qtSpecial->get(UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILESIZE); + if (gValue.isValid()) { + m_uMaxFileSize = gValue.toULongLong(); + } + } +} \ No newline at end of file diff --git a/src/log4qt/ukui-logconfigurator.h b/src/log4qt/ukui-logconfigurator.h new file mode 100644 index 0000000..031fa30 --- /dev/null +++ b/src/log4qt/ukui-logconfigurator.h @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include "log4qt/helpers/properties.h" +#include "ukui-logrolling.h" + +// 日志sdk对外衔接类 +class LIBUKUILOG4QT_EXPORT UkuiLog4qtConfig : public QObject +{ + Q_OBJECT + +private: + virtual ~UkuiLog4qtConfig(); + UkuiLog4qtConfig(QObject *parent = nullptr); + +public: + // 返回日志配置器实例 + static UkuiLog4qtConfig *instance(); + // 初始化日志sdk属性 + int init(QString strAppName); + // 释放自身资源 + static void shutdown(); + +private: + // 初始化gsettings并监听 + void initSettings(QString strAppName, Log4Qt::Properties &properties); + +public: + // 检查日志文件线程对象 + UkuiLog4qtRolling *m_threadCheckFile; + +private: + // 自身实例 + static UkuiLog4qtConfig *mInstance; + // 是否已初始化 + bool m_isInited; + // 全局gsettings + QGSettings *m_gsLog4qtGlobal; + // 当前程序特例gsettings + QGSettings *m_gsLog4qtSpecial; + // 当前属性列表 + Log4Qt::Properties m_log4qtProperties; + // 最多允许文件数 + unsigned m_uMaxFileCount; + // 最大允许文件容量 + quint64 m_uMaxFileSize; + // 文件检查时间间隔 s + quint64 m_timeCheckFile; +}; + +#endif // __UKUI_LOGCONFIGURATOR_H__ \ No newline at end of file diff --git a/src/log4qt/ukui-logmacros.h b/src/log4qt/ukui-logmacros.h new file mode 100644 index 0000000..b637ac9 --- /dev/null +++ b/src/log4qt/ukui-logmacros.h @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#if defined(LIBUKUILOG4QT_LIBRARY) +# define LIBUKUILOG4QT_EXPORT Q_DECL_EXPORT +#else +# define LIBUKUILOG4QT_EXPORT Q_DECL_IMPORT +#endif + +// 日志文件相对home目录路径 +#define UKUILOG4QT_ROOTPATH "/.log/" + +// gsettings相关相关属性 +#define UKUILOG4QT_SETTINGS "org.ukui.ukui-log4qt" +#define UKUILOG4QT_SETTINGS_RESET "log4jReset" +#define UKUILOG4QT_SETTINGS_DEBUG "log4jDebug" +#define UKUILOG4QT_SETTINGS_HANDLEQT "log4jHandleqtmessages" +#define UKUILOG4QT_SETTINGS_ROOTLOGGER "log4jRootlogger" +#define UKUILOG4QT_SETTINGS_DAILY_DATEPATTERN "log4jAppenderDailyDatepattern" +#define UKUILOG4QT_SETTINGS_DAILY_CONVERSIONPATTERN "log4jAppenderDailyLayoutConversionpattern" +#define UKUILOG4QT_SETTINGS_ROLLINGCHECK_DELAYTIME "delaytime" +#define UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILECOUNT "maxfilecount" +#define UKUILOG4QT_SETTINGS_ROLLINGCHECK_MAXFILESIZE "maxfilesize" + +// log4qt相关属性 +#define UKUILOG4QT_RESET "log4j.reset" //是否重置所有配置,恢复全局设置默认值 +#define UKUILOG4QT_DEBUG "log4j.Debug" //设置日志sdk内部记录器级别 +#define UKUILOG4QT_HANDLEQT "log4j.handleQtMessages" //设置是否监听QDebug输出的字符串 +#define UKUILOG4QT_ROOTLOGGER "log4j.rootLogger" //设置根Logger的输出log等级和输出目的地 +#define UKUILOG4QT_DAILY_DATEPATTERN "log4j.appender.daily.datePattern" //记录器文件名日期后缀 按天 +#define UKUILOG4QT_DAILY_CONVERSIONPATTERN "log4j.appender.daily.layout.conversionPattern" //记录器日志输出格式 + +#endif // __UKUI_LOGMACROS__ diff --git a/src/log4qt/ukui-logrolling.cpp b/src/log4qt/ukui-logrolling.cpp new file mode 100644 index 0000000..35ba744 --- /dev/null +++ b/src/log4qt/ukui-logrolling.cpp @@ -0,0 +1,181 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include + +UkuiLog4qtRolling::UkuiLog4qtRolling(QString strBaseFilePath, unsigned uMaxFileCount, quint64 uMaxFileSize, + quint64 delayCheckFileTime, QObject *parent) : + QThread(parent), + m_isExit(false), + m_delayCheckFileTime(delayCheckFileTime), + m_strBaseFilePath(strBaseFilePath), + m_uMaxFileCount(uMaxFileCount), + m_uMaxFileSize(uMaxFileSize*1024*1024) // 单位 M +{ +} + +UkuiLog4qtRolling::~UkuiLog4qtRolling() +{ + +} + +// 线程过程 +void UkuiLog4qtRolling::run() +{ + // 时间间隔参数异常 + if (m_delayCheckFileTime == 0) { + return ; + } + + // 定时检查日志文件和大小 + while (!m_isExit && m_delayCheckFileTime != 0) { + m_lockReadWrite.lockForRead(); + if (m_uMaxFileCount > 0) { + checkLogFilesCount(); + } + if (m_uMaxFileSize > 0) { + checkLogFilesSize(); + } + quint64 willDelayCheckFileTime = m_delayCheckFileTime*1000; + m_lockReadWrite.unlock(); + // 细化sleep片段 + while (!m_isExit && willDelayCheckFileTime >= 50 && !m_isConfigChange) { + QThread::msleep(50); + willDelayCheckFileTime -= 50; + } + m_lockReadWrite.lockForWrite(); + m_isConfigChange = false; + m_lockReadWrite.unlock(); + if (m_isExit) { + break; + } + } +} + +// 设置文件检查限制条件 +void UkuiLog4qtRolling::setFileCheckLimit(unsigned uMaxFileCount, quint64 uMaxFileSize, quint64 delayCheckFileTime) +{ + m_lockReadWrite.lockForWrite(); + m_uMaxFileCount = uMaxFileCount; + m_uMaxFileSize = uMaxFileSize*1024*1024; // 单位 M + m_delayCheckFileTime = delayCheckFileTime; + m_isConfigChange = true; + m_lockReadWrite.unlock(); +} + +// 停止线程 +void UkuiLog4qtRolling::stop() +{ + m_isExit = true; +} + +// 检查文件数量 +void UkuiLog4qtRolling::checkLogFilesCount() +{ + if (m_strBaseFilePath.isEmpty()) { + return; + } + + QFileInfo fileInfo(m_strBaseFilePath); + if (!fileInfo.exists()) { + return; + } + QDir dir(fileInfo.path()); + if (!dir.exists()) { + return ; + } + dir.setFilter(QDir::Files | QDir::NoSymLinks); + QStringList filters; + filters<= 0; i--) { + if (willRmFileCount <= 0) { + break; + } + QString filePath = fileInfoList[i].absoluteFilePath(); + KyDebug()<<"Will Remove File:"<= 0; i--) { + if (willRmFileSize <= 0) { + break; + } + QString filePath = fileInfoList[i].absoluteFilePath(); + KyDebug()<<"Will Remove File:"< %1").arg(filePath)); + process.waitForFinished(100); + } + } +} \ No newline at end of file diff --git a/src/log4qt/ukui-logrolling.h b/src/log4qt/ukui-logrolling.h new file mode 100644 index 0000000..98c9df7 --- /dev/null +++ b/src/log4qt/ukui-logrolling.h @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2021 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include + +class UkuiLog4qtRolling : public QThread +{ +public: + UkuiLog4qtRolling(QString strBaseFilePath, unsigned uMaxFileCount = 0, quint64 uMaxFileSize = 0, + quint64 delayCheckFileTime = 0, QObject *parent = nullptr); + virtual ~UkuiLog4qtRolling(); + + // 停止线程 + void stop(); + // 设置文件检查限制条件 + void setFileCheckLimit(unsigned uMaxFileCount = 0, quint64 uMaxFileSize = 0, quint64 delayCheckFileTime = 0); + // 检查文件数量 + void checkLogFilesCount(); + // 检查文件大小 + void checkLogFilesSize(); + +protected: + void run(); + +private: + // 是否将线程退出 + bool m_isExit = true; + // 间隔检查文件时间 单位(s) + quint64 m_delayCheckFileTime = 0; + // 当前基础文件路径 + QString m_strBaseFilePath; + // 最大文件数限制 + unsigned m_uMaxFileCount = 0; + // 最大文件大小限制 + quint64 m_uMaxFileSize = 0; + // 数据保护锁 + QReadWriteLock m_lockReadWrite; + // 配置是否修改 + bool m_isConfigChange = false; +}; + +#endif // __UKUILOG4QT_ROLLING_H__ \ No newline at end of file diff --git a/src/network/Makefile.am b/src/network/Makefile.am new file mode 100644 index 0000000..b7955db --- /dev/null +++ b/src/network/Makefile.am @@ -0,0 +1 @@ +SUBDIRS=network diff --git a/src/network/network/Makefile.am b/src/network/network/Makefile.am new file mode 100644 index 0000000..828cfca --- /dev/null +++ b/src/network/network/Makefile.am @@ -0,0 +1,15 @@ +#Generata binary file +lib_LTLIBRARIES = libukui-network.la + +#gcc -wall: displays all the errors and warning information when compiling +#gcc -g: add the debugging code when compiling +COMM_CFS = -Wall -g + +#Add the dependent source file for libnetwork.la +libukui_network_la_SOURCES = kylin-network-interface.c \ + $(NULL) + +#The header files that need to be installed +include_HEADERS= kylin-network-interface.h \ + $(NULL) + diff --git a/src/network/network/kylin-network-interface.c b/src/network/network/kylin-network-interface.c new file mode 100644 index 0000000..3526464 --- /dev/null +++ b/src/network/network/kylin-network-interface.c @@ -0,0 +1,701 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +//#include +#include +#include +#include +//#include +//#include +//#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "kylin-network-interface.h" + +//获取网络接口信息 +int kylin_network_network_getifacename(char **if_name) +{ + int i = 0; + int sockfd; + struct ifconf ifconf; + struct ifreq *ifreq; + unsigned char buf[1024]; + + //初始化ifconf + ifconf.ifc_len = 1024; + //字符串指针ifconf.ifc_buf指向buf + ifconf.ifc_buf = buf; + + if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) + { + perror("socket error"); + return 0; + } + + //获取所有接口信息 + ioctl(sockfd, SIOCGIFCONF, &ifconf); + // printf("%s\n",ifconf.ifc_buf); + + //逐个获取Ip地址 + //结构体指针ifreq指向buf,即ifconf.ifc_buf + ifreq = (struct ifreq*)buf; + int number=ifconf.ifc_len/sizeof(struct ifreq); + printf("%d\n",number); + + for(i = number; i>0; i--) + { +// printf("name = [%s] \n",ifreq->ifr_name); + + int j=number-i; + if_name[j]=ifreq->ifr_name; +// printf("if_name[%d]:%s\n",j,if_name[j]); + + ifreq++; + } + return number; +} + +//获取ip地址 +int kylin_network_network_getipaddr(char *if_name,char *ipaddr) +{ + int sock_ip; + struct sockaddr_in sin_ip; + struct ifreq ifr_ip; + if((sock_ip=socket(AF_INET,SOCK_STREAM,0))<0) + { + perror("sockket error"); + return -1; + } + + strcpy(ifr_ip.ifr_name,if_name); + + if(ioctl(sock_ip,SIOCGIFADDR,&ifr_ip)<0)//直接获取ip地址 + { + perror("Not setup interface\n"); + return -1; + } + + memcpy(&sin_ip,&ifr_ip.ifr_addr,sizeof(sin_ip)); + strcpy(ipaddr,inet_ntoa(sin_ip.sin_addr));//#include + close(sock_ip); + return 0; + +} + +//设置ip地址 +int kylin_network_network_setip(char *if_name,char *ipaddr) +{ + int sock_ip; + struct sockaddr_in sin_ip; //#include + struct ifreq ifr_ip; //#include + +// bzero(&ifr_ip, sizeof(ifr_ip)); //#include + + if(ipaddr==NULL) + return -1; + + if((sock_ip=socket(AF_INET,SOCK_STREAM,0))==-1)//#include + { + perror("Create socket failure!\n"); + return -1; + } + + memset(&sin_ip,0,sizeof(sin_ip)); + memset(&ifr_ip.ifr_name,0,sizeof(ifr_ip)); + strcpy(ifr_ip.ifr_name,if_name); +// printf("-----%d------\n",ioctl(sock_ip,SIOCSIFADDR,&ifr_ip)); + + sin_ip.sin_family=AF_INET; + sin_ip.sin_addr.s_addr=inet_addr(ipaddr); + memcpy(&ifr_ip.ifr_addr,&sin_ip, sizeof(sin_ip)); + +// printf("-----%d------\n",ioctl(sock_ip,SIOCSIFADDR,&ifr_ip)); + + //此处非root用户运行报错,待解 + if(ioctl(sock_ip,SIOCSIFADDR,&ifr_ip)<0) + { + perror("Not setup interface\n"); + return -1; + } + + close(sock_ip); + return 0; +} + +//获取广播地址 +int kylin_network_network_getbrdaddr(char *if_name,char *brdaddr) +{ + int sock_brdaddr; + struct sockaddr_in sin_brd; + struct ifreq ifr_brd; + if((sock_brdaddr=socket(AF_INET,SOCK_STREAM,0))<0) + { + perror("sockket error"); + return -1; + } + + strcpy(ifr_brd.ifr_name,if_name); + + if(ioctl(sock_brdaddr,SIOCGIFBRDADDR,&ifr_brd)<0)//直接获取广播地址 + { + perror("Not setup interface\n"); + return -1; + } + + memcpy(&sin_brd,&ifr_brd.ifr_broadaddr,sizeof(sin_brd)); + strcpy(brdaddr,inet_ntoa(sin_brd.sin_addr)); + close(sock_brdaddr); + return 0; + +} + +//设置广播地址 +int kylin_network_network_setbrdaddr(char *if_name,char *brdaddr) +{ + int sock_brdaddr; +// char netmask_addr[32]; + + struct ifreq ifr_brd; + struct sockaddr_in sin_brd; + + sock_brdaddr=socket(AF_INET,SOCK_STREAM,0); + if(sock_brdaddr==-1) + { + perror("Create socket failure!\n"); + return -1; + } + + memset(&sin_brd,0,sizeof(sin_brd)); + memset(&ifr_brd,0,sizeof(ifr_brd)); + strcpy(ifr_brd.ifr_name,if_name); + + + sin_brd.sin_family=AF_INET; + sin_brd.sin_addr.s_addr=inet_addr(brdaddr); + memcpy(&ifr_brd.ifr_addr,&sin_brd,sizeof(sin_brd)); + + if(ioctl(sock_brdaddr,SIOCSIFBRDADDR,&ifr_brd)<0) + { + perror("Not setup interface:SIOCSIFBRDADDR\n"); + return -1; + } + + close(sock_brdaddr); + return 0; + +} + +//获取子网掩码 +int kylin_network_network_getnetmask(char *if_name,char *netmask) +{ + int sock_mask; + struct sockaddr_in sin_netmask; + struct ifreq ifr_mask; + if((sock_mask=socket(AF_INET,SOCK_STREAM,0))<0) + { + perror("sockket error"); + return -1; + } + + strcpy(ifr_mask.ifr_name,if_name); + + if(ioctl(sock_mask,SIOCGIFNETMASK,&ifr_mask)<0)//直接获取子网掩码 + { + perror("Not setup interface\n"); + return -1; + } + + memcpy(&sin_netmask,&ifr_mask.ifr_netmask,sizeof(sin_netmask)); + strcpy(netmask,inet_ntoa(sin_netmask.sin_addr)); + close(sock_mask); + return 0; + +} + +//设置子网掩码 +int kylin_network_network_setnetmask(char *if_name,char *netmask) +{ + int sock_netmask; +// char netmask_addr[32]; + + struct ifreq ifr_mask; + struct sockaddr_in sin_netmask; + + sock_netmask=socket(AF_INET,SOCK_STREAM,0); + if(sock_netmask==-1) + { + perror("Create socket failure!\n"); + return -1; + } + + memset(&sin_netmask,0,sizeof(sin_netmask)); + memset(&ifr_mask,0,sizeof(ifr_mask)); + strcpy(ifr_mask.ifr_name,if_name); + + + sin_netmask.sin_family=AF_INET; + sin_netmask.sin_addr.s_addr=inet_addr(netmask); + memcpy(&ifr_mask.ifr_addr,&sin_netmask,sizeof(sin_netmask)); + + +// printf("---%d---\n",ioctl(sock_netmask,SIOCSIFNETMASK,&ifr_mask)); + + if(ioctl(sock_netmask,SIOCSIFNETMASK,&ifr_mask)<0) + { + perror("Not setup interface\n"); + return -1; + } + + close(sock_netmask); + return 0; + +} + +//增加路由表 +int kylin_network_network_addgateway(char *gateway) +{ + int sock_gateway; + struct rtentry rmten; + struct sockaddr_in sin_gateway; + sock_gateway=socket(AF_INET,SOCK_DGRAM,0); + + if(sock_gateway==-1) + { + perror("Create socket failure!\n"); + return -1; + } + + memset(&rmten,0,sizeof(rmten)); + + sin_gateway.sin_family=AF_INET; + sin_gateway.sin_addr.s_addr=inet_addr(gateway); + sin_gateway.sin_port=0; + + ((struct sockaddr_in *)&rmten.rt_dst)->sin_family=AF_INET; + + ((struct sockaddr_in *)&rmten.rt_genmask)->sin_family=AF_INET; + + memcpy(&rmten.rt_gateway,&sin_gateway,sizeof(sin_gateway)); +// rmten.rt_flags=RTF_UP | RTF_GATEWAY; + rmten.rt_flags=RTF_GATEWAY; + + if(ioctl(sock_gateway,SIOCADDRT,&rmten)<0) + { + perror("Not setup interface\n"); + return -1; + } + + close(sock_gateway); + return 0; +} + +//删除路由表 +int kylin_network_network_delgateway(char *gateway) +{ + int sock_gateway; + struct rtentry rmten; + struct sockaddr_in sin_gateway; + sock_gateway=socket(AF_INET,SOCK_DGRAM,0); + + if(sock_gateway==-1) + { + perror("Create socket failure!\n"); + return -1; + } + + memset(&rmten,0,sizeof(rmten)); + + sin_gateway.sin_family=AF_INET; + sin_gateway.sin_addr.s_addr=inet_addr(gateway); + sin_gateway.sin_port=0; + + ((struct sockaddr_in *)&rmten.rt_dst)->sin_family=AF_INET; + ((struct sockaddr_in *)&rmten.rt_genmask)->sin_family=AF_INET; + + memcpy(&rmten.rt_gateway,&sin_gateway,sizeof(sin_gateway)); +// rmten.rt_flags=RTF_UP | RTF_GATEWAY; + rmten.rt_flags=RTF_GATEWAY; + + if(ioctl(sock_gateway,SIOCDELRT,&rmten)<0) + { + perror("Not setup interface\n"); + return -1; + } + + close(sock_gateway); + return 0; +} + +//获取MAC +int kylin_network_network_getmac(char *if_name,char *macaddr) +{ + int sock_mac; + struct ifreq ifr_mac; + struct sockaddr_in sin_mac; + struct ether_addr ethaddr;//#include + + sock_mac=socket(AF_INET,SOCK_STREAM,0); + + strcpy(ifr_mac.ifr_name,if_name); + + if(-1==ioctl(sock_mac,SIOCGIFHWADDR,&ifr_mac)) + { + perror("Not setup interface\n"); + return -1; + } + memcpy(ðaddr,&ifr_mac.ifr_hwaddr.sa_data,sizeof(ethaddr)); + strcpy(macaddr,ether_ntoa(ðaddr));//#include + +// strcpy(macaddr,ether_ntoa((struct ether_addr*)ifr_mac.ifr_hwaddr.sa_data)); + + close(sock_mac); + return 0; + + +} + +//启用网络接口 +int kylin_network_network_setifup(char *if_name) +{ + struct ifreq ifr; + int sockfd; + if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) + { + perror("socket error"); + return 1; + }//创建用来检查网络的套接字 + + + strcpy(ifr.ifr_name,if_name); + + if(ioctl(sockfd,SIOCGIFFLAGS,&ifr)<0) + { + perror("ioctl SIOCGIFFLAGS error\n"); + return -1; + } + +// printf("%d\n",ifr.ifr_flags); + ifr.ifr_flags|=IFF_UP; +// printf("%d\n",ifr.ifr_flags); + if(ioctl(sockfd,SIOCSIFFLAGS,&ifr)<0) + { + perror("ioctl SIOCSIFFLAGS ERROR\n"); + return -1; + } + + close(sockfd); + return 0; + +} + +//关闭网络接口 +int kylin_network_network_setifdown(char *if_name) +{ + struct ifreq ifr; + int sockfd; + if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) + { + perror("socket error"); + return 1; + }//创建用来检查网络的套接字 + + + strcpy(ifr.ifr_name,if_name); + + if(ioctl(sockfd,SIOCGIFFLAGS,&ifr)<0) + { + perror("ioctl SIOCGIFFLAGS error\n"); + return -1; + } + +// printf("%d\n",ifr.ifr_flags); + ifr.ifr_flags &=~IFF_UP; //将IFF_UP取反后与原来的标志进行与运算 +// printf("%d\n",ifr.ifr_flags); + if(ioctl(sockfd,SIOCSIFFLAGS,&ifr)<0) + { + perror("ioctl SIOCSIFFLAGS ERROR\n"); + return -1; + } + + close(sockfd); + return 0; + +} + +//获取MTU +int kylin_network_network_getmtu(char *if_name) +{ + int sock_mtu; +// struct sockaddr_in sin_ip; + struct ifreq ifr_MTU; + if((sock_mtu=socket(AF_INET,SOCK_STREAM,0))<0) + { + perror("sockket error"); + return -1; + } + + strcpy(ifr_MTU.ifr_name,if_name); + + if(ioctl(sock_mtu,SIOCGIFMTU,&ifr_MTU)) + { + perror("Not setup interface\n"); + return -1; + } + + int mtu=ifr_MTU.ifr_mtu; +// printf("%d\n",ifr_MTU.ifr_mtu); +// printf("%d\n",mtu); + + close(sock_mtu); + return mtu; + +} + +static void getBuf(char *bufstr) +{ + //O_RDONLY以只读方式打开文件 + int fd=open("/proc/net/dev", O_RDONLY); + if(-1==fd) + { + printf("/proc/net/dev not exists!\n"); + } + + char buf[1024*2]; + //将读写位置移到文件开头 + lseek(fd,0,SEEK_SET); + int nBytes=read(fd,buf,sizeof(buf)-1); + if(-1==nBytes) + { + perror("read error"); + close(fd); + } + + buf[nBytes]='\0'; + strcpy(bufstr,buf); +} + +//总计上传下载数据量 +long *kylin_network_network_getbytes(char *if_name) +{ + char buf[1024*2]; + getBuf(buf); + + //返回第一次指向if_name位置的指针 + char *pDev=strstr(buf,if_name); + if(NULL==pDev) + { + printf("don't find dev %s\n",if_name); + return NULL; + } + + char *p; + char *value; + int i=0; + static long rtbyt[2]; + /*去除空格,制表符,换行符等不需要的字段*/ + for (p = strtok(pDev, " \t\r\n"); p; p = strtok(NULL, " \t\r\n")) + { + i++; + value = (char*)malloc(20); + strcpy(value, p); + /*得到的字符串中的第二个字段是接收流量*/ + if(i == 2) + { + rtbyt[0] = atol(value); + } + /*得到的字符串中的第十个字段是发送流量*/ + if(i == 10) + { + rtbyt[1] = atol(value); + break; + } + free(value); + } + return rtbyt; +} + +//总计上传下载数据包 +long *kylin_network_network_getpackets(char *if_name) +{ + char buf[1024*2]; + getBuf(buf); + + //返回第一次指向if_name位置的指针 + char *pDev=strstr(buf,if_name); + if(NULL==pDev) + { + printf("don't find dev %s\n",if_name); + return NULL; + } + + char *p; + char *value; + int i=0; + static long rtpkt[2]; + /*去除空格,制表符,换行符等不需要的字段*/ + for (p = strtok(pDev, " \t\r\n"); p; p = strtok(NULL, " \t\r\n")) + { + i++; + value = (char*)malloc(20); + strcpy(value, p); + /*得到的字符串中的第三个字段是接收流量*/ + if(i == 3) + { + rtpkt[0] = atol(value); + } + /*得到的字符串中的第十一个字段是发送流量*/ + if(i == 11) + { + rtpkt[1] = atol(value); + break; + } + free(value); + } + return rtpkt; +} + +//总计上传下载错误数据包数量 +long *kylin_network_network_geterrs(char *if_name) +{ + char buf[1024*2]; + getBuf(buf); + + //返回第一次指向if_name位置的指针 + char *pDev=strstr(buf,if_name); + if(NULL==pDev) + { + printf("don't find dev %s\n",if_name); + return NULL; + } + + char *p; + char *value; + int i=0; + static long rterrs[2]; + /*去除空格,制表符,换行符等不需要的字段*/ + for (p = strtok(pDev, " \t\r\n"); p; p = strtok(NULL, " \t\r\n")) + { + i++; + value = (char*)malloc(20); + strcpy(value, p); + /*得到的字符串中的第四个字段是接收流量*/ + if(i == 4) + { + rterrs[0] = atol(value); + } + /*得到的字符串中的第十二个字段是发送流量*/ + if(i == 12) + { + rterrs[1] = atol(value); + break; + } + free(value); + } + return rterrs; +} + +//总计上传下载丢弃数据包数量 +long *kylin_network_network_getdrop(char *if_name) +{ + char buf[1024*2]; + getBuf(buf); + + //返回第一次指向if_name位置的指针 + char *pDev=strstr(buf,if_name); + if(NULL==pDev) + { + printf("don't find dev %s\n",if_name); + return NULL; + } + + char *p; + char *value; + int i=0; + static long rtdrop[2]; + /*去除空格,制表符,换行符等不需要的字段*/ + for (p = strtok(pDev, " \t\r\n"); p; p = strtok(NULL, " \t\r\n")) + { + i++; + value = (char*)malloc(20); + strcpy(value, p); + /*得到的字符串中的第五个字段是接收流量*/ + if(i == 5) + { + rtdrop[0] = atol(value); + } + /*得到的字符串中的第十三个字段是发送流量*/ + if(i == 13) + { + rtdrop[1] = atol(value); + break; + } + free(value); + } + return rtdrop; +} + +//总计上传下载过载数据包数量 +long *kylin_network_network_getfifo(char *if_name) +{ + char buf[1024*2]; + getBuf(buf); + + //返回第一次指向if_name位置的指针 + char *pDev=strstr(buf,if_name); + if(NULL==pDev) + { + printf("don't find dev %s\n",if_name); + return NULL; + } + + char *p; + char *value; + int i=0; + static long rtfifo[2]; + /*去除空格,制表符,换行符等不需要的字段*/ + for (p = strtok(pDev, " \t\r\n"); p; p = strtok(NULL, " \t\r\n")) + { + i++; + value = (char*)malloc(20); + strcpy(value, p); + /*得到的字符串中的第六个字段是接收流量*/ + if(i == 6) + { + rtfifo[0] = atol(value); + } + /*得到的字符串中的第十四个字段是发送流量*/ + if(i == 14) + { + rtfifo[1] = atol(value); + break; + } + free(value); + } + return rtfifo; +} + diff --git a/src/network/network/kylin-network-interface.h b/src/network/network/kylin-network-interface.h new file mode 100644 index 0000000..9f3e84f --- /dev/null +++ b/src/network/network/kylin-network-interface.h @@ -0,0 +1,152 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C"{ +#endif + +/* + * Get the network interface information. + * @if_name is used to save the interface name. + * return the interface number. + */ +int kylin_network_network_getifacename(char **if_name); + +/* Get the ip address. + * @if_name is the interface name. + * @ipaddr is used to save the ip address. + */ +int kylin_network_network_getipaddr(char *if_name,char *ipaddr); + +/* + * Set the ip address. + * @if_name is the interface name. + * @ipaddr is the ip address that need to be set. + */ +int kylin_network_network_setip(char *if_name,char *ipaddr); + +/* + * Get the broadcast address. + * @if_name is the interface name. + * @brdaddr is used to save the broadcast address. + */ +int kylin_network_network_getbrdaddr(char *if_name,char *brdaddr); + +/* + * Set the broadcast address. + * @if_name is the interface name. + * @brdaddr is the broadcast address that need to be set. + */ +int kylin_network_network_setbrdaddr(char *if_name,char *brdaddr); + +/* + * Get the subnet mask. + * @if_name is the interface name. + * @netmask is used to save the subnet mask. + */ +int kylin_network_network_getnetmask(char *if_name,char *netmask); + +/* Set the subnet mask. + * @if_name is the interface name. + * @netmask is the subnet mask that need to be set. + */ +int kylin_network_network_setnetmask(char *if_name,char *netmask); + +/* + * Add routing tables. + * @gateway is the gateway address that need to be added. + */ +int kylin_network_network_addgateway(char *gateway); + +/* + * Delete routing tables. + * @gateway is the gateway address that need to be deleted. + */ +int kylin_network_network_delgateway(char *gateway); + +/* + * Get MAC address. + * @if_name is the interface name. + * @macaddr is used to save the MAC address. + */ +int kylin_network_network_getmac(char *if_name,char *macaddr); + +/* + * Enable network interface. + * @if_name is the interface name that need to be enabled. + */ +int kylin_network_network_setifup(char *if_name); + +/* + * Disabled network interface. + * @if_name is the interface name that need to be disabled. + */ +int kylin_network_network_setifdown(char *if_name); + +/* Get the MTU. + * @if_name is the interface name. + * return the MTU value. + */ +int kylin_network_network_getmtu(char *if_name); + +/* + * Total upload and download data volume. + * @if_name is the network interface name. + * return the address of the first element of a one-dimensional long integer array. + */ +long *kylin_network_network_getbytes(char *if_name); + +/* + * Total upload and download data packets. + * @if_name is the network interface name. + * return the address of the first element of a one-dimensional long integer array. + */ +long *kylin_network_network_getpackets(char *if_name); + +/* + * Total wrong data packets number of uploading and downloading. + * @if_name is the network interface name. + * return the address of the first element of a one-dimensional long integer array. + */ +long *kylin_network_network_geterrs(char *if_name); + +/* + * Total discarded data packets number of uploading and downloading. + * @if_name is the network interface name. + * return the address of the first element of a one-dimensional long integer array. + */ +long *kylin_network_network_getdrop(char *if_name); + +/* + * Total overloaded data packets number of uploading and downloading. + * @if_name is the network interface name. + * return the address of the first element of a one-dimensional long integer array. + */ +long *kylin_network_network_getfifo(char *if_name); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/os/Makefile.am b/src/os/Makefile.am new file mode 100644 index 0000000..215c46c --- /dev/null +++ b/src/os/Makefile.am @@ -0,0 +1 @@ +SUBDIRS=subversion sysinfo diff --git a/src/os/subversion/Makefile.am b/src/os/subversion/Makefile.am new file mode 100644 index 0000000..9be711c --- /dev/null +++ b/src/os/subversion/Makefile.am @@ -0,0 +1,18 @@ +lib_LTLIBRARIES = libukui-subversion.la + +COMM_CFS = -Wall -g -fPIC + +libukui_subversion_la_SOURCES = kylin-version-interface.cpp \ + $(NULL) + +include_HEADERS= \ + kylin-version-interface.h \ + $(NULL) + +libukui_subversion_la_CPPFLAGS= $(COMM_CFS) \ + $(QT5CORE_CFLAGS) \ + $(NULL) + +libukui_subversion_la_LDFLAGS= \ + $(QT5CORE_LIBS) \ + $(NULL) diff --git a/src/os/subversion/kylin-version-interface.cpp b/src/os/subversion/kylin-version-interface.cpp new file mode 100644 index 0000000..c073f75 --- /dev/null +++ b/src/os/subversion/kylin-version-interface.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include "kylin-version-interface.h" + +#define SUBVERSION "/var/lib/system-info/subversion" + +//查找以File开头的key +int cmpKey(const char *keystr) +{ + int result=strncmp(keystr,"File",4); +// qDebug()< +#include +#include +#include +#include "kylin-sysinfo-interface.h" + +void kylin_os_sysinfo_sysname(char *sysname) +{ + struct utsname buf; + if(uname(&buf)) + { + perror("uname"); + return; + } + + strcpy(sysname,buf.sysname); + +} + +void kylin_os_sysinfo_nodename(char *nodename) +{ + struct utsname buf; + if(uname(&buf)) + { + perror("uname"); + return; + } + + strcpy(nodename,buf.nodename); +} + +void kylin_os_sysinfo_release(char *release) +{ + struct utsname buf; + if(uname(&buf)) + { + perror("uname"); + return; + } + + strcpy(release,buf.release); +} + +void kylin_os_sysinfo_machine(char *machine) +{ + struct utsname buf; + if(uname(&buf)) + { + perror("uname"); + return; + } + + strcpy(machine,buf.machine); +} + +void kylin_os_sysinfo_version(char *version) +{ + struct utsname buf; + if(uname(&buf)) + { + perror("uname"); + return; + } + + strcpy(version,buf.version); +} diff --git a/src/os/sysinfo/kylin-sysinfo-interface.h b/src/os/sysinfo/kylin-sysinfo-interface.h new file mode 100644 index 0000000..377a754 --- /dev/null +++ b/src/os/sysinfo/kylin-sysinfo-interface.h @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C"{ +#endif + +/* + * Get the name of the implementation of the operating system. + * @sysname is used to store the name of the operating system. + */ +void kylin_os_sysinfo_sysname(char *sysname); + +/* + * Get the name of this node on the network. + * @nodename is used to store the name of network node. + */ +void kylin_os_sysinfo_nodename(char *nodename); + +/* + * Get current release level of this implementation. + * @release is used to store the release level. + */ +void kylin_os_sysinfo_release(char *release); + +/* + * Get the name of the hardware type the system is running on. + * @machine is used to store the name of the hardware type. + */ +void kylin_os_sysinfo_machine(char *machine); + +/* + * Get current version level of this release. + * @version is used to store the current version level. + */ +void kylin_os_sysinfo_version(char *version); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/other/Makefile.am b/src/other/Makefile.am new file mode 100644 index 0000000..e69de29 diff --git a/src/personal/Makefile.am b/src/personal/Makefile.am new file mode 100755 index 0000000..89929a6 --- /dev/null +++ b/src/personal/Makefile.am @@ -0,0 +1 @@ +SUBDIRS=font background desktop marcogeneral diff --git a/src/personal/background/Makefile.am b/src/personal/background/Makefile.am new file mode 100644 index 0000000..c33f1fe --- /dev/null +++ b/src/personal/background/Makefile.am @@ -0,0 +1,55 @@ +COMM_PRINT= -L$(top_srcdir)/src/common -lukui-print +COMM_GSETTINGS= -L$(top_srcdir)/src/common -lukui-gsettings + +#generate the .c and .h file which used by client and server side by XML file +#$(top_srcdir) represents the top-level directory of the project +DESC_XML = $(top_srcdir)/data/cn.kylinos.background.xml +GENERATED_CH = background-generated + +background-generated.h background-generated.c: $(DESC_XML) + gdbus-codegen --interface-prefix cn.kylinos. --generate-c-code $(GENERATED_CH) $(DESC_XML) + +#Generata binary file +lib_LTLIBRARIES = libukui-backgroundclient.la + +#gcc -wall: displays all the errors and warning information when compiling +#gcc -g: add the debugging code when compiling +COMM_CFS = -Wall -g + +#Add the dependent source file for libbackgroundclient.la +#background-generated.c must be front of kylin-background-interface.c +libukui_backgroundclient_la_SOURCES = background-generated.c kylin-background-interface.c \ + $(NULL) + +#The header files that need to be installed +include_HEADERS= kylin-background-interface.h \ + $(NULL) + +#Additional C compiler flags +libukui_backgroundclient_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_backgroundclient_la_LDFLAGS= $(COMM_PRINT) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Generata binary file +bin_PROGRAMS = ukui-backgroundserver + +#Add the dependent source file for backgroundserver +ukui_backgroundserver_SOURCES = \ + background-generated.h background-generated.c \ + kylin-background-server.c \ + $(NULL) + +#Additional C compiler flags +ukui_backgroundserver_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +ukui_backgroundserver_LDFLAGS= $(COMM_PRINT) $(COMM_GSETTINGS) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) diff --git a/src/personal/background/background-dbus.h b/src/personal/background/background-dbus.h new file mode 100644 index 0000000..d177021 --- /dev/null +++ b/src/personal/background/background-dbus.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 /* Bus define */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define BACKGROUND_BUS G_BUS_TYPE_SESSION +#define BACKGROUND_BUS_NAME "cn.kylinos.background" +#define BACKGROUND_OBJECT_PATH "/cn/kylinos/background" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/personal/background/background-generated.c b/src/personal/background/background-generated.c new file mode 100644 index 0000000..55b28ab --- /dev/null +++ b/src/personal/background/background-generated.c @@ -0,0 +1,1392 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#ifdef G_OS_UNIX +# include +#endif + +typedef struct +{ + GDBusArgInfo parent_struct; + gboolean use_gvariant; +} _ExtendedGDBusArgInfo; + +typedef struct +{ + GDBusMethodInfo parent_struct; + const gchar *signal_name; + gboolean pass_fdlist; +} _ExtendedGDBusMethodInfo; + +typedef struct +{ + GDBusSignalInfo parent_struct; + const gchar *signal_name; +} _ExtendedGDBusSignalInfo; + +typedef struct +{ + GDBusPropertyInfo parent_struct; + const gchar *hyphen_name; + guint use_gvariant : 1; + guint emits_changed_signal : 1; +} _ExtendedGDBusPropertyInfo; + +typedef struct +{ + GDBusInterfaceInfo parent_struct; + const gchar *hyphen_name; +} _ExtendedGDBusInterfaceInfo; + +typedef struct +{ + const _ExtendedGDBusPropertyInfo *info; + guint prop_id; + GValue orig_value; /* the value before the change */ +} ChangedProperty; + +static void +_changed_property_free (ChangedProperty *data) +{ + g_value_unset (&data->orig_value); + g_free (data); +} + +static gboolean +_g_strv_equal0 (gchar **a, gchar **b) +{ + gboolean ret = FALSE; + guint n; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + if (g_strv_length (a) != g_strv_length (b)) + goto out; + for (n = 0; a[n] != NULL; n++) + if (g_strcmp0 (a[n], b[n]) != 0) + goto out; + ret = TRUE; +out: + return ret; +} + +static gboolean +_g_variant_equal0 (GVariant *a, GVariant *b) +{ + gboolean ret = FALSE; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + ret = g_variant_equal (a, b); +out: + return ret; +} + +G_GNUC_UNUSED static gboolean +_g_value_equal (const GValue *a, const GValue *b) +{ + gboolean ret = FALSE; + g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); + switch (G_VALUE_TYPE (a)) + { + case G_TYPE_BOOLEAN: + ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); + break; + case G_TYPE_UCHAR: + ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); + break; + case G_TYPE_INT: + ret = (g_value_get_int (a) == g_value_get_int (b)); + break; + case G_TYPE_UINT: + ret = (g_value_get_uint (a) == g_value_get_uint (b)); + break; + case G_TYPE_INT64: + ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); + break; + case G_TYPE_UINT64: + ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); + break; + case G_TYPE_DOUBLE: + { + /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ + gdouble da = g_value_get_double (a); + gdouble db = g_value_get_double (b); + ret = memcmp (&da, &db, sizeof (gdouble)) == 0; + } + break; + case G_TYPE_STRING: + ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); + break; + case G_TYPE_VARIANT: + ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); + break; + default: + if (G_VALUE_TYPE (a) == G_TYPE_STRV) + ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); + else + g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); + break; + } + return ret; +} + +/* ------------------------------------------------------------------------ + * Code for interface cn.kylinos.background + * ------------------------------------------------------------------------ + */ + +/** + * SECTION:Background + * @title: Background + * @short_description: Generated C code for the cn.kylinos.background D-Bus interface + * + * This section contains code for working with the cn.kylinos.background D-Bus interface in C. + */ + +/* ---- Introspection data for cn.kylinos.background ---- */ + +static const _ExtendedGDBusArgInfo _background_method_info_transfer_bool_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(sb)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _background_method_info_transfer_bool_value_IN_ARG_pointers[] = +{ + &_background_method_info_transfer_bool_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _background_method_info_transfer_bool_value = +{ + { + -1, + (gchar *) "TransferBoolValue", + (GDBusArgInfo **) &_background_method_info_transfer_bool_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-bool-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _background_method_info_transfer_string_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(ss)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _background_method_info_transfer_string_value_IN_ARG_pointers[] = +{ + &_background_method_info_transfer_string_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _background_method_info_transfer_string_value = +{ + { + -1, + (gchar *) "TransferStringValue", + (GDBusArgInfo **) &_background_method_info_transfer_string_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-string-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _background_method_info_transfer_int_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(si)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _background_method_info_transfer_int_value_IN_ARG_pointers[] = +{ + &_background_method_info_transfer_int_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _background_method_info_transfer_int_value = +{ + { + -1, + (gchar *) "TransferIntValue", + (GDBusArgInfo **) &_background_method_info_transfer_int_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-int-value", + FALSE +}; + +static const GDBusMethodInfo * const _background_method_info_pointers[] = +{ + &_background_method_info_transfer_bool_value.parent_struct, + &_background_method_info_transfer_string_value.parent_struct, + &_background_method_info_transfer_int_value.parent_struct, + NULL +}; + +static const _ExtendedGDBusInterfaceInfo _background_interface_info = +{ + { + -1, + (gchar *) "cn.kylinos.background", + (GDBusMethodInfo **) &_background_method_info_pointers, + NULL, + NULL, + NULL + }, + "background", +}; + + +/** + * background_interface_info: + * + * Gets a machine-readable description of the cn.kylinos.background D-Bus interface. + * + * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. + */ +GDBusInterfaceInfo * +background_interface_info (void) +{ + return (GDBusInterfaceInfo *) &_background_interface_info.parent_struct; +} + +/** + * background_override_properties: + * @klass: The class structure for a #GObject derived class. + * @property_id_begin: The property id to assign to the first overridden property. + * + * Overrides all #GObject properties in the #Background interface for a concrete class. + * The properties are overridden in the order they are defined. + * + * Returns: The last property id. + */ +guint +background_override_properties (GObjectClass *klass, guint property_id_begin) +{ + return property_id_begin - 1; +} + + + +/** + * Background: + * + * Abstract interface type for the D-Bus interface cn.kylinos.background. + */ + +/** + * BackgroundIface: + * @parent_iface: The parent interface. + * @handle_transfer_bool_value: Handler for the #Background::handle-transfer-bool-value signal. + * @handle_transfer_int_value: Handler for the #Background::handle-transfer-int-value signal. + * @handle_transfer_string_value: Handler for the #Background::handle-transfer-string-value signal. + * + * Virtual table for the D-Bus interface cn.kylinos.background. + */ + +typedef BackgroundIface BackgroundInterface; +G_DEFINE_INTERFACE (Background, background, G_TYPE_OBJECT) + +static void +background_default_init (BackgroundIface *iface) +{ + /* GObject signals for incoming D-Bus method calls: */ + /** + * Background::handle-transfer-bool-value: + * @object: A #Background. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferBoolValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call background_complete_transfer_bool_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-bool-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (BackgroundIface, handle_transfer_bool_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Background::handle-transfer-string-value: + * @object: A #Background. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferStringValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call background_complete_transfer_string_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-string-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (BackgroundIface, handle_transfer_string_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Background::handle-transfer-int-value: + * @object: A #Background. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferIntValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call background_complete_transfer_int_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-int-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (BackgroundIface, handle_transfer_int_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + +} + +/** + * background_call_transfer_bool_value: + * @proxy: A #BackgroundProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferBoolValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call background_call_transfer_bool_value_finish() to get the result of the operation. + * + * See background_call_transfer_bool_value_sync() for the synchronous, blocking version of this method. + */ +void +background_call_transfer_bool_value ( + Background *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * background_call_transfer_bool_value_finish: + * @proxy: A #BackgroundProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to background_call_transfer_bool_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with background_call_transfer_bool_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +background_call_transfer_bool_value_finish ( + Background *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * background_call_transfer_bool_value_sync: + * @proxy: A #BackgroundProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferBoolValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See background_call_transfer_bool_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +background_call_transfer_bool_value_sync ( + Background *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * background_call_transfer_string_value: + * @proxy: A #BackgroundProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferStringValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call background_call_transfer_string_value_finish() to get the result of the operation. + * + * See background_call_transfer_string_value_sync() for the synchronous, blocking version of this method. + */ +void +background_call_transfer_string_value ( + Background *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferStringValue", + g_variant_new ("(@(ss))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * background_call_transfer_string_value_finish: + * @proxy: A #BackgroundProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to background_call_transfer_string_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with background_call_transfer_string_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +background_call_transfer_string_value_finish ( + Background *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * background_call_transfer_string_value_sync: + * @proxy: A #BackgroundProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferStringValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See background_call_transfer_string_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +background_call_transfer_string_value_sync ( + Background *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferStringValue", + g_variant_new ("(@(ss))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * background_call_transfer_int_value: + * @proxy: A #BackgroundProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferIntValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call background_call_transfer_int_value_finish() to get the result of the operation. + * + * See background_call_transfer_int_value_sync() for the synchronous, blocking version of this method. + */ +void +background_call_transfer_int_value ( + Background *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * background_call_transfer_int_value_finish: + * @proxy: A #BackgroundProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to background_call_transfer_int_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with background_call_transfer_int_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +background_call_transfer_int_value_finish ( + Background *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * background_call_transfer_int_value_sync: + * @proxy: A #BackgroundProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferIntValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See background_call_transfer_int_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +background_call_transfer_int_value_sync ( + Background *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * background_complete_transfer_bool_value: + * @object: A #Background. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferBoolValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +background_complete_transfer_bool_value ( + Background *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/** + * background_complete_transfer_string_value: + * @object: A #Background. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferStringValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +background_complete_transfer_string_value ( + Background *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/** + * background_complete_transfer_int_value: + * @object: A #Background. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferIntValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +background_complete_transfer_int_value ( + Background *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/* ------------------------------------------------------------------------ */ + +/** + * BackgroundProxy: + * + * The #BackgroundProxy structure contains only private data and should only be accessed using the provided API. + */ + +/** + * BackgroundProxyClass: + * @parent_class: The parent class. + * + * Class structure for #BackgroundProxy. + */ + +struct _BackgroundProxyPrivate +{ + GData *qdata; +}; + +static void background_proxy_iface_init (BackgroundIface *iface); + +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (BackgroundProxy, background_proxy, G_TYPE_DBUS_PROXY, + G_ADD_PRIVATE (BackgroundProxy) + G_IMPLEMENT_INTERFACE (TYPE_BACKGROUND, background_proxy_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (BackgroundProxy, background_proxy, G_TYPE_DBUS_PROXY, + G_IMPLEMENT_INTERFACE (TYPE_BACKGROUND, background_proxy_iface_init)) + +#endif +static void +background_proxy_finalize (GObject *object) +{ + BackgroundProxy *proxy = BACKGROUND_PROXY (object); + g_datalist_clear (&proxy->priv->qdata); + G_OBJECT_CLASS (background_proxy_parent_class)->finalize (object); +} + +static void +background_proxy_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +background_proxy_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +background_proxy_g_signal (GDBusProxy *proxy, + const gchar *sender_name G_GNUC_UNUSED, + const gchar *signal_name, + GVariant *parameters) +{ + _ExtendedGDBusSignalInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + gsize n; + guint signal_id; + info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_background_interface_info.parent_struct, signal_name); + if (info == NULL) + return; + num_params = g_variant_n_children (parameters); + paramv = g_new0 (GValue, num_params + 1); + g_value_init (¶mv[0], TYPE_BACKGROUND); + g_value_set_object (¶mv[0], proxy); + g_variant_iter_init (&iter, parameters); + n = 1; + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_BACKGROUND); + g_signal_emitv (paramv, signal_id, 0, NULL); + for (n = 0; n < num_params + 1; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static void +background_proxy_g_properties_changed (GDBusProxy *_proxy, + GVariant *changed_properties, + const gchar *const *invalidated_properties) +{ + BackgroundProxy *proxy = BACKGROUND_PROXY (_proxy); + guint n; + const gchar *key; + GVariantIter *iter; + _ExtendedGDBusPropertyInfo *info; + g_variant_get (changed_properties, "a{sv}", &iter); + while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_background_interface_info.parent_struct, key); + g_datalist_remove_data (&proxy->priv->qdata, key); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } + g_variant_iter_free (iter); + for (n = 0; invalidated_properties[n] != NULL; n++) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_background_interface_info.parent_struct, invalidated_properties[n]); + g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } +} + +static void +background_proxy_init (BackgroundProxy *proxy) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + proxy->priv = background_proxy_get_instance_private (proxy); +#else + proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, TYPE_BACKGROUND_PROXY, BackgroundProxyPrivate); +#endif + + g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), background_interface_info ()); +} + +static void +background_proxy_class_init (BackgroundProxyClass *klass) +{ + GObjectClass *gobject_class; + GDBusProxyClass *proxy_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = background_proxy_finalize; + gobject_class->get_property = background_proxy_get_property; + gobject_class->set_property = background_proxy_set_property; + + proxy_class = G_DBUS_PROXY_CLASS (klass); + proxy_class->g_signal = background_proxy_g_signal; + proxy_class->g_properties_changed = background_proxy_g_properties_changed; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (BackgroundProxyPrivate)); +#endif +} + +static void +background_proxy_iface_init (BackgroundIface *iface) +{ +} + +/** + * background_proxy_new: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Asynchronously creates a proxy for the D-Bus interface cn.kylinos.background. See g_dbus_proxy_new() for more details. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call background_proxy_new_finish() to get the result of the operation. + * + * See background_proxy_new_sync() for the synchronous, blocking version of this constructor. + */ +void +background_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_BACKGROUND_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.background", NULL); +} + +/** + * background_proxy_new_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to background_proxy_new(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with background_proxy_new(). + * + * Returns: (transfer full) (type BackgroundProxy): The constructed proxy object or %NULL if @error is set. + */ +Background * +background_proxy_new_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return BACKGROUND (ret); + else + return NULL; +} + +/** + * background_proxy_new_sync: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Synchronously creates a proxy for the D-Bus interface cn.kylinos.background. See g_dbus_proxy_new_sync() for more details. + * + * The calling thread is blocked until a reply is received. + * + * See background_proxy_new() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type BackgroundProxy): The constructed proxy object or %NULL if @error is set. + */ +Background * +background_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_BACKGROUND_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.background", NULL); + if (ret != NULL) + return BACKGROUND (ret); + else + return NULL; +} + + +/** + * background_proxy_new_for_bus: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Like background_proxy_new() but takes a #GBusType instead of a #GDBusConnection. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call background_proxy_new_for_bus_finish() to get the result of the operation. + * + * See background_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. + */ +void +background_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_BACKGROUND_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.background", NULL); +} + +/** + * background_proxy_new_for_bus_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to background_proxy_new_for_bus(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with background_proxy_new_for_bus(). + * + * Returns: (transfer full) (type BackgroundProxy): The constructed proxy object or %NULL if @error is set. + */ +Background * +background_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return BACKGROUND (ret); + else + return NULL; +} + +/** + * background_proxy_new_for_bus_sync: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Like background_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. + * + * The calling thread is blocked until a reply is received. + * + * See background_proxy_new_for_bus() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type BackgroundProxy): The constructed proxy object or %NULL if @error is set. + */ +Background * +background_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_BACKGROUND_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.background", NULL); + if (ret != NULL) + return BACKGROUND (ret); + else + return NULL; +} + + +/* ------------------------------------------------------------------------ */ + +/** + * BackgroundSkeleton: + * + * The #BackgroundSkeleton structure contains only private data and should only be accessed using the provided API. + */ + +/** + * BackgroundSkeletonClass: + * @parent_class: The parent class. + * + * Class structure for #BackgroundSkeleton. + */ + +struct _BackgroundSkeletonPrivate +{ + GValue *properties; + GList *changed_properties; + GSource *changed_properties_idle_source; + GMainContext *context; + GMutex lock; +}; + +static void +_background_skeleton_handle_method_call ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name, + const gchar *method_name, + GVariant *parameters, + GDBusMethodInvocation *invocation, + gpointer user_data) +{ + BackgroundSkeleton *skeleton = BACKGROUND_SKELETON (user_data); + _ExtendedGDBusMethodInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + guint num_extra; + gsize n; + guint signal_id; + GValue return_value = G_VALUE_INIT; + info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); + g_assert (info != NULL); + num_params = g_variant_n_children (parameters); + num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); + n = 0; + g_value_init (¶mv[n], TYPE_BACKGROUND); + g_value_set_object (¶mv[n++], skeleton); + g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); + g_value_set_object (¶mv[n++], invocation); + if (info->pass_fdlist) + { +#ifdef G_OS_UNIX + g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); + g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); +#else + g_assert_not_reached (); +#endif + } + g_variant_iter_init (&iter, parameters); + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_BACKGROUND); + g_value_init (&return_value, G_TYPE_BOOLEAN); + g_signal_emitv (paramv, signal_id, 0, &return_value); + if (!g_value_get_boolean (&return_value)) + g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); + g_value_unset (&return_value); + for (n = 0; n < num_params + num_extra; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static GVariant * +_background_skeleton_handle_get_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GError **error, + gpointer user_data) +{ + BackgroundSkeleton *skeleton = BACKGROUND_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + GVariant *ret; + ret = NULL; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_background_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + g_value_init (&value, pspec->value_type); + g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); + ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); + g_value_unset (&value); + } + return ret; +} + +static gboolean +_background_skeleton_handle_set_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GVariant *variant, + GError **error, + gpointer user_data) +{ + BackgroundSkeleton *skeleton = BACKGROUND_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + gboolean ret; + ret = FALSE; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_background_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + if (info->use_gvariant) + g_value_set_variant (&value, variant); + else + g_dbus_gvariant_to_gvalue (variant, &value); + g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); + g_value_unset (&value); + ret = TRUE; + } + return ret; +} + +static const GDBusInterfaceVTable _background_skeleton_vtable = +{ + _background_skeleton_handle_method_call, + _background_skeleton_handle_get_property, + _background_skeleton_handle_set_property, + {NULL} +}; + +static GDBusInterfaceInfo * +background_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return background_interface_info (); +} + +static GDBusInterfaceVTable * +background_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return (GDBusInterfaceVTable *) &_background_skeleton_vtable; +} + +static GVariant * +background_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) +{ + BackgroundSkeleton *skeleton = BACKGROUND_SKELETON (_skeleton); + + GVariantBuilder builder; + guint n; + g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); + if (_background_interface_info.parent_struct.properties == NULL) + goto out; + for (n = 0; _background_interface_info.parent_struct.properties[n] != NULL; n++) + { + GDBusPropertyInfo *info = _background_interface_info.parent_struct.properties[n]; + if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) + { + GVariant *value; + value = _background_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "cn.kylinos.background", info->name, NULL, skeleton); + if (value != NULL) + { + g_variant_take_ref (value); + g_variant_builder_add (&builder, "{sv}", info->name, value); + g_variant_unref (value); + } + } + } +out: + return g_variant_builder_end (&builder); +} + +static void +background_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) +{ +} + +static void background_skeleton_iface_init (BackgroundIface *iface); +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (BackgroundSkeleton, background_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_ADD_PRIVATE (BackgroundSkeleton) + G_IMPLEMENT_INTERFACE (TYPE_BACKGROUND, background_skeleton_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (BackgroundSkeleton, background_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_IMPLEMENT_INTERFACE (TYPE_BACKGROUND, background_skeleton_iface_init)) + +#endif +static void +background_skeleton_finalize (GObject *object) +{ + BackgroundSkeleton *skeleton = BACKGROUND_SKELETON (object); + g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); + if (skeleton->priv->changed_properties_idle_source != NULL) + g_source_destroy (skeleton->priv->changed_properties_idle_source); + g_main_context_unref (skeleton->priv->context); + g_mutex_clear (&skeleton->priv->lock); + G_OBJECT_CLASS (background_skeleton_parent_class)->finalize (object); +} + +static void +background_skeleton_init (BackgroundSkeleton *skeleton) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + skeleton->priv = background_skeleton_get_instance_private (skeleton); +#else + skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_BACKGROUND_SKELETON, BackgroundSkeletonPrivate); +#endif + + g_mutex_init (&skeleton->priv->lock); + skeleton->priv->context = g_main_context_ref_thread_default (); +} + +static void +background_skeleton_class_init (BackgroundSkeletonClass *klass) +{ + GObjectClass *gobject_class; + GDBusInterfaceSkeletonClass *skeleton_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = background_skeleton_finalize; + + skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); + skeleton_class->get_info = background_skeleton_dbus_interface_get_info; + skeleton_class->get_properties = background_skeleton_dbus_interface_get_properties; + skeleton_class->flush = background_skeleton_dbus_interface_flush; + skeleton_class->get_vtable = background_skeleton_dbus_interface_get_vtable; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (BackgroundSkeletonPrivate)); +#endif +} + +static void +background_skeleton_iface_init (BackgroundIface *iface) +{ +} + +/** + * background_skeleton_new: + * + * Creates a skeleton object for the D-Bus interface cn.kylinos.background. + * + * Returns: (transfer full) (type BackgroundSkeleton): The skeleton object. + */ +Background * +background_skeleton_new (void) +{ + return BACKGROUND (g_object_new (TYPE_BACKGROUND_SKELETON, NULL)); +} + diff --git a/src/personal/background/background-generated.h b/src/personal/background/background-generated.h new file mode 100644 index 0000000..dac08f3 --- /dev/null +++ b/src/personal/background/background-generated.h @@ -0,0 +1,244 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +G_BEGIN_DECLS + + +/* ------------------------------------------------------------------------ */ +/* Declarations for cn.kylinos.background */ + +#define TYPE_BACKGROUND (background_get_type ()) +#define BACKGROUND(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_BACKGROUND, Background)) +#define IS_BACKGROUND(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_BACKGROUND)) +#define BACKGROUND_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), TYPE_BACKGROUND, BackgroundIface)) + +struct _Background; +typedef struct _Background Background; +typedef struct _BackgroundIface BackgroundIface; + +struct _BackgroundIface +{ + GTypeInterface parent_iface; + + gboolean (*handle_transfer_bool_value) ( + Background *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + + gboolean (*handle_transfer_int_value) ( + Background *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + + gboolean (*handle_transfer_string_value) ( + Background *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + +}; + +GType background_get_type (void) G_GNUC_CONST; + +GDBusInterfaceInfo *background_interface_info (void); +guint background_override_properties (GObjectClass *klass, guint property_id_begin); + + +/* D-Bus method call completion functions: */ +void background_complete_transfer_bool_value ( + Background *object, + GDBusMethodInvocation *invocation); + +void background_complete_transfer_string_value ( + Background *object, + GDBusMethodInvocation *invocation); + +void background_complete_transfer_int_value ( + Background *object, + GDBusMethodInvocation *invocation); + + + +/* D-Bus method calls: */ +void background_call_transfer_bool_value ( + Background *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean background_call_transfer_bool_value_finish ( + Background *proxy, + GAsyncResult *res, + GError **error); + +gboolean background_call_transfer_bool_value_sync ( + Background *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + +void background_call_transfer_string_value ( + Background *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean background_call_transfer_string_value_finish ( + Background *proxy, + GAsyncResult *res, + GError **error); + +gboolean background_call_transfer_string_value_sync ( + Background *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + +void background_call_transfer_int_value ( + Background *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean background_call_transfer_int_value_finish ( + Background *proxy, + GAsyncResult *res, + GError **error); + +gboolean background_call_transfer_int_value_sync ( + Background *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + + + +/* ---- */ + +#define TYPE_BACKGROUND_PROXY (background_proxy_get_type ()) +#define BACKGROUND_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_BACKGROUND_PROXY, BackgroundProxy)) +#define BACKGROUND_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_BACKGROUND_PROXY, BackgroundProxyClass)) +#define BACKGROUND_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_BACKGROUND_PROXY, BackgroundProxyClass)) +#define IS_BACKGROUND_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_BACKGROUND_PROXY)) +#define IS_BACKGROUND_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_BACKGROUND_PROXY)) + +typedef struct _BackgroundProxy BackgroundProxy; +typedef struct _BackgroundProxyClass BackgroundProxyClass; +typedef struct _BackgroundProxyPrivate BackgroundProxyPrivate; + +struct _BackgroundProxy +{ + /*< private >*/ + GDBusProxy parent_instance; + BackgroundProxyPrivate *priv; +}; + +struct _BackgroundProxyClass +{ + GDBusProxyClass parent_class; +}; + +GType background_proxy_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (BackgroundProxy, g_object_unref) +#endif + +void background_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Background *background_proxy_new_finish ( + GAsyncResult *res, + GError **error); +Background *background_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + +void background_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Background *background_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error); +Background *background_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + + +/* ---- */ + +#define TYPE_BACKGROUND_SKELETON (background_skeleton_get_type ()) +#define BACKGROUND_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_BACKGROUND_SKELETON, BackgroundSkeleton)) +#define BACKGROUND_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_BACKGROUND_SKELETON, BackgroundSkeletonClass)) +#define BACKGROUND_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_BACKGROUND_SKELETON, BackgroundSkeletonClass)) +#define IS_BACKGROUND_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_BACKGROUND_SKELETON)) +#define IS_BACKGROUND_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_BACKGROUND_SKELETON)) + +typedef struct _BackgroundSkeleton BackgroundSkeleton; +typedef struct _BackgroundSkeletonClass BackgroundSkeletonClass; +typedef struct _BackgroundSkeletonPrivate BackgroundSkeletonPrivate; + +struct _BackgroundSkeleton +{ + /*< private >*/ + GDBusInterfaceSkeleton parent_instance; + BackgroundSkeletonPrivate *priv; +}; + +struct _BackgroundSkeletonClass +{ + GDBusInterfaceSkeletonClass parent_class; +}; + +GType background_skeleton_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (BackgroundSkeleton, g_object_unref) +#endif + +Background *background_skeleton_new (void); + + +G_END_DECLS + +#endif /* __BACKGROUND_GENERATED_H__ */ diff --git a/src/personal/background/kylin-background-interface.c b/src/personal/background/kylin-background-interface.c new file mode 100644 index 0000000..22703a8 --- /dev/null +++ b/src/personal/background/kylin-background-interface.c @@ -0,0 +1,267 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#define DB "draw-background" +#define SDI "show-desktop-icons" +#define BF "background-fade" +#define POPT "picture-options" +#define PF "picture-filename" +#define POPA "picture-opacity" +#define PC "primary-color" +#define SC "secondary-color" +#define CST "color-shading-type" + +static GMainLoop *pLoop = NULL; +static GDBusConnection *pConnection = NULL; +static Background *pProxy = NULL; + +void kylin_personal_personal_drawbackground(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=DB; + arg=g_variant_new("(sb)", key, in_arg); + background_call_transfer_bool_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_personal_drawbackground. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_personal_showdesktopicons(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=SDI; + arg=g_variant_new("(sb)", key, in_arg); + background_call_transfer_bool_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_personal_showdesktopicons. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_personal_backgroundfade(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=BF; + arg=g_variant_new("(sb)", key, in_arg); + background_call_transfer_bool_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_personal_backgroundfade. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_personal_pictureoptions(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=POPT; + arg=g_variant_new("(si)",key,in_arg); + background_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_personal_pictureoptions. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; + +} + +void kylin_personal_personal_picturefilename(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=PF; + arg=g_variant_new("(ss)", key, in_arg); + background_call_transfer_string_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_personal_picturefilename. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_personal_pictureopacity(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=POPA; + arg=g_variant_new("(si)",key,in_arg); + background_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_personal_pictureopacity. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_personal_primarycolor(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=PC; + arg=g_variant_new("(ss)", key, in_arg); + background_call_transfer_string_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_personal_primarycolor. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_personal_secondarycolor(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=SC; + arg=g_variant_new("(ss)", key, in_arg); + background_call_transfer_string_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_personal_secondarycolor. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_personal_colorshadingtype(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=CST; + arg=g_variant_new("(si)",key,in_arg); + background_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_personal_colorshadingtype. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void *run(void* arg) +{ + /** start the main event loop which manages all available sources of events */ + g_main_loop_run(pLoop); + + return ((void*)0); +} + +int thread_create(void) + { + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if(0 != err){ + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; + } + +bool InitDBusBackground(void) + { + bool bRet = TRUE; + GError *pConnError = NULL; + GError *pProxyError = NULL; + + do{ + bRet = TRUE; + pLoop = g_main_loop_new(NULL, FALSE); /** create main loop, but do not start it.*/ + + /** First step: get a connection */ + pConnection = g_bus_get_sync(BACKGROUND_BUS, NULL, &pConnError); + + if (NULL == pConnError){ + /** Second step: try to get a connection to the given bus.*/ + pProxy = background_proxy_new_sync(pConnection, + G_DBUS_PROXY_FLAGS_NONE, + BACKGROUND_BUS_NAME, + BACKGROUND_OBJECT_PATH, + NULL, + &pProxyError); + if (0 == pProxy){ + print_error("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message); + g_error_free(pProxyError); + bRet = FALSE; + } + + + } + else{ + print_error("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message); + g_error_free(pConnError); + bRet = FALSE; + } + }while(FALSE == bRet); + + thread_create(); + + return bRet; + } + +bool DeInitDBusBackground(void) +{ + bool bRet = FALSE; + + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} diff --git a/src/personal/background/kylin-background-interface.h b/src/personal/background/kylin-background-interface.h new file mode 100644 index 0000000..1f83949 --- /dev/null +++ b/src/personal/background/kylin-background-interface.h @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +//Initialize the DBus Communication +bool InitDBusBackground(void); + +//Delete the DBus Communication +bool DeInitDBusBackground(void); + +/* + * Draw Desktop Background. + */ +void kylin_personal_personal_drawbackground(const bool in_arg); + +/* + * Show Desktop Icons. + */ +void kylin_personal_personal_showdesktopicons(const bool in_arg); + +/* + * Fade the background on change. + * If set to true, then MATE will change the desktop background with a fading effect. + */ +void kylin_personal_personal_backgroundfade(const bool in_arg); + +/* + * Determines how the image set by wallpaper_filename is rendered. + * Possible values are: + * @in_arg is equal to 0, "wallpaper"; + * @in_arg is equal to 1, "zoom"; + * @in_arg is equal to 2, "centered"; + * @in_arg is equal to 3, "scaled"; + * @in_arg is equal to 4, "stretched"; + * @in_arg is equal to 5, "spanned". + */ +void kylin_personal_personal_pictureoptions(const int in_arg); + +/* + * File to use for the background image. + */ +void kylin_personal_personal_picturefilename(const char *in_arg); + +/* + * Opacity with which to draw the background picture. + */ +void kylin_personal_personal_pictureopacity(const int in_arg); + +/* + * Left or Top color when drawing gradients, or the solid color. + */ +void kylin_personal_personal_primarycolor(const char *in_arg); + +/* + * Right or Bottom color when drawing gradients, not used for solid color. + */ +void kylin_personal_personal_secondarycolor(const char *in_arg); + +/* + * How to shade the background color. + * Possible values are: + * @in_arg is equal to 0, "solid"; + * @in_arg is equal to 1, "horizontal-gradient"; + * @in_arg is equal to 2, "vertical-gradient". + */ +void kylin_personal_personal_colorshadingtype(const int in_arg); + +#ifdef __cplusplus +} +#endif + +#endif + + + + + + + + + + + + + diff --git a/src/personal/background/kylin-background-server.c b/src/personal/background/kylin-background-server.c new file mode 100644 index 0000000..fdf3848 --- /dev/null +++ b/src/personal/background/kylin-background-server.c @@ -0,0 +1,223 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include "background-dbus.h" +#include "src/common/kylin-gsettings-set.h" +#include "src/common/kylin-print.h" +#include "background-generated.h" +#include +#include + +#define schemaID "org.mate.background" + +static GMainLoop *pLoop = NULL; +static Background *pSkeleton = NULL; + +static gboolean kylin_set_bool(Background* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gboolean value; + gint i; + g_variant_get(in_arg, "(sb)", &key, &value); + if(value==false)i=0; + else i=1; + + background_complete_transfer_bool_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + gsettings_set_boolean(setting, key, value); + Dec_ref(setting); + + print_info("(%s, %d)\n", key, i); + + return TRUE; +} + +static gboolean kylin_set_int(Background* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gint value; + g_variant_get(in_arg, "(si)", &key, &value); + + background_complete_transfer_int_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + if(strcmp(key,"picture-options")==0||strcmp(key,"color-shading-type")==0) + gsettings_set_enum(setting, key, value); + else gsettings_set_int(setting, key, value); + Dec_ref(setting); + + print_info("(%s, %d)\n", key, value); + + return TRUE; +} + +static gboolean kylin_set_char(Background* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gchar *value=NULL; + g_variant_get(in_arg, "(ss)", &key, &value); + + background_complete_transfer_string_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + gsettings_set_string(setting, key, value); + Dec_ref(setting); + + print_info("(%s, %s)\n", key, value); + + return TRUE; +} + +static void bus_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + + GError *pError = NULL; + + /** Second step: Try to get a connection to the given bus. */ + pSkeleton = background_skeleton_new(); + + /** Third step: Attach to dbus signals. */ + (void) g_signal_connect(pSkeleton, "handle-transfer-bool-value", G_CALLBACK(kylin_set_bool), NULL); + (void) g_signal_connect(pSkeleton, "handle-transfer-int-value", G_CALLBACK(kylin_set_int), NULL); + (void) g_signal_connect(pSkeleton, "handle-transfer-string-value", G_CALLBACK(kylin_set_char), NULL); + + /** Fourth step: Export interface skeleton. */ + (void)g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(pSkeleton), + connection, + BACKGROUND_OBJECT_PATH, + &pError); + + if(pError != NULL){ + print_error("Error: Failed to export object. Reason: %s.\n", pError->message); + g_error_free(pError); + g_main_loop_quit(pLoop); + } +} + +static void name_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + print_info("name_acquired_cb call, Acquired bus name: %s.\n", BACKGROUND_BUS_NAME); +} + +static void name_lost_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + if(connection == NULL) + { + print_error("name_lost_cb call, Error: Failed to connect to dbus.\n"); + } + else + { + print_error("name_lost_cb call, Error: Failed to obtain bus name: %s.\n", BACKGROUND_BUS_NAME); + } + + g_main_loop_quit(pLoop); +} + +void* run(void* para) +{ + /** Start the Main Event Loop which manages all available sources of events */ + g_main_loop_run( pLoop ); + + return ((void*)0); +} + +int thread_create(void) +{ + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if (err != 0) + { + + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; +} + +bool InitDBusCommunicationServer(void) +{ + bool bRet = TRUE; + + g_print("InitDBusCommunicationServer: Server started.\n"); + + /** create main loop, but do not start it. */ + pLoop = g_main_loop_new(NULL, FALSE); + + /** first step: connect to dbus */ + (void)g_bus_own_name(BACKGROUND_BUS, + BACKGROUND_BUS_NAME, + G_BUS_NAME_OWNER_FLAGS_NONE, + &bus_acquired_cb, + &name_acquired_cb, + &name_lost_cb, + NULL, + NULL); + + thread_create(); + + return bRet; +} + +bool DeinitDBusCommunicationServer(void) +{ + bool bRet = FALSE; + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} + +int main(void) +{ + InitDBusCommunicationServer(); + + sleep(100); + + DeinitDBusCommunicationServer(); + return 0; +} diff --git a/src/personal/desktop/Makefile.am b/src/personal/desktop/Makefile.am new file mode 100644 index 0000000..f263d53 --- /dev/null +++ b/src/personal/desktop/Makefile.am @@ -0,0 +1,55 @@ +COMM_PRINT= -L$(top_srcdir)/src/common -lukui-print +COMM_GSETTINGS= -L$(top_srcdir)/src/common -lukui-gsettings + +#generate the .c and .h file which used by client and server side by XML file +#$(top_srcdir) represents the top-level directory of the project +DESC_XML = $(top_srcdir)/data/cn.kylinos.desktop.xml +GENERATED_CH = desktop-generated + +desktop-generated.h desktop-generated.c: $(DESC_XML) + gdbus-codegen --interface-prefix cn.kylinos. --generate-c-code $(GENERATED_CH) $(DESC_XML) + +#Generata binary file +lib_LTLIBRARIES = libukui-desktopclient.la + +#gcc -wall: displays all the errors and warning information when compiling +#gcc -g: add the debugging code when compiling +COMM_CFS = -Wall -g + +#Add the dependent source file for libdesktopclient.la +#desktop-generated.c must be front of kylin-desktop-interface.c +libukui_desktopclient_la_SOURCES = desktop-generated.c kylin-desktop-interface.c \ + $(NULL) + +#The header files that need to be installed +include_HEADERS= kylin-desktop-interface.h \ + $(NULL) + +#Additional C compiler flags +libukui_desktopclient_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_desktopclient_la_LDFLAGS= $(COMM_PRINT) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Generata binary file +bin_PROGRAMS = ukui-desktopserver + +#Add the dependent source file for desktopserver +ukui_desktopserver_SOURCES = \ + desktop-generated.h desktop-generated.c \ + kylin-desktop-server.c \ + $(NULL) + +#Additional C compiler flags +ukui_desktopserver_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +ukui_desktopserver_LDFLAGS= $(COMM_PRINT) $(COMM_GSETTINGS) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) diff --git a/src/personal/desktop/desktop-dbus.h b/src/personal/desktop/desktop-dbus.h new file mode 100644 index 0000000..67ab3cc --- /dev/null +++ b/src/personal/desktop/desktop-dbus.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 /* Bus define */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define DESKTOP_BUS G_BUS_TYPE_SESSION +#define DESKTOP_BUS_NAME "cn.kylinos.desktop" +#define DESKTOP_OBJECT_PATH "/cn/kylinos/desktop" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/personal/desktop/desktop-generated.c b/src/personal/desktop/desktop-generated.c new file mode 100644 index 0000000..5e76089 --- /dev/null +++ b/src/personal/desktop/desktop-generated.c @@ -0,0 +1,1392 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#ifdef G_OS_UNIX +# include +#endif + +typedef struct +{ + GDBusArgInfo parent_struct; + gboolean use_gvariant; +} _ExtendedGDBusArgInfo; + +typedef struct +{ + GDBusMethodInfo parent_struct; + const gchar *signal_name; + gboolean pass_fdlist; +} _ExtendedGDBusMethodInfo; + +typedef struct +{ + GDBusSignalInfo parent_struct; + const gchar *signal_name; +} _ExtendedGDBusSignalInfo; + +typedef struct +{ + GDBusPropertyInfo parent_struct; + const gchar *hyphen_name; + guint use_gvariant : 1; + guint emits_changed_signal : 1; +} _ExtendedGDBusPropertyInfo; + +typedef struct +{ + GDBusInterfaceInfo parent_struct; + const gchar *hyphen_name; +} _ExtendedGDBusInterfaceInfo; + +typedef struct +{ + const _ExtendedGDBusPropertyInfo *info; + guint prop_id; + GValue orig_value; /* the value before the change */ +} ChangedProperty; + +static void +_changed_property_free (ChangedProperty *data) +{ + g_value_unset (&data->orig_value); + g_free (data); +} + +static gboolean +_g_strv_equal0 (gchar **a, gchar **b) +{ + gboolean ret = FALSE; + guint n; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + if (g_strv_length (a) != g_strv_length (b)) + goto out; + for (n = 0; a[n] != NULL; n++) + if (g_strcmp0 (a[n], b[n]) != 0) + goto out; + ret = TRUE; +out: + return ret; +} + +static gboolean +_g_variant_equal0 (GVariant *a, GVariant *b) +{ + gboolean ret = FALSE; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + ret = g_variant_equal (a, b); +out: + return ret; +} + +G_GNUC_UNUSED static gboolean +_g_value_equal (const GValue *a, const GValue *b) +{ + gboolean ret = FALSE; + g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); + switch (G_VALUE_TYPE (a)) + { + case G_TYPE_BOOLEAN: + ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); + break; + case G_TYPE_UCHAR: + ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); + break; + case G_TYPE_INT: + ret = (g_value_get_int (a) == g_value_get_int (b)); + break; + case G_TYPE_UINT: + ret = (g_value_get_uint (a) == g_value_get_uint (b)); + break; + case G_TYPE_INT64: + ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); + break; + case G_TYPE_UINT64: + ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); + break; + case G_TYPE_DOUBLE: + { + /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ + gdouble da = g_value_get_double (a); + gdouble db = g_value_get_double (b); + ret = memcmp (&da, &db, sizeof (gdouble)) == 0; + } + break; + case G_TYPE_STRING: + ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); + break; + case G_TYPE_VARIANT: + ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); + break; + default: + if (G_VALUE_TYPE (a) == G_TYPE_STRV) + ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); + else + g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); + break; + } + return ret; +} + +/* ------------------------------------------------------------------------ + * Code for interface cn.kylinos.desktop + * ------------------------------------------------------------------------ + */ + +/** + * SECTION:Desktop + * @title: Desktop + * @short_description: Generated C code for the cn.kylinos.desktop D-Bus interface + * + * This section contains code for working with the cn.kylinos.desktop D-Bus interface in C. + */ + +/* ---- Introspection data for cn.kylinos.desktop ---- */ + +static const _ExtendedGDBusArgInfo _desktop_method_info_transfer_bool_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(sb)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _desktop_method_info_transfer_bool_value_IN_ARG_pointers[] = +{ + &_desktop_method_info_transfer_bool_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _desktop_method_info_transfer_bool_value = +{ + { + -1, + (gchar *) "TransferBoolValue", + (GDBusArgInfo **) &_desktop_method_info_transfer_bool_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-bool-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _desktop_method_info_transfer_string_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(ss)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _desktop_method_info_transfer_string_value_IN_ARG_pointers[] = +{ + &_desktop_method_info_transfer_string_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _desktop_method_info_transfer_string_value = +{ + { + -1, + (gchar *) "TransferStringValue", + (GDBusArgInfo **) &_desktop_method_info_transfer_string_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-string-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _desktop_method_info_transfer_int_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(si)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _desktop_method_info_transfer_int_value_IN_ARG_pointers[] = +{ + &_desktop_method_info_transfer_int_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _desktop_method_info_transfer_int_value = +{ + { + -1, + (gchar *) "TransferIntValue", + (GDBusArgInfo **) &_desktop_method_info_transfer_int_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-int-value", + FALSE +}; + +static const GDBusMethodInfo * const _desktop_method_info_pointers[] = +{ + &_desktop_method_info_transfer_bool_value.parent_struct, + &_desktop_method_info_transfer_string_value.parent_struct, + &_desktop_method_info_transfer_int_value.parent_struct, + NULL +}; + +static const _ExtendedGDBusInterfaceInfo _desktop_interface_info = +{ + { + -1, + (gchar *) "cn.kylinos.desktop", + (GDBusMethodInfo **) &_desktop_method_info_pointers, + NULL, + NULL, + NULL + }, + "desktop", +}; + + +/** + * desktop_interface_info: + * + * Gets a machine-readable description of the cn.kylinos.desktop D-Bus interface. + * + * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. + */ +GDBusInterfaceInfo * +desktop_interface_info (void) +{ + return (GDBusInterfaceInfo *) &_desktop_interface_info.parent_struct; +} + +/** + * desktop_override_properties: + * @klass: The class structure for a #GObject derived class. + * @property_id_begin: The property id to assign to the first overridden property. + * + * Overrides all #GObject properties in the #Desktop interface for a concrete class. + * The properties are overridden in the order they are defined. + * + * Returns: The last property id. + */ +guint +desktop_override_properties (GObjectClass *klass, guint property_id_begin) +{ + return property_id_begin - 1; +} + + + +/** + * Desktop: + * + * Abstract interface type for the D-Bus interface cn.kylinos.desktop. + */ + +/** + * DesktopIface: + * @parent_iface: The parent interface. + * @handle_transfer_bool_value: Handler for the #Desktop::handle-transfer-bool-value signal. + * @handle_transfer_int_value: Handler for the #Desktop::handle-transfer-int-value signal. + * @handle_transfer_string_value: Handler for the #Desktop::handle-transfer-string-value signal. + * + * Virtual table for the D-Bus interface cn.kylinos.desktop. + */ + +typedef DesktopIface DesktopInterface; +G_DEFINE_INTERFACE (Desktop, desktop, G_TYPE_OBJECT) + +static void +desktop_default_init (DesktopIface *iface) +{ + /* GObject signals for incoming D-Bus method calls: */ + /** + * Desktop::handle-transfer-bool-value: + * @object: A #Desktop. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferBoolValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call desktop_complete_transfer_bool_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-bool-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (DesktopIface, handle_transfer_bool_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Desktop::handle-transfer-string-value: + * @object: A #Desktop. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferStringValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call desktop_complete_transfer_string_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-string-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (DesktopIface, handle_transfer_string_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Desktop::handle-transfer-int-value: + * @object: A #Desktop. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferIntValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call desktop_complete_transfer_int_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-int-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (DesktopIface, handle_transfer_int_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + +} + +/** + * desktop_call_transfer_bool_value: + * @proxy: A #DesktopProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferBoolValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call desktop_call_transfer_bool_value_finish() to get the result of the operation. + * + * See desktop_call_transfer_bool_value_sync() for the synchronous, blocking version of this method. + */ +void +desktop_call_transfer_bool_value ( + Desktop *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * desktop_call_transfer_bool_value_finish: + * @proxy: A #DesktopProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to desktop_call_transfer_bool_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with desktop_call_transfer_bool_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +desktop_call_transfer_bool_value_finish ( + Desktop *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * desktop_call_transfer_bool_value_sync: + * @proxy: A #DesktopProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferBoolValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See desktop_call_transfer_bool_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +desktop_call_transfer_bool_value_sync ( + Desktop *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferBoolValue", + g_variant_new ("(@(sb))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * desktop_call_transfer_string_value: + * @proxy: A #DesktopProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferStringValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call desktop_call_transfer_string_value_finish() to get the result of the operation. + * + * See desktop_call_transfer_string_value_sync() for the synchronous, blocking version of this method. + */ +void +desktop_call_transfer_string_value ( + Desktop *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferStringValue", + g_variant_new ("(@(ss))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * desktop_call_transfer_string_value_finish: + * @proxy: A #DesktopProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to desktop_call_transfer_string_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with desktop_call_transfer_string_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +desktop_call_transfer_string_value_finish ( + Desktop *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * desktop_call_transfer_string_value_sync: + * @proxy: A #DesktopProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferStringValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See desktop_call_transfer_string_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +desktop_call_transfer_string_value_sync ( + Desktop *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferStringValue", + g_variant_new ("(@(ss))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * desktop_call_transfer_int_value: + * @proxy: A #DesktopProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferIntValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call desktop_call_transfer_int_value_finish() to get the result of the operation. + * + * See desktop_call_transfer_int_value_sync() for the synchronous, blocking version of this method. + */ +void +desktop_call_transfer_int_value ( + Desktop *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * desktop_call_transfer_int_value_finish: + * @proxy: A #DesktopProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to desktop_call_transfer_int_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with desktop_call_transfer_int_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +desktop_call_transfer_int_value_finish ( + Desktop *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * desktop_call_transfer_int_value_sync: + * @proxy: A #DesktopProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferIntValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See desktop_call_transfer_int_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +desktop_call_transfer_int_value_sync ( + Desktop *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * desktop_complete_transfer_bool_value: + * @object: A #Desktop. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferBoolValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +desktop_complete_transfer_bool_value ( + Desktop *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/** + * desktop_complete_transfer_string_value: + * @object: A #Desktop. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferStringValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +desktop_complete_transfer_string_value ( + Desktop *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/** + * desktop_complete_transfer_int_value: + * @object: A #Desktop. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferIntValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +desktop_complete_transfer_int_value ( + Desktop *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/* ------------------------------------------------------------------------ */ + +/** + * DesktopProxy: + * + * The #DesktopProxy structure contains only private data and should only be accessed using the provided API. + */ + +/** + * DesktopProxyClass: + * @parent_class: The parent class. + * + * Class structure for #DesktopProxy. + */ + +struct _DesktopProxyPrivate +{ + GData *qdata; +}; + +static void desktop_proxy_iface_init (DesktopIface *iface); + +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (DesktopProxy, desktop_proxy, G_TYPE_DBUS_PROXY, + G_ADD_PRIVATE (DesktopProxy) + G_IMPLEMENT_INTERFACE (TYPE_DESKTOP, desktop_proxy_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (DesktopProxy, desktop_proxy, G_TYPE_DBUS_PROXY, + G_IMPLEMENT_INTERFACE (TYPE_DESKTOP, desktop_proxy_iface_init)) + +#endif +static void +desktop_proxy_finalize (GObject *object) +{ + DesktopProxy *proxy = DESKTOP_PROXY (object); + g_datalist_clear (&proxy->priv->qdata); + G_OBJECT_CLASS (desktop_proxy_parent_class)->finalize (object); +} + +static void +desktop_proxy_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +desktop_proxy_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +desktop_proxy_g_signal (GDBusProxy *proxy, + const gchar *sender_name G_GNUC_UNUSED, + const gchar *signal_name, + GVariant *parameters) +{ + _ExtendedGDBusSignalInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + gsize n; + guint signal_id; + info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_desktop_interface_info.parent_struct, signal_name); + if (info == NULL) + return; + num_params = g_variant_n_children (parameters); + paramv = g_new0 (GValue, num_params + 1); + g_value_init (¶mv[0], TYPE_DESKTOP); + g_value_set_object (¶mv[0], proxy); + g_variant_iter_init (&iter, parameters); + n = 1; + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_DESKTOP); + g_signal_emitv (paramv, signal_id, 0, NULL); + for (n = 0; n < num_params + 1; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static void +desktop_proxy_g_properties_changed (GDBusProxy *_proxy, + GVariant *changed_properties, + const gchar *const *invalidated_properties) +{ + DesktopProxy *proxy = DESKTOP_PROXY (_proxy); + guint n; + const gchar *key; + GVariantIter *iter; + _ExtendedGDBusPropertyInfo *info; + g_variant_get (changed_properties, "a{sv}", &iter); + while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_desktop_interface_info.parent_struct, key); + g_datalist_remove_data (&proxy->priv->qdata, key); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } + g_variant_iter_free (iter); + for (n = 0; invalidated_properties[n] != NULL; n++) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_desktop_interface_info.parent_struct, invalidated_properties[n]); + g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } +} + +static void +desktop_proxy_init (DesktopProxy *proxy) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + proxy->priv = desktop_proxy_get_instance_private (proxy); +#else + proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, TYPE_DESKTOP_PROXY, DesktopProxyPrivate); +#endif + + g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), desktop_interface_info ()); +} + +static void +desktop_proxy_class_init (DesktopProxyClass *klass) +{ + GObjectClass *gobject_class; + GDBusProxyClass *proxy_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = desktop_proxy_finalize; + gobject_class->get_property = desktop_proxy_get_property; + gobject_class->set_property = desktop_proxy_set_property; + + proxy_class = G_DBUS_PROXY_CLASS (klass); + proxy_class->g_signal = desktop_proxy_g_signal; + proxy_class->g_properties_changed = desktop_proxy_g_properties_changed; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (DesktopProxyPrivate)); +#endif +} + +static void +desktop_proxy_iface_init (DesktopIface *iface) +{ +} + +/** + * desktop_proxy_new: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Asynchronously creates a proxy for the D-Bus interface cn.kylinos.desktop. See g_dbus_proxy_new() for more details. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call desktop_proxy_new_finish() to get the result of the operation. + * + * See desktop_proxy_new_sync() for the synchronous, blocking version of this constructor. + */ +void +desktop_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_DESKTOP_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.desktop", NULL); +} + +/** + * desktop_proxy_new_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to desktop_proxy_new(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with desktop_proxy_new(). + * + * Returns: (transfer full) (type DesktopProxy): The constructed proxy object or %NULL if @error is set. + */ +Desktop * +desktop_proxy_new_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return DESKTOP (ret); + else + return NULL; +} + +/** + * desktop_proxy_new_sync: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Synchronously creates a proxy for the D-Bus interface cn.kylinos.desktop. See g_dbus_proxy_new_sync() for more details. + * + * The calling thread is blocked until a reply is received. + * + * See desktop_proxy_new() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type DesktopProxy): The constructed proxy object or %NULL if @error is set. + */ +Desktop * +desktop_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_DESKTOP_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.desktop", NULL); + if (ret != NULL) + return DESKTOP (ret); + else + return NULL; +} + + +/** + * desktop_proxy_new_for_bus: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Like desktop_proxy_new() but takes a #GBusType instead of a #GDBusConnection. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call desktop_proxy_new_for_bus_finish() to get the result of the operation. + * + * See desktop_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. + */ +void +desktop_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_DESKTOP_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.desktop", NULL); +} + +/** + * desktop_proxy_new_for_bus_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to desktop_proxy_new_for_bus(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with desktop_proxy_new_for_bus(). + * + * Returns: (transfer full) (type DesktopProxy): The constructed proxy object or %NULL if @error is set. + */ +Desktop * +desktop_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return DESKTOP (ret); + else + return NULL; +} + +/** + * desktop_proxy_new_for_bus_sync: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Like desktop_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. + * + * The calling thread is blocked until a reply is received. + * + * See desktop_proxy_new_for_bus() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type DesktopProxy): The constructed proxy object or %NULL if @error is set. + */ +Desktop * +desktop_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_DESKTOP_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.desktop", NULL); + if (ret != NULL) + return DESKTOP (ret); + else + return NULL; +} + + +/* ------------------------------------------------------------------------ */ + +/** + * DesktopSkeleton: + * + * The #DesktopSkeleton structure contains only private data and should only be accessed using the provided API. + */ + +/** + * DesktopSkeletonClass: + * @parent_class: The parent class. + * + * Class structure for #DesktopSkeleton. + */ + +struct _DesktopSkeletonPrivate +{ + GValue *properties; + GList *changed_properties; + GSource *changed_properties_idle_source; + GMainContext *context; + GMutex lock; +}; + +static void +_desktop_skeleton_handle_method_call ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name, + const gchar *method_name, + GVariant *parameters, + GDBusMethodInvocation *invocation, + gpointer user_data) +{ + DesktopSkeleton *skeleton = DESKTOP_SKELETON (user_data); + _ExtendedGDBusMethodInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + guint num_extra; + gsize n; + guint signal_id; + GValue return_value = G_VALUE_INIT; + info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); + g_assert (info != NULL); + num_params = g_variant_n_children (parameters); + num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); + n = 0; + g_value_init (¶mv[n], TYPE_DESKTOP); + g_value_set_object (¶mv[n++], skeleton); + g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); + g_value_set_object (¶mv[n++], invocation); + if (info->pass_fdlist) + { +#ifdef G_OS_UNIX + g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); + g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); +#else + g_assert_not_reached (); +#endif + } + g_variant_iter_init (&iter, parameters); + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_DESKTOP); + g_value_init (&return_value, G_TYPE_BOOLEAN); + g_signal_emitv (paramv, signal_id, 0, &return_value); + if (!g_value_get_boolean (&return_value)) + g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); + g_value_unset (&return_value); + for (n = 0; n < num_params + num_extra; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static GVariant * +_desktop_skeleton_handle_get_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GError **error, + gpointer user_data) +{ + DesktopSkeleton *skeleton = DESKTOP_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + GVariant *ret; + ret = NULL; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_desktop_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + g_value_init (&value, pspec->value_type); + g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); + ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); + g_value_unset (&value); + } + return ret; +} + +static gboolean +_desktop_skeleton_handle_set_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GVariant *variant, + GError **error, + gpointer user_data) +{ + DesktopSkeleton *skeleton = DESKTOP_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + gboolean ret; + ret = FALSE; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_desktop_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + if (info->use_gvariant) + g_value_set_variant (&value, variant); + else + g_dbus_gvariant_to_gvalue (variant, &value); + g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); + g_value_unset (&value); + ret = TRUE; + } + return ret; +} + +static const GDBusInterfaceVTable _desktop_skeleton_vtable = +{ + _desktop_skeleton_handle_method_call, + _desktop_skeleton_handle_get_property, + _desktop_skeleton_handle_set_property, + {NULL} +}; + +static GDBusInterfaceInfo * +desktop_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return desktop_interface_info (); +} + +static GDBusInterfaceVTable * +desktop_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return (GDBusInterfaceVTable *) &_desktop_skeleton_vtable; +} + +static GVariant * +desktop_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) +{ + DesktopSkeleton *skeleton = DESKTOP_SKELETON (_skeleton); + + GVariantBuilder builder; + guint n; + g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); + if (_desktop_interface_info.parent_struct.properties == NULL) + goto out; + for (n = 0; _desktop_interface_info.parent_struct.properties[n] != NULL; n++) + { + GDBusPropertyInfo *info = _desktop_interface_info.parent_struct.properties[n]; + if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) + { + GVariant *value; + value = _desktop_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "cn.kylinos.desktop", info->name, NULL, skeleton); + if (value != NULL) + { + g_variant_take_ref (value); + g_variant_builder_add (&builder, "{sv}", info->name, value); + g_variant_unref (value); + } + } + } +out: + return g_variant_builder_end (&builder); +} + +static void +desktop_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) +{ +} + +static void desktop_skeleton_iface_init (DesktopIface *iface); +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (DesktopSkeleton, desktop_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_ADD_PRIVATE (DesktopSkeleton) + G_IMPLEMENT_INTERFACE (TYPE_DESKTOP, desktop_skeleton_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (DesktopSkeleton, desktop_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_IMPLEMENT_INTERFACE (TYPE_DESKTOP, desktop_skeleton_iface_init)) + +#endif +static void +desktop_skeleton_finalize (GObject *object) +{ + DesktopSkeleton *skeleton = DESKTOP_SKELETON (object); + g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); + if (skeleton->priv->changed_properties_idle_source != NULL) + g_source_destroy (skeleton->priv->changed_properties_idle_source); + g_main_context_unref (skeleton->priv->context); + g_mutex_clear (&skeleton->priv->lock); + G_OBJECT_CLASS (desktop_skeleton_parent_class)->finalize (object); +} + +static void +desktop_skeleton_init (DesktopSkeleton *skeleton) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + skeleton->priv = desktop_skeleton_get_instance_private (skeleton); +#else + skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_DESKTOP_SKELETON, DesktopSkeletonPrivate); +#endif + + g_mutex_init (&skeleton->priv->lock); + skeleton->priv->context = g_main_context_ref_thread_default (); +} + +static void +desktop_skeleton_class_init (DesktopSkeletonClass *klass) +{ + GObjectClass *gobject_class; + GDBusInterfaceSkeletonClass *skeleton_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = desktop_skeleton_finalize; + + skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); + skeleton_class->get_info = desktop_skeleton_dbus_interface_get_info; + skeleton_class->get_properties = desktop_skeleton_dbus_interface_get_properties; + skeleton_class->flush = desktop_skeleton_dbus_interface_flush; + skeleton_class->get_vtable = desktop_skeleton_dbus_interface_get_vtable; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (DesktopSkeletonPrivate)); +#endif +} + +static void +desktop_skeleton_iface_init (DesktopIface *iface) +{ +} + +/** + * desktop_skeleton_new: + * + * Creates a skeleton object for the D-Bus interface cn.kylinos.desktop. + * + * Returns: (transfer full) (type DesktopSkeleton): The skeleton object. + */ +Desktop * +desktop_skeleton_new (void) +{ + return DESKTOP (g_object_new (TYPE_DESKTOP_SKELETON, NULL)); +} + diff --git a/src/personal/desktop/desktop-generated.h b/src/personal/desktop/desktop-generated.h new file mode 100644 index 0000000..ac9af91 --- /dev/null +++ b/src/personal/desktop/desktop-generated.h @@ -0,0 +1,244 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +G_BEGIN_DECLS + + +/* ------------------------------------------------------------------------ */ +/* Declarations for cn.kylinos.desktop */ + +#define TYPE_DESKTOP (desktop_get_type ()) +#define DESKTOP(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_DESKTOP, Desktop)) +#define IS_DESKTOP(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_DESKTOP)) +#define DESKTOP_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), TYPE_DESKTOP, DesktopIface)) + +struct _Desktop; +typedef struct _Desktop Desktop; +typedef struct _DesktopIface DesktopIface; + +struct _DesktopIface +{ + GTypeInterface parent_iface; + + gboolean (*handle_transfer_bool_value) ( + Desktop *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + + gboolean (*handle_transfer_int_value) ( + Desktop *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + + gboolean (*handle_transfer_string_value) ( + Desktop *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + +}; + +GType desktop_get_type (void) G_GNUC_CONST; + +GDBusInterfaceInfo *desktop_interface_info (void); +guint desktop_override_properties (GObjectClass *klass, guint property_id_begin); + + +/* D-Bus method call completion functions: */ +void desktop_complete_transfer_bool_value ( + Desktop *object, + GDBusMethodInvocation *invocation); + +void desktop_complete_transfer_string_value ( + Desktop *object, + GDBusMethodInvocation *invocation); + +void desktop_complete_transfer_int_value ( + Desktop *object, + GDBusMethodInvocation *invocation); + + + +/* D-Bus method calls: */ +void desktop_call_transfer_bool_value ( + Desktop *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean desktop_call_transfer_bool_value_finish ( + Desktop *proxy, + GAsyncResult *res, + GError **error); + +gboolean desktop_call_transfer_bool_value_sync ( + Desktop *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + +void desktop_call_transfer_string_value ( + Desktop *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean desktop_call_transfer_string_value_finish ( + Desktop *proxy, + GAsyncResult *res, + GError **error); + +gboolean desktop_call_transfer_string_value_sync ( + Desktop *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + +void desktop_call_transfer_int_value ( + Desktop *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean desktop_call_transfer_int_value_finish ( + Desktop *proxy, + GAsyncResult *res, + GError **error); + +gboolean desktop_call_transfer_int_value_sync ( + Desktop *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + + + +/* ---- */ + +#define TYPE_DESKTOP_PROXY (desktop_proxy_get_type ()) +#define DESKTOP_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_DESKTOP_PROXY, DesktopProxy)) +#define DESKTOP_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_DESKTOP_PROXY, DesktopProxyClass)) +#define DESKTOP_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_DESKTOP_PROXY, DesktopProxyClass)) +#define IS_DESKTOP_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_DESKTOP_PROXY)) +#define IS_DESKTOP_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_DESKTOP_PROXY)) + +typedef struct _DesktopProxy DesktopProxy; +typedef struct _DesktopProxyClass DesktopProxyClass; +typedef struct _DesktopProxyPrivate DesktopProxyPrivate; + +struct _DesktopProxy +{ + /*< private >*/ + GDBusProxy parent_instance; + DesktopProxyPrivate *priv; +}; + +struct _DesktopProxyClass +{ + GDBusProxyClass parent_class; +}; + +GType desktop_proxy_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (DesktopProxy, g_object_unref) +#endif + +void desktop_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Desktop *desktop_proxy_new_finish ( + GAsyncResult *res, + GError **error); +Desktop *desktop_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + +void desktop_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Desktop *desktop_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error); +Desktop *desktop_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + + +/* ---- */ + +#define TYPE_DESKTOP_SKELETON (desktop_skeleton_get_type ()) +#define DESKTOP_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_DESKTOP_SKELETON, DesktopSkeleton)) +#define DESKTOP_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_DESKTOP_SKELETON, DesktopSkeletonClass)) +#define DESKTOP_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_DESKTOP_SKELETON, DesktopSkeletonClass)) +#define IS_DESKTOP_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_DESKTOP_SKELETON)) +#define IS_DESKTOP_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_DESKTOP_SKELETON)) + +typedef struct _DesktopSkeleton DesktopSkeleton; +typedef struct _DesktopSkeletonClass DesktopSkeletonClass; +typedef struct _DesktopSkeletonPrivate DesktopSkeletonPrivate; + +struct _DesktopSkeleton +{ + /*< private >*/ + GDBusInterfaceSkeleton parent_instance; + DesktopSkeletonPrivate *priv; +}; + +struct _DesktopSkeletonClass +{ + GDBusInterfaceSkeletonClass parent_class; +}; + +GType desktop_skeleton_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (DesktopSkeleton, g_object_unref) +#endif + +Desktop *desktop_skeleton_new (void); + + +G_END_DECLS + +#endif /* __DESKTOP_GENERATED_H__ */ diff --git a/src/personal/desktop/kylin-desktop-interface.c b/src/personal/desktop/kylin-desktop-interface.c new file mode 100644 index 0000000..b9e686a --- /dev/null +++ b/src/personal/desktop/kylin-desktop-interface.c @@ -0,0 +1,301 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#define FN "font" +#define HIV "home-icon-visible" +#define CIV "computer-icon-visible" +#define TIV "trash-icon-visible" +#define VV "volumes-visible" +#define NIV "network-icon-visible" +#define CIN "computer-icon-name" +#define HIN "home-icon-name" +#define TIN "trash-icon-name" +#define NIN "network-icon-name" +#define TEL "text-ellipsis-limit" + +static GMainLoop *pLoop = NULL; +static GDBusConnection *pConnection = NULL; +static Desktop *pProxy = NULL; + +void kylin_personal_fonts_font(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=FN; + arg=g_variant_new("(ss)", key, in_arg); + desktop_call_transfer_string_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_font. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_fonts_homeiconvisible(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=HIV; + arg=g_variant_new("(sb)", key, in_arg); + desktop_call_transfer_bool_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_homeiconvisible. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_fonts_computericonvisible(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=CIV; + arg=g_variant_new("(sb)", key, in_arg); + desktop_call_transfer_bool_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_computericonvisible. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_fonts_trashiconvisible(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=TIV; + arg=g_variant_new("(sb)", key, in_arg); + desktop_call_transfer_bool_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_trashiconvisible. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_fonts_volumesvisible(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=VV; + arg=g_variant_new("(sb)", key, in_arg); + desktop_call_transfer_bool_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_volumesvisible. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_fonts_networkiconvisible(const bool in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=NIV; + arg=g_variant_new("(sb)", key, in_arg); + desktop_call_transfer_bool_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_networkiconvisible. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_fonts_computericonname(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=CIN; + arg=g_variant_new("(ss)", key, in_arg); + desktop_call_transfer_string_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_computericonname. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_fonts_homeiconname(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=HIN; + arg=g_variant_new("(ss)", key, in_arg); + desktop_call_transfer_string_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_homeiconname. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_fonts_trashiconname(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=TIN; + arg=g_variant_new("(ss)", key, in_arg); + desktop_call_transfer_string_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_trashiconname. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_fonts_networkiconname(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=NIN; + arg=g_variant_new("(ss)", key, in_arg); + desktop_call_transfer_string_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_networkiconname. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_fonts_textellipsislimit(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=TEL; + arg=g_variant_new("(si)",key,in_arg); + desktop_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_textellipsislimit. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; + +} + +void *run(void* arg) +{ + /** start the main event loop which manages all available sources of events */ + g_main_loop_run(pLoop); + + return ((void*)0); +} + +int thread_create(void) + { + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if(0 != err){ + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; + } + +bool InitDBusDesktop(void) + { + bool bRet = TRUE; + GError *pConnError = NULL; + GError *pProxyError = NULL; + + do{ + bRet = TRUE; + pLoop = g_main_loop_new(NULL, FALSE); /** create main loop, but do not start it.*/ + + /** First step: get a connection */ + pConnection = g_bus_get_sync(DESKTOP_BUS, NULL, &pConnError); + + if (NULL == pConnError){ + /** Second step: try to get a connection to the given bus.*/ + pProxy = desktop_proxy_new_sync(pConnection, + G_DBUS_PROXY_FLAGS_NONE, + DESKTOP_BUS_NAME, + DESKTOP_OBJECT_PATH, + NULL, + &pProxyError); + if (0 == pProxy){ + print_error("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message); + g_error_free(pProxyError); + bRet = FALSE; + } + + + } + else{ + print_error("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message); + g_error_free(pConnError); + bRet = FALSE; + } + }while(FALSE == bRet); + + thread_create(); + + return bRet; + } + +bool DeInitDBusDesktop(void) +{ + bool bRet = FALSE; + + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} diff --git a/src/personal/desktop/kylin-desktop-interface.h b/src/personal/desktop/kylin-desktop-interface.h new file mode 100644 index 0000000..517c517 --- /dev/null +++ b/src/personal/desktop/kylin-desktop-interface.h @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +//Initialize the DBus Communication +bool InitDBusDesktop(void); + +//Delete the DBus Communication +bool DeInitDBusDesktop(void); + +/* + * The font description used for the icons on the desktop. + */ +void kylin_personal_fonts_font(const char *in_arg); + +/* + * Home icon visible on desktop. + * If this is set to true, an icon linking to the home folder + * will be put on the desktop. + */ +void kylin_personal_fonts_homeiconvisible(const bool in_arg); + +/* + * Computer icon visible on desktop. + * If this is set to true, an icon linking to the computer location + * will be put on the desktop. + */ +void kylin_personal_fonts_computericonvisible(const bool in_arg); + +/* + * Trash icon visible on desktop. + * If this is set to true, an icon linking to the trash + * will be put on the desktop. + */ +void kylin_personal_fonts_trashiconvisible(const bool in_arg); + +/* + * Show mounted volumes on the desktop. + * If this is set to true, icons linking to mounted volumes + * will be put on the desktop. + */ +void kylin_personal_fonts_volumesvisible(const bool in_arg); + +/* + * Network Servers icon visible on the desktop. + * If this is set to true, an icon linking to the Network Servers view + * will be put on the desktop. + */ +void kylin_personal_fonts_networkiconvisible(const bool in_arg); + +/* + * Desktop computer icon name. + */ +void kylin_personal_fonts_computericonname(const char *in_arg); + +/* + * Desktop home icon name. + */ +void kylin_personal_fonts_homeiconname(const char *in_arg); + +/* + * Desktop trash icon name. + */ +void kylin_personal_fonts_trashiconname(const char *in_arg); + +/* + * Network servers icon name. + */ +void kylin_personal_fonts_networkiconname(const char *in_arg); + +/* + * Text Ellipsis Limit. + */ +void kylin_personal_fonts_textellipsislimit(const int in_arg); + +#ifdef __cplusplus +} +#endif + +#endif + + + + + + + + + + + + + diff --git a/src/personal/desktop/kylin-desktop-server.c b/src/personal/desktop/kylin-desktop-server.c new file mode 100644 index 0000000..03240e1 --- /dev/null +++ b/src/personal/desktop/kylin-desktop-server.c @@ -0,0 +1,221 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include "desktop-dbus.h" +#include "src/common/kylin-gsettings-set.h" +#include "src/common/kylin-print.h" +#include "desktop-generated.h" +#include +#include + +#define schemaID "org.mate.caja.desktop" + +static GMainLoop *pLoop = NULL; +static Desktop *pSkeleton = NULL; + +static gboolean kylin_set_bool(Desktop* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gboolean value; + gint i; + g_variant_get(in_arg, "(sb)", &key, &value); + if(value==false)i=0; + else i=1; + + desktop_complete_transfer_bool_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + gsettings_set_boolean(setting, key, value); + Dec_ref(setting); + + print_info("(%s, %d)\n", key, i); + + return TRUE; +} + +static gboolean kylin_set_int(Desktop* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gint value; + g_variant_get(in_arg, "(si)", &key, &value); + + desktop_complete_transfer_int_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + gsettings_set_int(setting, key, value); + Dec_ref(setting); + + print_info("(%s, %d)\n", key, value); + + return TRUE; +} + +static gboolean kylin_set_char(Desktop* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gchar *value=NULL; + g_variant_get(in_arg, "(ss)", &key, &value); + + desktop_complete_transfer_string_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + gsettings_set_string(setting, key, value); + Dec_ref(setting); + + print_info("(%s, %s)\n", key, value); + + return TRUE; +} + +static void bus_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + + GError *pError = NULL; + + /** Second step: Try to get a connection to the given bus. */ + pSkeleton = desktop_skeleton_new(); + + /** Third step: Attach to dbus signals. */ + (void) g_signal_connect(pSkeleton, "handle-transfer-bool-value", G_CALLBACK(kylin_set_bool), NULL); + (void) g_signal_connect(pSkeleton, "handle-transfer-int-value", G_CALLBACK(kylin_set_int), NULL); + (void) g_signal_connect(pSkeleton, "handle-transfer-string-value", G_CALLBACK(kylin_set_char), NULL); + + /** Fourth step: Export interface skeleton. */ + (void)g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(pSkeleton), + connection, + DESKTOP_OBJECT_PATH, + &pError); + + if(pError != NULL){ + print_error("Error: Failed to export object. Reason: %s.\n", pError->message); + g_error_free(pError); + g_main_loop_quit(pLoop); + } +} + +static void name_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + print_info("name_acquired_cb call, Acquired bus name: %s.\n", DESKTOP_BUS_NAME); +} + +static void name_lost_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + if(connection == NULL) + { + print_error("name_lost_cb call, Error: Failed to connect to dbus.\n"); + } + else + { + print_error("name_lost_cb call, Error: Failed to obtain bus name: %s.\n", DESKTOP_BUS_NAME); + } + + g_main_loop_quit(pLoop); +} + +void* run(void* para) +{ + /** Start the Main Event Loop which manages all available sources of events */ + g_main_loop_run( pLoop ); + + return ((void*)0); +} + +int thread_create(void) +{ + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if (err != 0) + { + + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; +} + +bool InitDBusCommunicationServer(void) +{ + bool bRet = TRUE; + + g_print("InitDBusCommunicationServer: Server started.\n"); + + /** create main loop, but do not start it. */ + pLoop = g_main_loop_new(NULL, FALSE); + + /** first step: connect to dbus */ + (void)g_bus_own_name(DESKTOP_BUS, + DESKTOP_BUS_NAME, + G_BUS_NAME_OWNER_FLAGS_NONE, + &bus_acquired_cb, + &name_acquired_cb, + &name_lost_cb, + NULL, + NULL); + + thread_create(); + + return bRet; +} + +bool DeinitDBusCommunicationServer(void) +{ + bool bRet = FALSE; + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} + +int main(void) +{ + InitDBusCommunicationServer(); + + sleep(100); + + DeinitDBusCommunicationServer(); + return 0; +} diff --git a/src/personal/font/Makefile.am b/src/personal/font/Makefile.am new file mode 100644 index 0000000..6dc8fb3 --- /dev/null +++ b/src/personal/font/Makefile.am @@ -0,0 +1,56 @@ +COMM_PRINT= -L$(top_srcdir)/src/common -lukui-print +COMM_GSETTINGS= -L$(top_srcdir)/src/common -lukui-gsettings + +#generate the .c and .h file which used by client and server side by XML file +#$(top_srcdir) represents the top-level directory of the project +DESC_XML = $(top_srcdir)/data/cn.kylinos.font.xml +GENERATED_CH = font-generated + +font-generated.h font-generated.c: $(DESC_XML) + gdbus-codegen --interface-prefix cn.kylinos. --generate-c-code $(GENERATED_CH) $(DESC_XML) + +#Generata binary file +lib_LTLIBRARIES = libukui-fontclient.la + +#gcc -wall: displays all the errors and warning information when compiling +#gcc -g: add the debugging code when compiling +COMM_CFS = -Wall -g + +#Add the dependent source file for libfontclient.la +#font-generated.c must be front of kylin-font-interface.c +libukui_fontclient_la_SOURCES = \ + font-generated.c kylin-font-interface.c \ + $(NULL) + +#The header files that need to be installed +include_HEADERS= kylin-font-interface.h \ + $(NULL) + +#Additional C compiler flags +libukui_fontclient_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_fontclient_la_LDFLAGS= $(COMM_PRINT) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Generata binary file +bin_PROGRAMS = ukui-fontserver + +#Add the dependent source file for fontserver +ukui_fontserver_SOURCES = \ + font-generated.h font-generated.c \ + kylin-font-server.c \ + $(NULL) + +#Additional C compiler flags +ukui_fontserver_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +ukui_fontserver_LDFLAGS= $(COMM_PRINT) $(COMM_GSETTINGS) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) diff --git a/src/personal/font/font-dbus.h b/src/personal/font/font-dbus.h new file mode 100644 index 0000000..aa04a98 --- /dev/null +++ b/src/personal/font/font-dbus.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 /* Bus define */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define FONT_BUS G_BUS_TYPE_SESSION +#define FONT_BUS_NAME "cn.kylinos.font" +#define FONT_OBJECT_PATH "/cn/kylinos/font" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/personal/font/font-generated.c b/src/personal/font/font-generated.c new file mode 100644 index 0000000..eeec04e --- /dev/null +++ b/src/personal/font/font-generated.c @@ -0,0 +1,1221 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#ifdef G_OS_UNIX +# include +#endif + +typedef struct +{ + GDBusArgInfo parent_struct; + gboolean use_gvariant; +} _ExtendedGDBusArgInfo; + +typedef struct +{ + GDBusMethodInfo parent_struct; + const gchar *signal_name; + gboolean pass_fdlist; +} _ExtendedGDBusMethodInfo; + +typedef struct +{ + GDBusSignalInfo parent_struct; + const gchar *signal_name; +} _ExtendedGDBusSignalInfo; + +typedef struct +{ + GDBusPropertyInfo parent_struct; + const gchar *hyphen_name; + guint use_gvariant : 1; + guint emits_changed_signal : 1; +} _ExtendedGDBusPropertyInfo; + +typedef struct +{ + GDBusInterfaceInfo parent_struct; + const gchar *hyphen_name; +} _ExtendedGDBusInterfaceInfo; + +typedef struct +{ + const _ExtendedGDBusPropertyInfo *info; + guint prop_id; + GValue orig_value; /* the value before the change */ +} ChangedProperty; + +static void +_changed_property_free (ChangedProperty *data) +{ + g_value_unset (&data->orig_value); + g_free (data); +} + +static gboolean +_g_strv_equal0 (gchar **a, gchar **b) +{ + gboolean ret = FALSE; + guint n; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + if (g_strv_length (a) != g_strv_length (b)) + goto out; + for (n = 0; a[n] != NULL; n++) + if (g_strcmp0 (a[n], b[n]) != 0) + goto out; + ret = TRUE; +out: + return ret; +} + +static gboolean +_g_variant_equal0 (GVariant *a, GVariant *b) +{ + gboolean ret = FALSE; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + ret = g_variant_equal (a, b); +out: + return ret; +} + +G_GNUC_UNUSED static gboolean +_g_value_equal (const GValue *a, const GValue *b) +{ + gboolean ret = FALSE; + g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); + switch (G_VALUE_TYPE (a)) + { + case G_TYPE_BOOLEAN: + ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); + break; + case G_TYPE_UCHAR: + ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); + break; + case G_TYPE_INT: + ret = (g_value_get_int (a) == g_value_get_int (b)); + break; + case G_TYPE_UINT: + ret = (g_value_get_uint (a) == g_value_get_uint (b)); + break; + case G_TYPE_INT64: + ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); + break; + case G_TYPE_UINT64: + ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); + break; + case G_TYPE_DOUBLE: + { + /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ + gdouble da = g_value_get_double (a); + gdouble db = g_value_get_double (b); + ret = memcmp (&da, &db, sizeof (gdouble)) == 0; + } + break; + case G_TYPE_STRING: + ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); + break; + case G_TYPE_VARIANT: + ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); + break; + default: + if (G_VALUE_TYPE (a) == G_TYPE_STRV) + ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); + else + g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); + break; + } + return ret; +} + +/* ------------------------------------------------------------------------ + * Code for interface cn.kylinos.font + * ------------------------------------------------------------------------ + */ + +/** + * SECTION:Font + * @title: Font + * @short_description: Generated C code for the cn.kylinos.font D-Bus interface + * + * This section contains code for working with the cn.kylinos.font D-Bus interface in C. + */ + +/* ---- Introspection data for cn.kylinos.font ---- */ + +static const _ExtendedGDBusArgInfo _font_method_info_transfer_int_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(si)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _font_method_info_transfer_int_value_IN_ARG_pointers[] = +{ + &_font_method_info_transfer_int_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _font_method_info_transfer_int_value = +{ + { + -1, + (gchar *) "TransferIntValue", + (GDBusArgInfo **) &_font_method_info_transfer_int_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-int-value", + FALSE +}; + +static const _ExtendedGDBusArgInfo _font_method_info_transfer_double_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(sd)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _font_method_info_transfer_double_value_IN_ARG_pointers[] = +{ + &_font_method_info_transfer_double_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _font_method_info_transfer_double_value = +{ + { + -1, + (gchar *) "TransferDoubleValue", + (GDBusArgInfo **) &_font_method_info_transfer_double_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-double-value", + FALSE +}; + +static const GDBusMethodInfo * const _font_method_info_pointers[] = +{ + &_font_method_info_transfer_int_value.parent_struct, + &_font_method_info_transfer_double_value.parent_struct, + NULL +}; + +static const _ExtendedGDBusInterfaceInfo _font_interface_info = +{ + { + -1, + (gchar *) "cn.kylinos.font", + (GDBusMethodInfo **) &_font_method_info_pointers, + NULL, + NULL, + NULL + }, + "font", +}; + + +/** + * font_interface_info: + * + * Gets a machine-readable description of the cn.kylinos.font D-Bus interface. + * + * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. + */ +GDBusInterfaceInfo * +font_interface_info (void) +{ + return (GDBusInterfaceInfo *) &_font_interface_info.parent_struct; +} + +/** + * font_override_properties: + * @klass: The class structure for a #GObject derived class. + * @property_id_begin: The property id to assign to the first overridden property. + * + * Overrides all #GObject properties in the #Font interface for a concrete class. + * The properties are overridden in the order they are defined. + * + * Returns: The last property id. + */ +guint +font_override_properties (GObjectClass *klass, guint property_id_begin) +{ + return property_id_begin - 1; +} + + + +/** + * Font: + * + * Abstract interface type for the D-Bus interface cn.kylinos.font. + */ + +/** + * FontIface: + * @parent_iface: The parent interface. + * @handle_transfer_double_value: Handler for the #Font::handle-transfer-double-value signal. + * @handle_transfer_int_value: Handler for the #Font::handle-transfer-int-value signal. + * + * Virtual table for the D-Bus interface cn.kylinos.font. + */ + +typedef FontIface FontInterface; +G_DEFINE_INTERFACE (Font, font, G_TYPE_OBJECT) + +static void +font_default_init (FontIface *iface) +{ + /* GObject signals for incoming D-Bus method calls: */ + /** + * Font::handle-transfer-int-value: + * @object: A #Font. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferIntValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call font_complete_transfer_int_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-int-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (FontIface, handle_transfer_int_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + + /** + * Font::handle-transfer-double-value: + * @object: A #Font. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferDoubleValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call font_complete_transfer_double_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-double-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (FontIface, handle_transfer_double_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + +} + +/** + * font_call_transfer_int_value: + * @proxy: A #FontProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferIntValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call font_call_transfer_int_value_finish() to get the result of the operation. + * + * See font_call_transfer_int_value_sync() for the synchronous, blocking version of this method. + */ +void +font_call_transfer_int_value ( + Font *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * font_call_transfer_int_value_finish: + * @proxy: A #FontProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to font_call_transfer_int_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with font_call_transfer_int_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +font_call_transfer_int_value_finish ( + Font *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * font_call_transfer_int_value_sync: + * @proxy: A #FontProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferIntValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See font_call_transfer_int_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +font_call_transfer_int_value_sync ( + Font *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferIntValue", + g_variant_new ("(@(si))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * font_call_transfer_double_value: + * @proxy: A #FontProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferDoubleValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call font_call_transfer_double_value_finish() to get the result of the operation. + * + * See font_call_transfer_double_value_sync() for the synchronous, blocking version of this method. + */ +void +font_call_transfer_double_value ( + Font *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferDoubleValue", + g_variant_new ("(@(sd))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * font_call_transfer_double_value_finish: + * @proxy: A #FontProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to font_call_transfer_double_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with font_call_transfer_double_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +font_call_transfer_double_value_finish ( + Font *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * font_call_transfer_double_value_sync: + * @proxy: A #FontProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferDoubleValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See font_call_transfer_double_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +font_call_transfer_double_value_sync ( + Font *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferDoubleValue", + g_variant_new ("(@(sd))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * font_complete_transfer_int_value: + * @object: A #Font. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferIntValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +font_complete_transfer_int_value ( + Font *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/** + * font_complete_transfer_double_value: + * @object: A #Font. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferDoubleValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +font_complete_transfer_double_value ( + Font *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/* ------------------------------------------------------------------------ */ + +/** + * FontProxy: + * + * The #FontProxy structure contains only private data and should only be accessed using the provided API. + */ + +/** + * FontProxyClass: + * @parent_class: The parent class. + * + * Class structure for #FontProxy. + */ + +struct _FontProxyPrivate +{ + GData *qdata; +}; + +static void font_proxy_iface_init (FontIface *iface); + +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (FontProxy, font_proxy, G_TYPE_DBUS_PROXY, + G_ADD_PRIVATE (FontProxy) + G_IMPLEMENT_INTERFACE (TYPE_FONT, font_proxy_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (FontProxy, font_proxy, G_TYPE_DBUS_PROXY, + G_IMPLEMENT_INTERFACE (TYPE_FONT, font_proxy_iface_init)) + +#endif +static void +font_proxy_finalize (GObject *object) +{ + FontProxy *proxy = FONT_PROXY (object); + g_datalist_clear (&proxy->priv->qdata); + G_OBJECT_CLASS (font_proxy_parent_class)->finalize (object); +} + +static void +font_proxy_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +font_proxy_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +font_proxy_g_signal (GDBusProxy *proxy, + const gchar *sender_name G_GNUC_UNUSED, + const gchar *signal_name, + GVariant *parameters) +{ + _ExtendedGDBusSignalInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + gsize n; + guint signal_id; + info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_font_interface_info.parent_struct, signal_name); + if (info == NULL) + return; + num_params = g_variant_n_children (parameters); + paramv = g_new0 (GValue, num_params + 1); + g_value_init (¶mv[0], TYPE_FONT); + g_value_set_object (¶mv[0], proxy); + g_variant_iter_init (&iter, parameters); + n = 1; + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_FONT); + g_signal_emitv (paramv, signal_id, 0, NULL); + for (n = 0; n < num_params + 1; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static void +font_proxy_g_properties_changed (GDBusProxy *_proxy, + GVariant *changed_properties, + const gchar *const *invalidated_properties) +{ + FontProxy *proxy = FONT_PROXY (_proxy); + guint n; + const gchar *key; + GVariantIter *iter; + _ExtendedGDBusPropertyInfo *info; + g_variant_get (changed_properties, "a{sv}", &iter); + while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_font_interface_info.parent_struct, key); + g_datalist_remove_data (&proxy->priv->qdata, key); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } + g_variant_iter_free (iter); + for (n = 0; invalidated_properties[n] != NULL; n++) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_font_interface_info.parent_struct, invalidated_properties[n]); + g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } +} + +static void +font_proxy_init (FontProxy *proxy) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + proxy->priv = font_proxy_get_instance_private (proxy); +#else + proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, TYPE_FONT_PROXY, FontProxyPrivate); +#endif + + g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), font_interface_info ()); +} + +static void +font_proxy_class_init (FontProxyClass *klass) +{ + GObjectClass *gobject_class; + GDBusProxyClass *proxy_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = font_proxy_finalize; + gobject_class->get_property = font_proxy_get_property; + gobject_class->set_property = font_proxy_set_property; + + proxy_class = G_DBUS_PROXY_CLASS (klass); + proxy_class->g_signal = font_proxy_g_signal; + proxy_class->g_properties_changed = font_proxy_g_properties_changed; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (FontProxyPrivate)); +#endif +} + +static void +font_proxy_iface_init (FontIface *iface) +{ +} + +/** + * font_proxy_new: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Asynchronously creates a proxy for the D-Bus interface cn.kylinos.font. See g_dbus_proxy_new() for more details. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call font_proxy_new_finish() to get the result of the operation. + * + * See font_proxy_new_sync() for the synchronous, blocking version of this constructor. + */ +void +font_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_FONT_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.font", NULL); +} + +/** + * font_proxy_new_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to font_proxy_new(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with font_proxy_new(). + * + * Returns: (transfer full) (type FontProxy): The constructed proxy object or %NULL if @error is set. + */ +Font * +font_proxy_new_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return FONT (ret); + else + return NULL; +} + +/** + * font_proxy_new_sync: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Synchronously creates a proxy for the D-Bus interface cn.kylinos.font. See g_dbus_proxy_new_sync() for more details. + * + * The calling thread is blocked until a reply is received. + * + * See font_proxy_new() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type FontProxy): The constructed proxy object or %NULL if @error is set. + */ +Font * +font_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_FONT_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.font", NULL); + if (ret != NULL) + return FONT (ret); + else + return NULL; +} + + +/** + * font_proxy_new_for_bus: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Like font_proxy_new() but takes a #GBusType instead of a #GDBusConnection. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call font_proxy_new_for_bus_finish() to get the result of the operation. + * + * See font_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. + */ +void +font_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_FONT_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.font", NULL); +} + +/** + * font_proxy_new_for_bus_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to font_proxy_new_for_bus(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with font_proxy_new_for_bus(). + * + * Returns: (transfer full) (type FontProxy): The constructed proxy object or %NULL if @error is set. + */ +Font * +font_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return FONT (ret); + else + return NULL; +} + +/** + * font_proxy_new_for_bus_sync: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Like font_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. + * + * The calling thread is blocked until a reply is received. + * + * See font_proxy_new_for_bus() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type FontProxy): The constructed proxy object or %NULL if @error is set. + */ +Font * +font_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_FONT_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.font", NULL); + if (ret != NULL) + return FONT (ret); + else + return NULL; +} + + +/* ------------------------------------------------------------------------ */ + +/** + * FontSkeleton: + * + * The #FontSkeleton structure contains only private data and should only be accessed using the provided API. + */ + +/** + * FontSkeletonClass: + * @parent_class: The parent class. + * + * Class structure for #FontSkeleton. + */ + +struct _FontSkeletonPrivate +{ + GValue *properties; + GList *changed_properties; + GSource *changed_properties_idle_source; + GMainContext *context; + GMutex lock; +}; + +static void +_font_skeleton_handle_method_call ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name, + const gchar *method_name, + GVariant *parameters, + GDBusMethodInvocation *invocation, + gpointer user_data) +{ + FontSkeleton *skeleton = FONT_SKELETON (user_data); + _ExtendedGDBusMethodInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + guint num_extra; + gsize n; + guint signal_id; + GValue return_value = G_VALUE_INIT; + info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); + g_assert (info != NULL); + num_params = g_variant_n_children (parameters); + num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); + n = 0; + g_value_init (¶mv[n], TYPE_FONT); + g_value_set_object (¶mv[n++], skeleton); + g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); + g_value_set_object (¶mv[n++], invocation); + if (info->pass_fdlist) + { +#ifdef G_OS_UNIX + g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); + g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); +#else + g_assert_not_reached (); +#endif + } + g_variant_iter_init (&iter, parameters); + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_FONT); + g_value_init (&return_value, G_TYPE_BOOLEAN); + g_signal_emitv (paramv, signal_id, 0, &return_value); + if (!g_value_get_boolean (&return_value)) + g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); + g_value_unset (&return_value); + for (n = 0; n < num_params + num_extra; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static GVariant * +_font_skeleton_handle_get_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GError **error, + gpointer user_data) +{ + FontSkeleton *skeleton = FONT_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + GVariant *ret; + ret = NULL; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_font_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + g_value_init (&value, pspec->value_type); + g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); + ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); + g_value_unset (&value); + } + return ret; +} + +static gboolean +_font_skeleton_handle_set_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GVariant *variant, + GError **error, + gpointer user_data) +{ + FontSkeleton *skeleton = FONT_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + gboolean ret; + ret = FALSE; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_font_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + if (info->use_gvariant) + g_value_set_variant (&value, variant); + else + g_dbus_gvariant_to_gvalue (variant, &value); + g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); + g_value_unset (&value); + ret = TRUE; + } + return ret; +} + +static const GDBusInterfaceVTable _font_skeleton_vtable = +{ + _font_skeleton_handle_method_call, + _font_skeleton_handle_get_property, + _font_skeleton_handle_set_property, + {NULL} +}; + +static GDBusInterfaceInfo * +font_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return font_interface_info (); +} + +static GDBusInterfaceVTable * +font_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return (GDBusInterfaceVTable *) &_font_skeleton_vtable; +} + +static GVariant * +font_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) +{ + FontSkeleton *skeleton = FONT_SKELETON (_skeleton); + + GVariantBuilder builder; + guint n; + g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); + if (_font_interface_info.parent_struct.properties == NULL) + goto out; + for (n = 0; _font_interface_info.parent_struct.properties[n] != NULL; n++) + { + GDBusPropertyInfo *info = _font_interface_info.parent_struct.properties[n]; + if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) + { + GVariant *value; + value = _font_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "cn.kylinos.font", info->name, NULL, skeleton); + if (value != NULL) + { + g_variant_take_ref (value); + g_variant_builder_add (&builder, "{sv}", info->name, value); + g_variant_unref (value); + } + } + } +out: + return g_variant_builder_end (&builder); +} + +static void +font_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) +{ +} + +static void font_skeleton_iface_init (FontIface *iface); +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (FontSkeleton, font_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_ADD_PRIVATE (FontSkeleton) + G_IMPLEMENT_INTERFACE (TYPE_FONT, font_skeleton_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (FontSkeleton, font_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_IMPLEMENT_INTERFACE (TYPE_FONT, font_skeleton_iface_init)) + +#endif +static void +font_skeleton_finalize (GObject *object) +{ + FontSkeleton *skeleton = FONT_SKELETON (object); + g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); + if (skeleton->priv->changed_properties_idle_source != NULL) + g_source_destroy (skeleton->priv->changed_properties_idle_source); + g_main_context_unref (skeleton->priv->context); + g_mutex_clear (&skeleton->priv->lock); + G_OBJECT_CLASS (font_skeleton_parent_class)->finalize (object); +} + +static void +font_skeleton_init (FontSkeleton *skeleton) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + skeleton->priv = font_skeleton_get_instance_private (skeleton); +#else + skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_FONT_SKELETON, FontSkeletonPrivate); +#endif + + g_mutex_init (&skeleton->priv->lock); + skeleton->priv->context = g_main_context_ref_thread_default (); +} + +static void +font_skeleton_class_init (FontSkeletonClass *klass) +{ + GObjectClass *gobject_class; + GDBusInterfaceSkeletonClass *skeleton_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = font_skeleton_finalize; + + skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); + skeleton_class->get_info = font_skeleton_dbus_interface_get_info; + skeleton_class->get_properties = font_skeleton_dbus_interface_get_properties; + skeleton_class->flush = font_skeleton_dbus_interface_flush; + skeleton_class->get_vtable = font_skeleton_dbus_interface_get_vtable; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (FontSkeletonPrivate)); +#endif +} + +static void +font_skeleton_iface_init (FontIface *iface) +{ +} + +/** + * font_skeleton_new: + * + * Creates a skeleton object for the D-Bus interface cn.kylinos.font. + * + * Returns: (transfer full) (type FontSkeleton): The skeleton object. + */ +Font * +font_skeleton_new (void) +{ + return FONT (g_object_new (TYPE_FONT_SKELETON, NULL)); +} + diff --git a/src/personal/font/font-generated.h b/src/personal/font/font-generated.h new file mode 100644 index 0000000..8429def --- /dev/null +++ b/src/personal/font/font-generated.h @@ -0,0 +1,217 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +G_BEGIN_DECLS + + +/* ------------------------------------------------------------------------ */ +/* Declarations for cn.kylinos.font */ + +#define TYPE_FONT (font_get_type ()) +#define FONT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_FONT, Font)) +#define IS_FONT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_FONT)) +#define FONT_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), TYPE_FONT, FontIface)) + +struct _Font; +typedef struct _Font Font; +typedef struct _FontIface FontIface; + +struct _FontIface +{ + GTypeInterface parent_iface; + + gboolean (*handle_transfer_double_value) ( + Font *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + + gboolean (*handle_transfer_int_value) ( + Font *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + +}; + +GType font_get_type (void) G_GNUC_CONST; + +GDBusInterfaceInfo *font_interface_info (void); +guint font_override_properties (GObjectClass *klass, guint property_id_begin); + + +/* D-Bus method call completion functions: */ +void font_complete_transfer_int_value ( + Font *object, + GDBusMethodInvocation *invocation); + +void font_complete_transfer_double_value ( + Font *object, + GDBusMethodInvocation *invocation); + + + +/* D-Bus method calls: */ +void font_call_transfer_int_value ( + Font *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean font_call_transfer_int_value_finish ( + Font *proxy, + GAsyncResult *res, + GError **error); + +gboolean font_call_transfer_int_value_sync ( + Font *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + +void font_call_transfer_double_value ( + Font *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean font_call_transfer_double_value_finish ( + Font *proxy, + GAsyncResult *res, + GError **error); + +gboolean font_call_transfer_double_value_sync ( + Font *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + + + +/* ---- */ + +#define TYPE_FONT_PROXY (font_proxy_get_type ()) +#define FONT_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_FONT_PROXY, FontProxy)) +#define FONT_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_FONT_PROXY, FontProxyClass)) +#define FONT_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_FONT_PROXY, FontProxyClass)) +#define IS_FONT_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_FONT_PROXY)) +#define IS_FONT_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_FONT_PROXY)) + +typedef struct _FontProxy FontProxy; +typedef struct _FontProxyClass FontProxyClass; +typedef struct _FontProxyPrivate FontProxyPrivate; + +struct _FontProxy +{ + /*< private >*/ + GDBusProxy parent_instance; + FontProxyPrivate *priv; +}; + +struct _FontProxyClass +{ + GDBusProxyClass parent_class; +}; + +GType font_proxy_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (FontProxy, g_object_unref) +#endif + +void font_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Font *font_proxy_new_finish ( + GAsyncResult *res, + GError **error); +Font *font_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + +void font_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Font *font_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error); +Font *font_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + + +/* ---- */ + +#define TYPE_FONT_SKELETON (font_skeleton_get_type ()) +#define FONT_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_FONT_SKELETON, FontSkeleton)) +#define FONT_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_FONT_SKELETON, FontSkeletonClass)) +#define FONT_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_FONT_SKELETON, FontSkeletonClass)) +#define IS_FONT_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_FONT_SKELETON)) +#define IS_FONT_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_FONT_SKELETON)) + +typedef struct _FontSkeleton FontSkeleton; +typedef struct _FontSkeletonClass FontSkeletonClass; +typedef struct _FontSkeletonPrivate FontSkeletonPrivate; + +struct _FontSkeleton +{ + /*< private >*/ + GDBusInterfaceSkeleton parent_instance; + FontSkeletonPrivate *priv; +}; + +struct _FontSkeletonClass +{ + GDBusInterfaceSkeletonClass parent_class; +}; + +GType font_skeleton_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (FontSkeleton, g_object_unref) +#endif + +Font *font_skeleton_new (void); + + +G_END_DECLS + +#endif /* __FONT_GENERATED_H__ */ diff --git a/src/personal/font/kylin-font-interface.c b/src/personal/font/kylin-font-interface.c new file mode 100644 index 0000000..9eb08da --- /dev/null +++ b/src/personal/font/kylin-font-interface.c @@ -0,0 +1,192 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include + +#define Dpi "dpi" +#define Ant "antialiasing" +#define Hint "hinting" +#define Rgba "rgba-order" + +typedef void (*METHOD1CALLBACK)(const gchar*, const GError*); +typedef void (*METHOD2CALLBACK)(const gchar*, const gint, GError*); +typedef struct methodcallback +{ + METHOD1CALLBACK callback1; + METHOD2CALLBACK callback2; +}S_METHOD_CALLBACK; + +static GMainLoop *pLoop = NULL; +static GDBusConnection *pConnection = NULL; +static Font *pProxy = NULL; + +void kylin_personal_fonts_dpi(const double in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=Dpi; + arg=g_variant_new("(sd)",key,in_arg); + font_call_transfer_double_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_dpi. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; + +} + +void kylin_personal_fonts_antialias(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=Ant; + + arg=g_variant_new("(si)",key,in_arg); + font_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_antialias. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void kylin_personal_fonts_hint(const int in_arg) +{ + + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=Hint; + arg=g_variant_new("(si)",key,in_arg); + font_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_hint. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + + void kylin_personal_fonts_rgbaorder(const int in_arg) +{ + GError* pError=NULL; + GVariant *arg=NULL; + gchar *key=Rgba; + arg=g_variant_new("(si)",key,in_arg); + font_call_transfer_int_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_rgbaorder. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; + + } + + void *run(void* arg) + { + /** start the main event loop which manages all available sources of events */ + g_main_loop_run(pLoop); + + return ((void*)0); + } + + int thread_create(void) + { + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if(0 != err){ + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; + } + + bool InitDBusFont(void) + { + bool bRet = TRUE; + GError *pConnError = NULL; + GError *pProxyError = NULL; + + do{ + bRet = TRUE; + pLoop = g_main_loop_new(NULL, FALSE); /** create main loop, but do not start it.*/ + + /** First step: get a connection */ + pConnection = g_bus_get_sync(FONT_BUS, NULL, &pConnError); + + if (NULL == pConnError){ + /** Second step: try to get a connection to the given bus.*/ + pProxy = font_proxy_new_sync(pConnection, + G_DBUS_PROXY_FLAGS_NONE, + FONT_BUS_NAME, + FONT_OBJECT_PATH, + NULL, + &pProxyError); + if (0 == pProxy){ + print_error("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message); + g_error_free(pProxyError); + bRet = FALSE; + } + + + } + else{ + print_error("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message); + g_error_free(pConnError); + bRet = FALSE; + } + }while(FALSE == bRet); + + thread_create(); + + return bRet; + } + +bool DeInitDBusFont(void) +{ + bool bRet = FALSE; + + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} diff --git a/src/personal/font/kylin-font-interface.h b/src/personal/font/kylin-font-interface.h new file mode 100644 index 0000000..39942cc --- /dev/null +++ b/src/personal/font/kylin-font-interface.h @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +//Initialize the DBus Communication +bool InitDBusFont(void); + +//Delete the DBus Communication +bool DeInitDBusFont(void); + +/* + * The resolution used for converting font sizes to pixel sizes, + * in dots per inch. + */ +void kylin_personal_fonts_dpi(const double in_arg); + +/* + * The type of antialiasing to use when rendering fonts. + * Possible values are: + * @in_arg is equal to 0, "none" for no antialiasing; + * @in_arg is equal to 1, "grayscale" for standard grayscale antialiasing; + * @in_arg is equal to 2, "rgba" for subpixel antialiasing (LCD screens only). + */ +void kylin_personal_fonts_antialias(const int in_arg); + +/* + * The type of hinting to use when rendering fonts. + * Possible values are: + * @in_arg is equal to 0, "none" for no hinting; + * @in_arg is equal to 1, "slight" for basic; + * @in_arg is equal to 2, "medium" for moderate; + * @in_arg is equal to 3, "full" for maximum hinting (may cause distortion of letter forms). + */ +void kylin_personal_fonts_hint(const int in_arg); + + /* + * The order of subpixel elements on an LCD screen; only used when antialiasing is set to "rgba". + * Possible values are: + * @in_arg is equal to 0, "rgb" for red on left (most common); + * @in_arg is equal to 1, "bgr" for blue on left; + * @in_arg is equal to 2, "vrgb" for red on top; + * @in_arg is equal to 3, "vbgr" for red on bottom. + */ +void kylin_personal_fonts_rgbaorder(const int in_arg); + +#ifdef __cplusplus +} +#endif + +#endif // FONTRENDERINGINTERFACE_H diff --git a/src/personal/font/kylin-font-server.c b/src/personal/font/kylin-font-server.c new file mode 100644 index 0000000..96e8c12 --- /dev/null +++ b/src/personal/font/kylin-font-server.c @@ -0,0 +1,198 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include "font-dbus.h" +#include "src/common/kylin-gsettings-set.h" +#include "src/common/kylin-print.h" +#include "font-generated.h" +#include + +#define schemaID "org.mate.font-rendering" + +static GMainLoop *pLoop = NULL; +static Font *pSkeleton = NULL; + +static gboolean kylin_set_double(Font* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + double value; + g_variant_get(in_arg, "(sd)", &key, &value); + + print_info("(%s,%f)\n",key,value); + + font_complete_transfer_double_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + gsettings_set_double(setting, key, value); + Dec_ref(setting); + + return TRUE; +} + + +static gboolean kylin_set_int(Font* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + int value; + g_variant_get(in_arg, "(si)", &key, &value); + + print_info("(%s,%d)\n",key,value); + + font_complete_transfer_int_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + gsettings_set_enum(setting, key, value); + Dec_ref(setting); + + return TRUE; +} + +static void bus_acquired_cb(GDBusConnection *connection, + const gchar *bus_name, + gpointer user_data) +{ + + GError *pError = NULL; + + /** Second step: Try to get a connection to the given bus. */ + pSkeleton = font_skeleton_new(); + + /** Third step: Attach to dbus signals. */ + (void) g_signal_connect(pSkeleton, "handle-transfer-double-value", G_CALLBACK(kylin_set_double), NULL); + (void) g_signal_connect(pSkeleton, "handle-transfer-int-value", G_CALLBACK(kylin_set_int), NULL); + + /** Fourth step: Export interface skeleton. */ + (void)g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(pSkeleton), + connection, + FONT_OBJECT_PATH, + &pError); + + if(pError != NULL){ + print_error("Error: Failed to export object. Reason: %s.\n", pError->message); + g_error_free(pError); + g_main_loop_quit(pLoop); + } +} + +static void name_acquired_cb(GDBusConnection *connection, + const gchar *bus_name, + gpointer user_data) +{ + print_info("name_acquired_cb call, Acquired bus name: %s.\n", FONT_BUS_NAME); +} + +static void name_lost_cb(GDBusConnection *connection, + const gchar *bus_name, + gpointer user_data) +{ + if(connection == NULL) + { + print_error("name_lost_cb call, Error: Failed to connect to dbus.\n"); + } + else + { + print_error("name_lost_cb call, Error: Failed to obtain bus name: %s.\n", FONT_BUS_NAME); + } + + g_main_loop_quit(pLoop); +} + +void* run(void* para) +{ + /** Start the Main Event Loop which manages all available sources of events */ + g_main_loop_run( pLoop ); + + return ((void*)0); +} + +int thread_create(void) +{ + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if (err != 0) + { + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; +} + + +bool InitDBusCommunicationServer(void) +{ + bool bRet = TRUE; + + g_print("InitDBusCommunicationServer: Server started.\n"); + + /** create main loop, but do not start it. */ + pLoop = g_main_loop_new(NULL, FALSE); + + /** first step: connect to dbus */ + (void)g_bus_own_name(FONT_BUS, + FONT_BUS_NAME, + G_BUS_NAME_OWNER_FLAGS_NONE, + &bus_acquired_cb, + &name_acquired_cb, + &name_lost_cb, + NULL, + NULL); + + thread_create(); + + return bRet; +} + +bool DeinitDBusCommunicationServer(void) +{ + bool bRet = FALSE; + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; + +} + +int main(void) +{ + InitDBusCommunicationServer(); + + sleep(100); + + DeinitDBusCommunicationServer(); + return 0; +} diff --git a/src/personal/marcogeneral/Makefile.am b/src/personal/marcogeneral/Makefile.am new file mode 100644 index 0000000..5a59655 --- /dev/null +++ b/src/personal/marcogeneral/Makefile.am @@ -0,0 +1,55 @@ +COMM_PRINT= -L$(top_srcdir)/src/common -lukui-print +COMM_GSETTINGS= -L$(top_srcdir)/src/common -lukui-gsettings + +#generate the .c and .h file which used by client and server side by XML file +#$(top_srcdir) represents the top-level directory of the project +DESC_XML = $(top_srcdir)/data/cn.kylinos.marcogeneral.xml +GENERATED_CH = marcogeneral-generated + +marcogeneral-generated.h marcogeneral-generated.c: $(DESC_XML) + gdbus-codegen --interface-prefix cn.kylinos. --generate-c-code $(GENERATED_CH) $(DESC_XML) + +#Generata binary file +lib_LTLIBRARIES = libukui-marcogeneralclient.la + +#gcc -wall: displays all the errors and warning information when compiling +#gcc -g: add the debugging code when compiling +COMM_CFS = -Wall -g + +#Add the dependent source file for libmarcogeneralclient.la +#marcogeneral-generated.c must be front of kylin-marcogeneral-interface.c +libukui_marcogeneralclient_la_SOURCES = marcogeneral-generated.c kylin-marcogeneral-interface.c \ + $(NULL) + +#The header files that need to be installed +include_HEADERS= kylin-marcogeneral-interface.h \ + $(NULL) + +#Additional C compiler flags +libukui_marcogeneralclient_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_marcogeneralclient_la_LDFLAGS= $(COMM_PRINT) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) + +#Generata binary file +bin_PROGRAMS = ukui-marcogeneralserver + +#Add the dependent source file for marcogeneralserver +ukui_marcogeneralserver_SOURCES = \ + marcogeneral-generated.h marcogeneral-generated.c \ + kylin-marcogeneral-server.c \ + $(NULL) + +#Additional C compiler flags +ukui_marcogeneralserver_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +ukui_marcogeneralserver_LDFLAGS= $(COMM_PRINT) $(COMM_GSETTINGS) \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) diff --git a/src/personal/marcogeneral/kylin-marcogeneral-interface.c b/src/personal/marcogeneral/kylin-marcogeneral-interface.c new file mode 100644 index 0000000..0c861f0 --- /dev/null +++ b/src/personal/marcogeneral/kylin-marcogeneral-interface.c @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include + +#define TF "titlebar-font" + +static GMainLoop *pLoop = NULL; +static GDBusConnection *pConnection = NULL; +static Marcogeneral *pProxy = NULL; + +void kylin_personal_fonts_titlebarfont(const char *in_arg) +{ + GError* pError=NULL; + GVariant* arg=NULL; + gchar *key=TF; + arg=g_variant_new("(ss)", key, in_arg); + marcogeneral_call_transfer_string_value_sync(pProxy, arg, NULL, &pError); + + if (pError != NULL){ + print_error("Failed to call method kylin_personal_fonts_titlebarfont. Reason: %s.\n", pError->message); + g_error_free(pError); + } + + return; +} + +void *run(void* arg) +{ + /** start the main event loop which manages all available sources of events */ + g_main_loop_run(pLoop); + + return ((void*)0); +} + +int thread_create(void) + { + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if(0 != err){ + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; + } + +bool InitDBusMarcogeneral(void) + { + bool bRet = TRUE; + GError *pConnError = NULL; + GError *pProxyError = NULL; + + do{ + bRet = TRUE; + pLoop = g_main_loop_new(NULL, FALSE); /** create main loop, but do not start it.*/ + + /** First step: get a connection */ + pConnection = g_bus_get_sync(MARCOGENERAL_BUS, NULL, &pConnError); + + if (NULL == pConnError){ + /** Second step: try to get a connection to the given bus.*/ + pProxy = marcogeneral_proxy_new_sync(pConnection, + G_DBUS_PROXY_FLAGS_NONE, + MARCOGENERAL_BUS_NAME, + MARCOGENERAL_OBJECT_PATH, + NULL, + &pProxyError); + if (0 == pProxy){ + print_error("InitDBusCommunication: Failed to create proxy. Reason: %s.\n", pProxyError->message); + g_error_free(pProxyError); + bRet = FALSE; + } + + + } + else{ + print_error("InitDBusCommunication: Failed to connect to dbus. Reason: %s.\n", pConnError->message); + g_error_free(pConnError); + bRet = FALSE; + } + }while(FALSE == bRet); + + thread_create(); + + return bRet; + } + +bool DeInitDBusMarcogeneral(void) +{ + bool bRet = FALSE; + + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} diff --git a/src/personal/marcogeneral/kylin-marcogeneral-interface.h b/src/personal/marcogeneral/kylin-marcogeneral-interface.h new file mode 100644 index 0000000..9393c30 --- /dev/null +++ b/src/personal/marcogeneral/kylin-marcogeneral-interface.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +#ifdef __cplusplus +extern "C" { +#endif + +//Initialize the DBus Communication +bool InitDBusMarcogeneral(void); + +//Delete the DBus Communication +bool DeInitDBusMarcogeneral(void); + +/* + * Window title font. + * + */ +void kylin_personal_fonts_titlebarfont(const char *in_arg); + +#ifdef __cplusplus +} +#endif + +#endif + + + + + + + + + + + + + diff --git a/src/personal/marcogeneral/kylin-marcogeneral-server.c b/src/personal/marcogeneral/kylin-marcogeneral-server.c new file mode 100644 index 0000000..29412f3 --- /dev/null +++ b/src/personal/marcogeneral/kylin-marcogeneral-server.c @@ -0,0 +1,176 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include +#include "marcogeneral-dbus.h" +#include "src/common/kylin-gsettings-set.h" +#include "src/common/kylin-print.h" +#include "marcogeneral-generated.h" +#include +#include + +#define schemaID "org.gnome.desktop.wm.preferences" + +static GMainLoop *pLoop = NULL; +static Marcogeneral *pSkeleton = NULL; + +static gboolean kylin_set_char(Marcogeneral* object, + GDBusMethodInvocation* invocation, + GVariant *in_arg, + gpointer user_data) +{ + gchar *key=NULL; + gchar *value=NULL; + g_variant_get(in_arg, "(ss)", &key, &value); + + marcogeneral_complete_transfer_string_value(object, invocation); + + GSettings *setting=gsettings_get_schemaID(schemaID); + gsettings_set_string(setting, key, value); + Dec_ref(setting); + + print_info("(%s, %s)\n", key, value); + + return TRUE; +} + +static void bus_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + + GError *pError = NULL; + + /** Second step: Try to get a connection to the given bus. */ + pSkeleton = marcogeneral_skeleton_new(); + + /** Third step: Attach to dbus signals. */ + (void) g_signal_connect(pSkeleton, "handle-transfer-string-value", G_CALLBACK(kylin_set_char), NULL); + + /** Fourth step: Export interface skeleton. */ + (void)g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(pSkeleton), + connection, + MARCOGENERAL_OBJECT_PATH, + &pError); + + if(pError != NULL){ + print_error("Error: Failed to export object. Reason: %s.\n", pError->message); + g_error_free(pError); + g_main_loop_quit(pLoop); + } +} + +static void name_acquired_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + print_info("name_acquired_cb call, Acquired bus name: %s.\n", MARCOGENERAL_BUS_NAME); +} + +static void name_lost_cb(GDBusConnection* connection, + const gchar* bus_name, + gpointer user_data) +{ + if(connection == NULL) + { + print_error("name_lost_cb call, Error: Failed to connect to dbus.\n"); + } + else + { + print_error("name_lost_cb call, Error: Failed to obtain bus name: %s.\n", MARCOGENERAL_BUS_NAME); + } + + g_main_loop_quit(pLoop); +} + +void* run(void* para) +{ + /** Start the Main Event Loop which manages all available sources of events */ + g_main_loop_run( pLoop ); + + return ((void*)0); +} + +int thread_create(void) +{ + int err; + pthread_t thr; + + err = pthread_create(&thr, NULL, run, NULL); + + if (err != 0) + { + + print_error("Can't create thread: %s\n", strerror(err)); + } + + return err; +} + +bool InitDBusCommunicationServer(void) +{ + bool bRet = TRUE; + + g_print("InitDBusCommunicationServer: Server started.\n"); + + /** create main loop, but do not start it. */ + pLoop = g_main_loop_new(NULL, FALSE); + + /** first step: connect to dbus */ + (void)g_bus_own_name(MARCOGENERAL_BUS, + MARCOGENERAL_BUS_NAME, + G_BUS_NAME_OWNER_FLAGS_NONE, + &bus_acquired_cb, + &name_acquired_cb, + &name_lost_cb, + NULL, + NULL); + + thread_create(); + + return bRet; +} + +bool DeinitDBusCommunicationServer(void) +{ + bool bRet = FALSE; + if(0 != pLoop){ + g_main_loop_quit(pLoop); + g_main_loop_unref(pLoop); + bRet = TRUE; + } + + return bRet; +} + +int main(void) +{ + InitDBusCommunicationServer(); + + sleep(100); + + DeinitDBusCommunicationServer(); + return 0; +} diff --git a/src/personal/marcogeneral/marcogeneral-dbus.h b/src/personal/marcogeneral/marcogeneral-dbus.h new file mode 100644 index 0000000..ff5d7bb --- /dev/null +++ b/src/personal/marcogeneral/marcogeneral-dbus.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 /* Bus define */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define MARCOGENERAL_BUS G_BUS_TYPE_SESSION +#define MARCOGENERAL_BUS_NAME "cn.kylinos.marcogeneral" +#define MARCOGENERAL_OBJECT_PATH "/cn/kylinos/marcogeneral" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/personal/marcogeneral/marcogeneral-generated.c b/src/personal/marcogeneral/marcogeneral-generated.c new file mode 100644 index 0000000..42156d5 --- /dev/null +++ b/src/personal/marcogeneral/marcogeneral-generated.c @@ -0,0 +1,1050 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#ifdef G_OS_UNIX +# include +#endif + +typedef struct +{ + GDBusArgInfo parent_struct; + gboolean use_gvariant; +} _ExtendedGDBusArgInfo; + +typedef struct +{ + GDBusMethodInfo parent_struct; + const gchar *signal_name; + gboolean pass_fdlist; +} _ExtendedGDBusMethodInfo; + +typedef struct +{ + GDBusSignalInfo parent_struct; + const gchar *signal_name; +} _ExtendedGDBusSignalInfo; + +typedef struct +{ + GDBusPropertyInfo parent_struct; + const gchar *hyphen_name; + guint use_gvariant : 1; + guint emits_changed_signal : 1; +} _ExtendedGDBusPropertyInfo; + +typedef struct +{ + GDBusInterfaceInfo parent_struct; + const gchar *hyphen_name; +} _ExtendedGDBusInterfaceInfo; + +typedef struct +{ + const _ExtendedGDBusPropertyInfo *info; + guint prop_id; + GValue orig_value; /* the value before the change */ +} ChangedProperty; + +static void +_changed_property_free (ChangedProperty *data) +{ + g_value_unset (&data->orig_value); + g_free (data); +} + +static gboolean +_g_strv_equal0 (gchar **a, gchar **b) +{ + gboolean ret = FALSE; + guint n; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + if (g_strv_length (a) != g_strv_length (b)) + goto out; + for (n = 0; a[n] != NULL; n++) + if (g_strcmp0 (a[n], b[n]) != 0) + goto out; + ret = TRUE; +out: + return ret; +} + +static gboolean +_g_variant_equal0 (GVariant *a, GVariant *b) +{ + gboolean ret = FALSE; + if (a == NULL && b == NULL) + { + ret = TRUE; + goto out; + } + if (a == NULL || b == NULL) + goto out; + ret = g_variant_equal (a, b); +out: + return ret; +} + +G_GNUC_UNUSED static gboolean +_g_value_equal (const GValue *a, const GValue *b) +{ + gboolean ret = FALSE; + g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); + switch (G_VALUE_TYPE (a)) + { + case G_TYPE_BOOLEAN: + ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); + break; + case G_TYPE_UCHAR: + ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); + break; + case G_TYPE_INT: + ret = (g_value_get_int (a) == g_value_get_int (b)); + break; + case G_TYPE_UINT: + ret = (g_value_get_uint (a) == g_value_get_uint (b)); + break; + case G_TYPE_INT64: + ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); + break; + case G_TYPE_UINT64: + ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); + break; + case G_TYPE_DOUBLE: + { + /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ + gdouble da = g_value_get_double (a); + gdouble db = g_value_get_double (b); + ret = memcmp (&da, &db, sizeof (gdouble)) == 0; + } + break; + case G_TYPE_STRING: + ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); + break; + case G_TYPE_VARIANT: + ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); + break; + default: + if (G_VALUE_TYPE (a) == G_TYPE_STRV) + ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); + else + g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); + break; + } + return ret; +} + +/* ------------------------------------------------------------------------ + * Code for interface cn.kylinos.marcogeneral + * ------------------------------------------------------------------------ + */ + +/** + * SECTION:Marcogeneral + * @title: Marcogeneral + * @short_description: Generated C code for the cn.kylinos.marcogeneral D-Bus interface + * + * This section contains code for working with the cn.kylinos.marcogeneral D-Bus interface in C. + */ + +/* ---- Introspection data for cn.kylinos.marcogeneral ---- */ + +static const _ExtendedGDBusArgInfo _marcogeneral_method_info_transfer_string_value_IN_ARG_InArg = +{ + { + -1, + (gchar *) "InArg", + (gchar *) "(ss)", + NULL + }, + FALSE +}; + +static const GDBusArgInfo * const _marcogeneral_method_info_transfer_string_value_IN_ARG_pointers[] = +{ + &_marcogeneral_method_info_transfer_string_value_IN_ARG_InArg.parent_struct, + NULL +}; + +static const _ExtendedGDBusMethodInfo _marcogeneral_method_info_transfer_string_value = +{ + { + -1, + (gchar *) "TransferStringValue", + (GDBusArgInfo **) &_marcogeneral_method_info_transfer_string_value_IN_ARG_pointers, + NULL, + NULL + }, + "handle-transfer-string-value", + FALSE +}; + +static const GDBusMethodInfo * const _marcogeneral_method_info_pointers[] = +{ + &_marcogeneral_method_info_transfer_string_value.parent_struct, + NULL +}; + +static const _ExtendedGDBusInterfaceInfo _marcogeneral_interface_info = +{ + { + -1, + (gchar *) "cn.kylinos.marcogeneral", + (GDBusMethodInfo **) &_marcogeneral_method_info_pointers, + NULL, + NULL, + NULL + }, + "marcogeneral", +}; + + +/** + * marcogeneral_interface_info: + * + * Gets a machine-readable description of the cn.kylinos.marcogeneral D-Bus interface. + * + * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. + */ +GDBusInterfaceInfo * +marcogeneral_interface_info (void) +{ + return (GDBusInterfaceInfo *) &_marcogeneral_interface_info.parent_struct; +} + +/** + * marcogeneral_override_properties: + * @klass: The class structure for a #GObject derived class. + * @property_id_begin: The property id to assign to the first overridden property. + * + * Overrides all #GObject properties in the #Marcogeneral interface for a concrete class. + * The properties are overridden in the order they are defined. + * + * Returns: The last property id. + */ +guint +marcogeneral_override_properties (GObjectClass *klass, guint property_id_begin) +{ + return property_id_begin - 1; +} + + + +/** + * Marcogeneral: + * + * Abstract interface type for the D-Bus interface cn.kylinos.marcogeneral. + */ + +/** + * MarcogeneralIface: + * @parent_iface: The parent interface. + * @handle_transfer_string_value: Handler for the #Marcogeneral::handle-transfer-string-value signal. + * + * Virtual table for the D-Bus interface cn.kylinos.marcogeneral. + */ + +typedef MarcogeneralIface MarcogeneralInterface; +G_DEFINE_INTERFACE (Marcogeneral, marcogeneral, G_TYPE_OBJECT) + +static void +marcogeneral_default_init (MarcogeneralIface *iface) +{ + /* GObject signals for incoming D-Bus method calls: */ + /** + * Marcogeneral::handle-transfer-string-value: + * @object: A #Marcogeneral. + * @invocation: A #GDBusMethodInvocation. + * @arg_InArg: Argument passed by remote caller. + * + * Signal emitted when a remote caller is invoking the TransferStringValue() D-Bus method. + * + * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call marcogeneral_complete_transfer_string_value() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. + * + * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. + */ + g_signal_new ("handle-transfer-string-value", + G_TYPE_FROM_INTERFACE (iface), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (MarcogeneralIface, handle_transfer_string_value), + g_signal_accumulator_true_handled, + NULL, + g_cclosure_marshal_generic, + G_TYPE_BOOLEAN, + 2, + G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_VARIANT); + +} + +/** + * marcogeneral_call_transfer_string_value: + * @proxy: A #MarcogeneralProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. + * @user_data: User data to pass to @callback. + * + * Asynchronously invokes the TransferStringValue() D-Bus method on @proxy. + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call marcogeneral_call_transfer_string_value_finish() to get the result of the operation. + * + * See marcogeneral_call_transfer_string_value_sync() for the synchronous, blocking version of this method. + */ +void +marcogeneral_call_transfer_string_value ( + Marcogeneral *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_dbus_proxy_call (G_DBUS_PROXY (proxy), + "TransferStringValue", + g_variant_new ("(@(ss))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + callback, + user_data); +} + +/** + * marcogeneral_call_transfer_string_value_finish: + * @proxy: A #MarcogeneralProxy. + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to marcogeneral_call_transfer_string_value(). + * @error: Return location for error or %NULL. + * + * Finishes an operation started with marcogeneral_call_transfer_string_value(). + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +marcogeneral_call_transfer_string_value_finish ( + Marcogeneral *proxy, + GAsyncResult *res, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * marcogeneral_call_transfer_string_value_sync: + * @proxy: A #MarcogeneralProxy. + * @arg_InArg: Argument to pass with the method invocation. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL. + * + * Synchronously invokes the TransferStringValue() D-Bus method on @proxy. The calling thread is blocked until a reply is received. + * + * See marcogeneral_call_transfer_string_value() for the asynchronous version of this method. + * + * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. + */ +gboolean +marcogeneral_call_transfer_string_value_sync ( + Marcogeneral *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error) +{ + GVariant *_ret; + _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), + "TransferStringValue", + g_variant_new ("(@(ss))", + arg_InArg), + G_DBUS_CALL_FLAGS_NONE, + -1, + cancellable, + error); + if (_ret == NULL) + goto _out; + g_variant_get (_ret, + "()"); + g_variant_unref (_ret); +_out: + return _ret != NULL; +} + +/** + * marcogeneral_complete_transfer_string_value: + * @object: A #Marcogeneral. + * @invocation: (transfer full): A #GDBusMethodInvocation. + * + * Helper function used in service implementations to finish handling invocations of the TransferStringValue() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. + * + * This method will free @invocation, you cannot use it afterwards. + */ +void +marcogeneral_complete_transfer_string_value ( + Marcogeneral *object, + GDBusMethodInvocation *invocation) +{ + g_dbus_method_invocation_return_value (invocation, + g_variant_new ("()")); +} + +/* ------------------------------------------------------------------------ */ + +/** + * MarcogeneralProxy: + * + * The #MarcogeneralProxy structure contains only private data and should only be accessed using the provided API. + */ + +/** + * MarcogeneralProxyClass: + * @parent_class: The parent class. + * + * Class structure for #MarcogeneralProxy. + */ + +struct _MarcogeneralProxyPrivate +{ + GData *qdata; +}; + +static void marcogeneral_proxy_iface_init (MarcogeneralIface *iface); + +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (MarcogeneralProxy, marcogeneral_proxy, G_TYPE_DBUS_PROXY, + G_ADD_PRIVATE (MarcogeneralProxy) + G_IMPLEMENT_INTERFACE (TYPE_MARCOGENERAL, marcogeneral_proxy_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (MarcogeneralProxy, marcogeneral_proxy, G_TYPE_DBUS_PROXY, + G_IMPLEMENT_INTERFACE (TYPE_MARCOGENERAL, marcogeneral_proxy_iface_init)) + +#endif +static void +marcogeneral_proxy_finalize (GObject *object) +{ + MarcogeneralProxy *proxy = MARCOGENERAL_PROXY (object); + g_datalist_clear (&proxy->priv->qdata); + G_OBJECT_CLASS (marcogeneral_proxy_parent_class)->finalize (object); +} + +static void +marcogeneral_proxy_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +marcogeneral_proxy_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec G_GNUC_UNUSED) +{ +} + +static void +marcogeneral_proxy_g_signal (GDBusProxy *proxy, + const gchar *sender_name G_GNUC_UNUSED, + const gchar *signal_name, + GVariant *parameters) +{ + _ExtendedGDBusSignalInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + gsize n; + guint signal_id; + info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_marcogeneral_interface_info.parent_struct, signal_name); + if (info == NULL) + return; + num_params = g_variant_n_children (parameters); + paramv = g_new0 (GValue, num_params + 1); + g_value_init (¶mv[0], TYPE_MARCOGENERAL); + g_value_set_object (¶mv[0], proxy); + g_variant_iter_init (&iter, parameters); + n = 1; + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_MARCOGENERAL); + g_signal_emitv (paramv, signal_id, 0, NULL); + for (n = 0; n < num_params + 1; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static void +marcogeneral_proxy_g_properties_changed (GDBusProxy *_proxy, + GVariant *changed_properties, + const gchar *const *invalidated_properties) +{ + MarcogeneralProxy *proxy = MARCOGENERAL_PROXY (_proxy); + guint n; + const gchar *key; + GVariantIter *iter; + _ExtendedGDBusPropertyInfo *info; + g_variant_get (changed_properties, "a{sv}", &iter); + while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_marcogeneral_interface_info.parent_struct, key); + g_datalist_remove_data (&proxy->priv->qdata, key); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } + g_variant_iter_free (iter); + for (n = 0; invalidated_properties[n] != NULL; n++) + { + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_marcogeneral_interface_info.parent_struct, invalidated_properties[n]); + g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); + if (info != NULL) + g_object_notify (G_OBJECT (proxy), info->hyphen_name); + } +} + +static void +marcogeneral_proxy_init (MarcogeneralProxy *proxy) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + proxy->priv = marcogeneral_proxy_get_instance_private (proxy); +#else + proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, TYPE_MARCOGENERAL_PROXY, MarcogeneralProxyPrivate); +#endif + + g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), marcogeneral_interface_info ()); +} + +static void +marcogeneral_proxy_class_init (MarcogeneralProxyClass *klass) +{ + GObjectClass *gobject_class; + GDBusProxyClass *proxy_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = marcogeneral_proxy_finalize; + gobject_class->get_property = marcogeneral_proxy_get_property; + gobject_class->set_property = marcogeneral_proxy_set_property; + + proxy_class = G_DBUS_PROXY_CLASS (klass); + proxy_class->g_signal = marcogeneral_proxy_g_signal; + proxy_class->g_properties_changed = marcogeneral_proxy_g_properties_changed; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (MarcogeneralProxyPrivate)); +#endif +} + +static void +marcogeneral_proxy_iface_init (MarcogeneralIface *iface) +{ +} + +/** + * marcogeneral_proxy_new: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Asynchronously creates a proxy for the D-Bus interface cn.kylinos.marcogeneral. See g_dbus_proxy_new() for more details. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call marcogeneral_proxy_new_finish() to get the result of the operation. + * + * See marcogeneral_proxy_new_sync() for the synchronous, blocking version of this constructor. + */ +void +marcogeneral_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_MARCOGENERAL_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.marcogeneral", NULL); +} + +/** + * marcogeneral_proxy_new_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to marcogeneral_proxy_new(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with marcogeneral_proxy_new(). + * + * Returns: (transfer full) (type MarcogeneralProxy): The constructed proxy object or %NULL if @error is set. + */ +Marcogeneral * +marcogeneral_proxy_new_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return MARCOGENERAL (ret); + else + return NULL; +} + +/** + * marcogeneral_proxy_new_sync: + * @connection: A #GDBusConnection. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: (nullable): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Synchronously creates a proxy for the D-Bus interface cn.kylinos.marcogeneral. See g_dbus_proxy_new_sync() for more details. + * + * The calling thread is blocked until a reply is received. + * + * See marcogeneral_proxy_new() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type MarcogeneralProxy): The constructed proxy object or %NULL if @error is set. + */ +Marcogeneral * +marcogeneral_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_MARCOGENERAL_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "cn.kylinos.marcogeneral", NULL); + if (ret != NULL) + return MARCOGENERAL (ret); + else + return NULL; +} + + +/** + * marcogeneral_proxy_new_for_bus: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @callback: A #GAsyncReadyCallback to call when the request is satisfied. + * @user_data: User data to pass to @callback. + * + * Like marcogeneral_proxy_new() but takes a #GBusType instead of a #GDBusConnection. + * + * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. + * You can then call marcogeneral_proxy_new_for_bus_finish() to get the result of the operation. + * + * See marcogeneral_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. + */ +void +marcogeneral_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_async_initable_new_async (TYPE_MARCOGENERAL_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.marcogeneral", NULL); +} + +/** + * marcogeneral_proxy_new_for_bus_finish: + * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to marcogeneral_proxy_new_for_bus(). + * @error: Return location for error or %NULL + * + * Finishes an operation started with marcogeneral_proxy_new_for_bus(). + * + * Returns: (transfer full) (type MarcogeneralProxy): The constructed proxy object or %NULL if @error is set. + */ +Marcogeneral * +marcogeneral_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error) +{ + GObject *ret; + GObject *source_object; + source_object = g_async_result_get_source_object (res); + ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); + g_object_unref (source_object); + if (ret != NULL) + return MARCOGENERAL (ret); + else + return NULL; +} + +/** + * marcogeneral_proxy_new_for_bus_sync: + * @bus_type: A #GBusType. + * @flags: Flags from the #GDBusProxyFlags enumeration. + * @name: A bus name (well-known or unique). + * @object_path: An object path. + * @cancellable: (nullable): A #GCancellable or %NULL. + * @error: Return location for error or %NULL + * + * Like marcogeneral_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. + * + * The calling thread is blocked until a reply is received. + * + * See marcogeneral_proxy_new_for_bus() for the asynchronous version of this constructor. + * + * Returns: (transfer full) (type MarcogeneralProxy): The constructed proxy object or %NULL if @error is set. + */ +Marcogeneral * +marcogeneral_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error) +{ + GInitable *ret; + ret = g_initable_new (TYPE_MARCOGENERAL_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "cn.kylinos.marcogeneral", NULL); + if (ret != NULL) + return MARCOGENERAL (ret); + else + return NULL; +} + + +/* ------------------------------------------------------------------------ */ + +/** + * MarcogeneralSkeleton: + * + * The #MarcogeneralSkeleton structure contains only private data and should only be accessed using the provided API. + */ + +/** + * MarcogeneralSkeletonClass: + * @parent_class: The parent class. + * + * Class structure for #MarcogeneralSkeleton. + */ + +struct _MarcogeneralSkeletonPrivate +{ + GValue *properties; + GList *changed_properties; + GSource *changed_properties_idle_source; + GMainContext *context; + GMutex lock; +}; + +static void +_marcogeneral_skeleton_handle_method_call ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name, + const gchar *method_name, + GVariant *parameters, + GDBusMethodInvocation *invocation, + gpointer user_data) +{ + MarcogeneralSkeleton *skeleton = MARCOGENERAL_SKELETON (user_data); + _ExtendedGDBusMethodInfo *info; + GVariantIter iter; + GVariant *child; + GValue *paramv; + gsize num_params; + guint num_extra; + gsize n; + guint signal_id; + GValue return_value = G_VALUE_INIT; + info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); + g_assert (info != NULL); + num_params = g_variant_n_children (parameters); + num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); + n = 0; + g_value_init (¶mv[n], TYPE_MARCOGENERAL); + g_value_set_object (¶mv[n++], skeleton); + g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); + g_value_set_object (¶mv[n++], invocation); + if (info->pass_fdlist) + { +#ifdef G_OS_UNIX + g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); + g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); +#else + g_assert_not_reached (); +#endif + } + g_variant_iter_init (&iter, parameters); + while ((child = g_variant_iter_next_value (&iter)) != NULL) + { + _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; + if (arg_info->use_gvariant) + { + g_value_init (¶mv[n], G_TYPE_VARIANT); + g_value_set_variant (¶mv[n], child); + n++; + } + else + g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); + g_variant_unref (child); + } + signal_id = g_signal_lookup (info->signal_name, TYPE_MARCOGENERAL); + g_value_init (&return_value, G_TYPE_BOOLEAN); + g_signal_emitv (paramv, signal_id, 0, &return_value); + if (!g_value_get_boolean (&return_value)) + g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); + g_value_unset (&return_value); + for (n = 0; n < num_params + num_extra; n++) + g_value_unset (¶mv[n]); + g_free (paramv); +} + +static GVariant * +_marcogeneral_skeleton_handle_get_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GError **error, + gpointer user_data) +{ + MarcogeneralSkeleton *skeleton = MARCOGENERAL_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + GVariant *ret; + ret = NULL; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_marcogeneral_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + g_value_init (&value, pspec->value_type); + g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); + ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); + g_value_unset (&value); + } + return ret; +} + +static gboolean +_marcogeneral_skeleton_handle_set_property ( + GDBusConnection *connection G_GNUC_UNUSED, + const gchar *sender G_GNUC_UNUSED, + const gchar *object_path G_GNUC_UNUSED, + const gchar *interface_name G_GNUC_UNUSED, + const gchar *property_name, + GVariant *variant, + GError **error, + gpointer user_data) +{ + MarcogeneralSkeleton *skeleton = MARCOGENERAL_SKELETON (user_data); + GValue value = G_VALUE_INIT; + GParamSpec *pspec; + _ExtendedGDBusPropertyInfo *info; + gboolean ret; + ret = FALSE; + info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_marcogeneral_interface_info.parent_struct, property_name); + g_assert (info != NULL); + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); + if (pspec == NULL) + { + g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); + } + else + { + if (info->use_gvariant) + g_value_set_variant (&value, variant); + else + g_dbus_gvariant_to_gvalue (variant, &value); + g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); + g_value_unset (&value); + ret = TRUE; + } + return ret; +} + +static const GDBusInterfaceVTable _marcogeneral_skeleton_vtable = +{ + _marcogeneral_skeleton_handle_method_call, + _marcogeneral_skeleton_handle_get_property, + _marcogeneral_skeleton_handle_set_property, + {NULL} +}; + +static GDBusInterfaceInfo * +marcogeneral_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return marcogeneral_interface_info (); +} + +static GDBusInterfaceVTable * +marcogeneral_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) +{ + return (GDBusInterfaceVTable *) &_marcogeneral_skeleton_vtable; +} + +static GVariant * +marcogeneral_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) +{ + MarcogeneralSkeleton *skeleton = MARCOGENERAL_SKELETON (_skeleton); + + GVariantBuilder builder; + guint n; + g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); + if (_marcogeneral_interface_info.parent_struct.properties == NULL) + goto out; + for (n = 0; _marcogeneral_interface_info.parent_struct.properties[n] != NULL; n++) + { + GDBusPropertyInfo *info = _marcogeneral_interface_info.parent_struct.properties[n]; + if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) + { + GVariant *value; + value = _marcogeneral_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "cn.kylinos.marcogeneral", info->name, NULL, skeleton); + if (value != NULL) + { + g_variant_take_ref (value); + g_variant_builder_add (&builder, "{sv}", info->name, value); + g_variant_unref (value); + } + } + } +out: + return g_variant_builder_end (&builder); +} + +static void +marcogeneral_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) +{ +} + +static void marcogeneral_skeleton_iface_init (MarcogeneralIface *iface); +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 +G_DEFINE_TYPE_WITH_CODE (MarcogeneralSkeleton, marcogeneral_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_ADD_PRIVATE (MarcogeneralSkeleton) + G_IMPLEMENT_INTERFACE (TYPE_MARCOGENERAL, marcogeneral_skeleton_iface_init)) + +#else +G_DEFINE_TYPE_WITH_CODE (MarcogeneralSkeleton, marcogeneral_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, + G_IMPLEMENT_INTERFACE (TYPE_MARCOGENERAL, marcogeneral_skeleton_iface_init)) + +#endif +static void +marcogeneral_skeleton_finalize (GObject *object) +{ + MarcogeneralSkeleton *skeleton = MARCOGENERAL_SKELETON (object); + g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); + if (skeleton->priv->changed_properties_idle_source != NULL) + g_source_destroy (skeleton->priv->changed_properties_idle_source); + g_main_context_unref (skeleton->priv->context); + g_mutex_clear (&skeleton->priv->lock); + G_OBJECT_CLASS (marcogeneral_skeleton_parent_class)->finalize (object); +} + +static void +marcogeneral_skeleton_init (MarcogeneralSkeleton *skeleton) +{ +#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 + skeleton->priv = marcogeneral_skeleton_get_instance_private (skeleton); +#else + skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, TYPE_MARCOGENERAL_SKELETON, MarcogeneralSkeletonPrivate); +#endif + + g_mutex_init (&skeleton->priv->lock); + skeleton->priv->context = g_main_context_ref_thread_default (); +} + +static void +marcogeneral_skeleton_class_init (MarcogeneralSkeletonClass *klass) +{ + GObjectClass *gobject_class; + GDBusInterfaceSkeletonClass *skeleton_class; + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = marcogeneral_skeleton_finalize; + + skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); + skeleton_class->get_info = marcogeneral_skeleton_dbus_interface_get_info; + skeleton_class->get_properties = marcogeneral_skeleton_dbus_interface_get_properties; + skeleton_class->flush = marcogeneral_skeleton_dbus_interface_flush; + skeleton_class->get_vtable = marcogeneral_skeleton_dbus_interface_get_vtable; + +#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 + g_type_class_add_private (klass, sizeof (MarcogeneralSkeletonPrivate)); +#endif +} + +static void +marcogeneral_skeleton_iface_init (MarcogeneralIface *iface) +{ +} + +/** + * marcogeneral_skeleton_new: + * + * Creates a skeleton object for the D-Bus interface cn.kylinos.marcogeneral. + * + * Returns: (transfer full) (type MarcogeneralSkeleton): The skeleton object. + */ +Marcogeneral * +marcogeneral_skeleton_new (void) +{ + return MARCOGENERAL (g_object_new (TYPE_MARCOGENERAL_SKELETON, NULL)); +} + diff --git a/src/personal/marcogeneral/marcogeneral-generated.h b/src/personal/marcogeneral/marcogeneral-generated.h new file mode 100644 index 0000000..89e2ddb --- /dev/null +++ b/src/personal/marcogeneral/marcogeneral-generated.h @@ -0,0 +1,190 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 + +G_BEGIN_DECLS + + +/* ------------------------------------------------------------------------ */ +/* Declarations for cn.kylinos.marcogeneral */ + +#define TYPE_MARCOGENERAL (marcogeneral_get_type ()) +#define MARCOGENERAL(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_MARCOGENERAL, Marcogeneral)) +#define IS_MARCOGENERAL(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_MARCOGENERAL)) +#define MARCOGENERAL_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), TYPE_MARCOGENERAL, MarcogeneralIface)) + +struct _Marcogeneral; +typedef struct _Marcogeneral Marcogeneral; +typedef struct _MarcogeneralIface MarcogeneralIface; + +struct _MarcogeneralIface +{ + GTypeInterface parent_iface; + + gboolean (*handle_transfer_string_value) ( + Marcogeneral *object, + GDBusMethodInvocation *invocation, + GVariant *arg_InArg); + +}; + +GType marcogeneral_get_type (void) G_GNUC_CONST; + +GDBusInterfaceInfo *marcogeneral_interface_info (void); +guint marcogeneral_override_properties (GObjectClass *klass, guint property_id_begin); + + +/* D-Bus method call completion functions: */ +void marcogeneral_complete_transfer_string_value ( + Marcogeneral *object, + GDBusMethodInvocation *invocation); + + + +/* D-Bus method calls: */ +void marcogeneral_call_transfer_string_value ( + Marcogeneral *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); + +gboolean marcogeneral_call_transfer_string_value_finish ( + Marcogeneral *proxy, + GAsyncResult *res, + GError **error); + +gboolean marcogeneral_call_transfer_string_value_sync ( + Marcogeneral *proxy, + GVariant *arg_InArg, + GCancellable *cancellable, + GError **error); + + + +/* ---- */ + +#define TYPE_MARCOGENERAL_PROXY (marcogeneral_proxy_get_type ()) +#define MARCOGENERAL_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_MARCOGENERAL_PROXY, MarcogeneralProxy)) +#define MARCOGENERAL_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_MARCOGENERAL_PROXY, MarcogeneralProxyClass)) +#define MARCOGENERAL_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_MARCOGENERAL_PROXY, MarcogeneralProxyClass)) +#define IS_MARCOGENERAL_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_MARCOGENERAL_PROXY)) +#define IS_MARCOGENERAL_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_MARCOGENERAL_PROXY)) + +typedef struct _MarcogeneralProxy MarcogeneralProxy; +typedef struct _MarcogeneralProxyClass MarcogeneralProxyClass; +typedef struct _MarcogeneralProxyPrivate MarcogeneralProxyPrivate; + +struct _MarcogeneralProxy +{ + /*< private >*/ + GDBusProxy parent_instance; + MarcogeneralProxyPrivate *priv; +}; + +struct _MarcogeneralProxyClass +{ + GDBusProxyClass parent_class; +}; + +GType marcogeneral_proxy_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (MarcogeneralProxy, g_object_unref) +#endif + +void marcogeneral_proxy_new ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Marcogeneral *marcogeneral_proxy_new_finish ( + GAsyncResult *res, + GError **error); +Marcogeneral *marcogeneral_proxy_new_sync ( + GDBusConnection *connection, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + +void marcogeneral_proxy_new_for_bus ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data); +Marcogeneral *marcogeneral_proxy_new_for_bus_finish ( + GAsyncResult *res, + GError **error); +Marcogeneral *marcogeneral_proxy_new_for_bus_sync ( + GBusType bus_type, + GDBusProxyFlags flags, + const gchar *name, + const gchar *object_path, + GCancellable *cancellable, + GError **error); + + +/* ---- */ + +#define TYPE_MARCOGENERAL_SKELETON (marcogeneral_skeleton_get_type ()) +#define MARCOGENERAL_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), TYPE_MARCOGENERAL_SKELETON, MarcogeneralSkeleton)) +#define MARCOGENERAL_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), TYPE_MARCOGENERAL_SKELETON, MarcogeneralSkeletonClass)) +#define MARCOGENERAL_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), TYPE_MARCOGENERAL_SKELETON, MarcogeneralSkeletonClass)) +#define IS_MARCOGENERAL_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), TYPE_MARCOGENERAL_SKELETON)) +#define IS_MARCOGENERAL_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), TYPE_MARCOGENERAL_SKELETON)) + +typedef struct _MarcogeneralSkeleton MarcogeneralSkeleton; +typedef struct _MarcogeneralSkeletonClass MarcogeneralSkeletonClass; +typedef struct _MarcogeneralSkeletonPrivate MarcogeneralSkeletonPrivate; + +struct _MarcogeneralSkeleton +{ + /*< private >*/ + GDBusInterfaceSkeleton parent_instance; + MarcogeneralSkeletonPrivate *priv; +}; + +struct _MarcogeneralSkeletonClass +{ + GDBusInterfaceSkeletonClass parent_class; +}; + +GType marcogeneral_skeleton_get_type (void) G_GNUC_CONST; + +#if GLIB_CHECK_VERSION(2, 44, 0) +G_DEFINE_AUTOPTR_CLEANUP_FUNC (MarcogeneralSkeleton, g_object_unref) +#endif + +Marcogeneral *marcogeneral_skeleton_new (void); + + +G_END_DECLS + +#endif /* __MARCOGENERAL_GENERATED_H__ */ diff --git a/src/security/Makefile.am b/src/security/Makefile.am new file mode 100644 index 0000000..e69de29 diff --git a/src/software/Makefile.am b/src/software/Makefile.am new file mode 100644 index 0000000..b7a7292 --- /dev/null +++ b/src/software/Makefile.am @@ -0,0 +1 @@ +SUBDIRS=defaultprograms diff --git a/src/software/defaultprograms/Makefile.am b/src/software/defaultprograms/Makefile.am new file mode 100644 index 0000000..66792c3 --- /dev/null +++ b/src/software/defaultprograms/Makefile.am @@ -0,0 +1,24 @@ +#Generata binary file +lib_LTLIBRARIES = libukui-defaultprograms.la + +#gcc -wall: displays all the errors and warning information when compiling +#gcc -g: add the debugging code when compiling +COMM_CFS = -Wall -g + +#Add the dependent source file for libdefaultprograms.la +libukui_defaultprograms_la_SOURCES = kylin-defaultprograms-interface.c \ + $(NULL) + +#The header files that need to be installed +include_HEADERS= kylin-defaultprograms-interface.h \ + $(NULL) + +#Additional C compiler flags +libukui_defaultprograms_la_CFLAGS= $(COMM_CFS) \ + $(GLIB_2_CFLAGS) $(GIO_2_CFLAGS) $(GIO_UNIX_2_CFLAGS) \ + $(NULL) + +#Additional link objects +libukui_defaultprograms_la_LDFLAGS= \ + $(GLIB_2_LIBS) $(GIO_2_LIBS) $(GIO_UNIX_2_LIBS) \ + $(NULL) diff --git a/src/software/defaultprograms/kylin-defaultprograms-interface.c b/src/software/defaultprograms/kylin-defaultprograms-interface.c new file mode 100644 index 0000000..9d5e7f8 --- /dev/null +++ b/src/software/defaultprograms/kylin-defaultprograms-interface.c @@ -0,0 +1,469 @@ +/* + * Copyright (C) 2019 Tianjin KYLIN Information Technology Co., 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 3, 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 +#include +#include +#include +#include +#include +#include "kylin-defaultprograms-interface.h" + +typedef struct _AppInfo +{ + GAppInfo *item; +}Appinfo;//用于存放应用列表信息 + +//获取给定类型的所有应用程序列表 +static Appinfo *kylin_software_defaultprograms_getapplist(const char *content_type) +{ + GList *applist; + applist=g_app_info_get_all_for_type(content_type); + GAppInfo* item; + + if(applist!=NULL) + { + guint len=g_list_length(applist); + Appinfo *appinfo=(Appinfo *)malloc(sizeof(Appinfo)*(len+1)); + + //获取应用列表 + for (guint index=0; index < len; index++) + { + item = (GAppInfo*) g_list_nth_data(applist, index); + appinfo[index].item=item; + // const char *id=g_app_info_get_name(appinfo[index].item); + // const char *ID=g_app_info_get_id(appinfo[index].item); + // printf("%s,%s\n", id, ID); + + } + + appinfo[len].item=NULL; + return appinfo; + } + else{ + return NULL; + } + +} + +AppList *kylin_software_defaultprograms_getappidlist(const char *content_type) +{ + Appinfo *appinfo=kylin_software_defaultprograms_getapplist(content_type); + + if(appinfo!=NULL) + { + gint i=0; + while(appinfo[i].item!=NULL) + i++; + + AppList *list=(AppList *)malloc(sizeof(AppList)*(i+1)); + int count=i; + int index=0; + for(gint j=0;appinfo[j].item!=NULL;j++) + { + + const char *id=g_app_info_get_id(appinfo[j].item); + if(id!=NULL) + { + gint len=strlen(id); + list[index].appid=(char *)malloc(sizeof(char)*(len+1)); + strcpy(list[index].appid,id); + index++; + } + else{ + free(list+count); + count--; + } + + } + list[count].appid=NULL; + free(appinfo); + return list; + } + else{ + return NULL; + } + +} + +//获取当前默认应用 +char *kylin_software_defaultprograms_getdefaultappid(const char *content_type) +{ + GAppInfo *app=g_app_info_get_default_for_type(content_type, false); + if(app!=NULL) + { + const char *id=g_app_info_get_id(app); + if(id!=NULL) + { + gint len=strlen(id); + char *appid=(char *)malloc(sizeof(char)*(len+1)); + strcpy(appid,id); + return appid; + } + else + { + return NULL; + } + + } + else{ + return NULL; + } + +} + +//获取应用支持的内容类型 +Contenttype *kylin_software_defaultprograms_getappcontenttype(char *appid) +{ + GList *applist=g_app_info_get_all(); + + if(applist!=NULL) + { + GAppInfo* item; + + guint len=g_list_length(applist); + + //获取应用列表 + for (guint index=0; index < len; index++) + { + item = (GAppInfo*) g_list_nth_data(applist, index); + const char *id=g_app_info_get_id(item); + int result=strcmp(id,appid); + if(result==0) + { + const char **types=g_app_info_get_supported_types(item); + if(types!=NULL) + { + int num=0; + + while(*(types+num)) + { + num++; + } +// printf("%d\n",num); + + Contenttype *contenttype=(Contenttype *)malloc(sizeof(Contenttype)*(num+1)); + + for(int j=0;j + +#ifdef __cplusplus +extern "C"{ +#endif + +typedef struct _ContentType +{ + char *type; +}Contenttype;//用于存放应用支持的内容类型 + +typedef struct _Applist +{ + char *appid; +}AppList;//用于存放应用列表 + +/** + * Gets the list of applications. + * @content_type is the content-type the application supported. + * @return the struct pointer. + */ +AppList *kylin_software_defaultprograms_getappidlist(const char *content_type); + +/** + * Gets the current default application. + * @content_type is the content-type the application supported. + * @return the default application id. + */ +char *kylin_software_defaultprograms_getdefaultappid(const char *content_type); + +/** + * Gets the content type supported by the application. + * @appid is the application id. + * return the struct pointer. + */ +Contenttype *kylin_software_defaultprograms_getappcontenttype(char *appid); + +/** + * Adds a content type to the application information. + * @content_type is the type that need to be added,Some content types are suggested as follows: + * web browsers: "x-scheme-handler/http" + * mail readers: "x-scheme-handler/mailto" + * image viewers: "image/png" + * media players: "audio/x-vorbis+ogg" + * video players: "video/x-ogm+ogg" + * text_editors: "text/plain". + * @appid is the application id. + * return ture on success, or false on error. + */ +bool kylin_software_defaultprograms_addapptype(const char *content_type, + char *appid); +/** + * Removes a supported type from an application. + * @content_type is a supported type. + * @appid is the application id. + * return ture on success, or false on error. + */ +bool kylin_software_defaultprograms_delapptype(const char *content_type, + char *appid); + +/** + * Set the default web browser. + * @appid is the application id. + */ +bool kylin_software_defaultprograms_setwebbrowsers(char *appid); + +/** + * Set the default mail readers. + * @appid is the application id. + */ +bool kylin_software_defaultprograms_setmailreaders(char *appid); + +/** + * Set the default image viewers. + * @appid is the application id. + */ +bool kylin_software_defaultprograms_setimageviewers(char *appid); + +/** + * Set the default audio players. + * @appid is the application id. + */ +bool kylin_software_defaultprograms_setaudioplayers(char *appid); + +/** + * Set the default video players. + * @appid is the application id. + */ +bool kylin_software_defaultprograms_setvideoplayers(char *appid); + +/** + * Set the default text editors. + * @appid is the application id. + */ +bool kylin_software_defaultprograms_settexteditors(char *appid); + + +#ifdef __cplusplus +} +#endif + +#endif // KYLINDEFAULTPROGRAMSINTERFACE_H diff --git a/src/updates/Makefile.am b/src/updates/Makefile.am new file mode 100644 index 0000000..e69de29