pax_global_header00006660000000000000000000000064141426324220014512gustar00rootroot0000000000000052 comment=4b0a2dfd008553e8ab1a6b5dd8f72330373b464b go-gir-generator-master/000077500000000000000000000000001414263242200155175ustar00rootroot00000000000000go-gir-generator-master/CHANGELOG.md000066400000000000000000000015221414263242200173300ustar00rootroot00000000000000[2.0.2] 2019-05-09 * fix: memory test failed on arm64 arch * feat: memory test comparing growth [2.0.1] 2019-04-16 * Fix path in Makefile. * chore: improve english [2.0.0] 2019-03-01 * chore: put code into pkg.deepin.io dir * fix: build issues with new glib2/gobject-introspection ## [1.2.0] - 2019-01-03 * chore: compile with sw arch no longer needs to use gccgo * fix: dde-api build error with gobject-introspection 1.58+ ## [1.1.0] - 2018-10-25 * fix: `sw_64` no export `USE_GCCGO=1` ## [1.0.4] - 2018-08-12 * fix: `sw_64` gccgo720 build failed * fix: build failed SettingsBackendLike undefined ## [1.0.3] - 2018-03-09 - docs: rewirte Chinglish style README part - fix: Adapt lintian - Support `g_bytes_get_data()` - Install missing Typelib file for GUdev ## [1.0.2] - 2017-10-12 - Fix gobject map concurrent crashed go-gir-generator-master/LICENSE000066400000000000000000001045131414263242200165300ustar00rootroot00000000000000 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 . go-gir-generator-master/Makefile000066400000000000000000000030301414263242200171530ustar00rootroot00000000000000PREFIX = /usr GOBUILD = go build GOTEST = go build GORUN = go run OUT_GIR_DIR = out/src/pkg.deepin.io/gir/ export GO111MODULE=off all: build CURRENT_DIR = $(shell pwd) export GOPATH = $(CURDIR):$(CURDIR)/vendor:$(CURDIR)/out GENERATOR = out/gir-generator build: glib-2.0 gobject-2.0 gio-2.0 gudev-1.0 copyfile generator: mkdir -p $(OUT_GIR_DIR) cd src/gir-generator && ${GOBUILD} -o $(CURRENT_DIR)/${GENERATOR} copyfile: cp -r lib.in/gobject-2.0 $(OUT_GIR_DIR) cp -r lib.in/gio-2.0 $(OUT_GIR_DIR) cp -r lib.in/glib-2.0 $(OUT_GIR_DIR) cp -r lib.in/gudev-1.0 $(OUT_GIR_DIR) glib-2.0: lib.in/glib-2.0/glib.go.in lib.in/glib-2.0/config.json generator ${GENERATOR} -o $(OUT_GIR_DIR)$@ $< gobject-2.0: lib.in/gobject-2.0/gobject.go.in lib.in/gobject-2.0/config.json generator ${GENERATOR} -o $(OUT_GIR_DIR)$@ $< gio-2.0: lib.in/gio-2.0/gio.go.in lib.in/gio-2.0/config.json generator ${GENERATOR} -o $(OUT_GIR_DIR)$@ $< gudev-1.0: lib.in/gudev-1.0/gudev.go.in lib.in/gudev-1.0/config.json generator ${GENERATOR} -o $(OUT_GIR_DIR)$@ $< test: cd $(OUT_GIR_DIR)gobject-2.0 && ${GOTEST} cd $(OUT_GIR_DIR)gio-2.0 && ${GOTEST} cd $(OUT_GIR_DIR)glib-2.0 && ${GOTEST} cd $(OUT_GIR_DIR)gudev-1.0 && ${GOTEST} @echo "Memory Testing" ${GORUN} test/memory.go install: install -d $(DESTDIR)$(PREFIX)/share/gocode/src/pkg.deepin.io/gir $(DESTDIR)$(PREFIX)/bin cp -r $(OUT_GIR_DIR)* $(DESTDIR)$(PREFIX)/share/gocode/src/pkg.deepin.io/gir cp out/gir-generator $(DESTDIR)$(PREFIX)/bin/ clean: rm -fr out .PHONY: test go-gir-generator-master/README.md000066400000000000000000000037411414263242200170030ustar00rootroot00000000000000# go-gir-generator ## Description Project go-gir-generator implements GObject-introspection based bindings generator for Go. There are many Go bindings of GObject/Gtk libraries out there, but almost all of them are written by hand. It's boring and error-prone since the corresponding C library may change very often. go-gir-generator can adapt to the newest version of GObject without changing one single line of code, which makes it less painful to write Go code with GObject. *NOTE: Currently it only supports GObject-2.0, Glib-2.0, Gio-2.0, support of Gdk/Gtk is not completed.* Many thanks to the genius guys who created the [GObject Introspection](https://wiki.gnome.org/action/show/Projects/GObjectIntrospection) and the original author [nsf](https://github.com/nsf/gogobject). ## Dependencies ### Build dependencies - golang 1.3 above - pkg-config - gobject-introspection-1.0 ### Runtime dependencies - gobject-introspection-1.0 ## Installation Install prerequisites ``` $ apt-get install libgirepository1.0-dev libgudev-1.0-dev $ make install ``` ## Usage The binary program gir-generator is the static binding code generator. It read the GIRepository and template files from lib.in directory. For example, we need generate gobject-2.0 binding, ``` cd lib.in/gobject-2.0 gir-generator -o . gobject.go.in ``` Note: deepin generate all bindings under $GOPATH/src/gir/$PackageName ## Getting help Any usage issues can ask for help via * [Gitter](https://gitter.im/orgs/linuxdeepin/rooms) * [IRC channel](https://webchat.freenode.net/?channels=deepin) * [Forum](https://bbs.deepin.org) * [WiKi](http://wiki.deepin.org/) ## Getting involved We encourage you to report issues and contribute changes * [Contribution guide for users](http://wiki.deepin.org/index.php?title=Contribution_Guidelines_for_Users) * [Contribution guide for developers](http://wiki.deepin.org/index.php?title=Contribution_Guidelines_for_Developers) ## License go-gir-generator is licensed under [GPLv3](LICENSE). go-gir-generator-master/debian/000077500000000000000000000000001414263242200167415ustar00rootroot00000000000000go-gir-generator-master/debian/changelog000066400000000000000000000034461414263242200206220ustar00rootroot00000000000000go-gir-generator (0.9.5-1) stable; urgency=low * Autobuild Tag 0.9.5 -- TagBuilder Wed, 03 Aug 2016 08:54:04 +0000 go-gir-generator (0.9.4-1) stable; urgency=low * Autobuild Tag 0.9.4 -- TagBuilder Sat, 09 Jul 2016 00:40:37 +0000 go-gir-generator (0.9.3-1) stable; urgency=low * Autobuild Tag 0.9.3 -- TagBuilder Mon, 23 May 2016 09:20:44 +0000 go-gir-generator (0.9.2-6) stable; urgency=low * Rebuild Version 0.9.2 -- TagBuilder Thu, 21 Apr 2016 15:54:09 +0000 go-gir-generator (0.9.2-5) stable; urgency=low * Rebuild Version 0.9.2 -- TagBuilder Mon, 22 Feb 2016 09:20:37 +0000 go-gir-generator (0.9.2-4) stable; urgency=low * Rebuild Version 0.9.2 -- TagBuilder Mon, 25 Jan 2016 17:16:12 +0000 go-gir-generator (0.9.2-3) stable; urgency=low * Rebuild Version 0.9.2 -- TagBuilder Mon, 25 Jan 2016 16:36:37 +0000 go-gir-generator (0.9.2-2) stable; urgency=low * Rebuild Version 0.9.2 -- TagBuilder Mon, 25 Jan 2016 16:21:09 +0000 go-gir-generator (0.9.2-1) stable; urgency=low * Autobuild Tag 0.9.2 -- TagBuilder Tue, 29 Dec 2015 21:00:07 +0000 go-gir-generator (0.9.1-1) stable; urgency=low * Autobuild Tag 0.9.1 -- TagBuilder Fri, 18 Dec 2015 17:50:47 +0000 go-gir-generator (0.9.0-1) stable; urgency=low * Autobuild Tag 0.9.0 -- TagBuilder Fri, 18 Dec 2015 16:53:49 +0000 go-gir-generator (0.0.1) unstable; urgency=low * Initial release -- Deepin Packages Builder Mon, 30 Nov 2015 11:02:47 +0800 go-gir-generator-master/debian/compat000066400000000000000000000000021414263242200201370ustar00rootroot000000000000009 go-gir-generator-master/debian/control000066400000000000000000000032731414263242200203510ustar00rootroot00000000000000Source: go-gir-generator Section: devel Priority: optional Maintainer: Deepin Packages Builder Build-Depends: debhelper (>= 9), dh-golang, golang-go, libgirepository1.0-dev, libgtk-3-dev,libgudev-1.0-dev Standards-Version: 3.9.8 Homepage: http://www.deepin.org Package: golang-gir-gobject-2.0-dev Architecture: any Depends: ${shlibs:Depends}, ${misc:Depends}, libglib2.0-dev, Conflicts: golang-gir-gobject-2.0 Breaks: golang-gir-gobject-2.0 (<< 0.9.3) Provides: golang-gir-gobject-2.0 Description: Go bindings Go bindings for Deepin Desktop Environment development. . gobject-2.0 go bindings. Package: golang-gir-gio-2.0-dev Architecture: any Depends: ${shlibs:Depends}, ${misc:Depends}, libglib2.0-dev, Conflicts: golang-gir-gio-2.0 Provides: golang-gir-gio-2.0 Breaks: golang-gir-gio-2.0 (<< 0.9.3) Description: Go bindings Go bindings for Deepin Desktop Environment development. . gio-2.0 go bindings. Package: golang-gir-glib-2.0-dev Architecture: any Depends: ${shlibs:Depends}, ${misc:Depends}, libglib2.0-dev, Conflicts: golang-gir-glib-2.0 Provides: golang-gir-glib-2.0 Breaks: golang-gir-glib-2.0 (<< 0.9.3) Description: Go bindings Go bindings for Deepin Desktop Environment development . glib-2.0 go bindings. Package: golang-gir-gudev-1.0-dev Architecture: any Depends: ${shlibs:Depends}, ${misc:Depends}, libgudev-1.0-dev, Description: Go bindings Go bindings for Deepin Desktop Environment development . gudev-1.0 go bindings. Package: golang-gir-generator Architecture: any Depends: ${shlibs:Depends}, ${misc:Depends}, Description: generate library binding code which support gir for golang. This tool can generate library binding code which support gir for golang. go-gir-generator-master/debian/copyright000066400000000000000000000016541414263242200207020ustar00rootroot00000000000000Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: go-gir-generator Files: * Copyright: 2017 Deepin Technology Co., Ltd. License: GPL-3+ This package is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. . This package is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. . You should have received a copy of the GNU General Public License along with this program. If not, see . On Debian systems, the complete text of the GNU General Public License version 3 can be found in "/usr/share/common-licenses/GPL-3". go-gir-generator-master/debian/docs000066400000000000000000000000121414263242200176050ustar00rootroot00000000000000README.md go-gir-generator-master/debian/golang-gir-generator.install000066400000000000000000000000101414263242200243320ustar00rootroot00000000000000usr/bin go-gir-generator-master/debian/golang-gir-gio-2.0-dev.install000066400000000000000000000000571414263242200242060ustar00rootroot00000000000000usr/share/gocode/src/pkg.deepin.io/gir/gio-2.0 go-gir-generator-master/debian/golang-gir-glib-2.0-dev.install000066400000000000000000000000601414263242200243370ustar00rootroot00000000000000usr/share/gocode/src/pkg.deepin.io/gir/glib-2.0 go-gir-generator-master/debian/golang-gir-gobject-2.0-dev.install000066400000000000000000000000631414263242200250420ustar00rootroot00000000000000usr/share/gocode/src/pkg.deepin.io/gir/gobject-2.0 go-gir-generator-master/debian/golang-gir-gudev-1.0-dev.install000066400000000000000000000000611414263242200245340ustar00rootroot00000000000000usr/share/gocode/src/pkg.deepin.io/gir/gudev-1.0 go-gir-generator-master/debian/rules000077500000000000000000000001021414263242200200120ustar00rootroot00000000000000#!/usr/bin/make -f export GOCACHE := /tmp/gocache %: dh $@ go-gir-generator-master/debian/source/000077500000000000000000000000001414263242200202415ustar00rootroot00000000000000go-gir-generator-master/debian/source/format000066400000000000000000000000151414263242200214500ustar00rootroot000000000000003.0 (native) go-gir-generator-master/documentation/000077500000000000000000000000001414263242200203705ustar00rootroot00000000000000go-gir-generator-master/documentation/Design.txt000066400000000000000000000130761414263242200223510ustar00rootroot00000000000000 --==* GObject-introspection based bindings generator for Go *==-- What's implemented and how. 1. OBJECTS In Go GObject is represented as a pointer to a pointer which points to the real GObject owned by C. See the code: type Object struct { ptr *C.GObject } var obj *Object Or a picture: +-----------------+ \ +----------------+ \ +------------------+ | Go pointer -|-----| C pointer -|-----| C GObject | | (stack memory) | / | (GCed memory) | / | (gobject memory) | +-----------------+ +----------------+ +------------------+ It's done that way, because that struct, which basically holds a chunk of garbage collected memory represents a reference owner of the particular GObject. When it is allocated, the reference count of GObject is incremented and when GC is about to collect that memory, reference count is decremented. That concludes the idea of memory management behind Go GObject representation. Also there is a need to mimic GObject type hierarchy and support things such as downcasting (casting from derived class to base class) and upcasting (casting from base class to derived class). It is implemented using combined approach: generated functions for explicit casting (up and down), interfaces and type embedding for implicit downcasting. 1.1. Implicit downcasting. In order to achieve that, only base GObject struct has a pointer to the C GObject. Every derived struct embeds that base GObject struct. Every GObject struct X has a method of that form: InheritedFromX() *C.X And when derived structs embed that struct, they also receive that method. Therefore it is possible to specify an interface for each of the base structs: type ObjectLike interface { InheritedFromGObject() *C.GObject } Each base struct itself implements that interface and every derived struct implements that interface as well (because it embeds the whole chain of base structs). And that system is used to do implicit downcasting, every generated function or a method instead of taking a pointer to a GObject struct, uses a corresponding Like interface. See the code: func (x *Container) Add(w WidgetLike) // ... var x *gtk.Container var a *gtk.Button var b *gtk.Entry x.Add(a) x.Add(b) 1.2. Explicit casting. Explicit casting in both directions is implemented as a generated ToX (where X is the name of a concrete type) function for each of the GObject structs. See the code: func ToWindow(o gobject.ObjectLike) *Window 1.3. Status Implemented: - GObject memory management (not optimal) - Object hierarchy, upcasting, downcasting - Methods - Signals/Slots (gobject.Object.Connect and closure marshaling) - Properties TODO: - Overriding virtual methods by defining a derived type (for custom widgets) - ... 2. INTERFACES The major problem with interfaces, that it's not possible to use Go interfaces to implement GObject interfaces, because GObject interfaces may have non-virtual methods and in Go interfaces you can only mimic that with functions that take interface as a parameter, which is not very helpful. Therefore I use a hack: empty struct which implements all the non-virtual interface methods. Any GObject derived struct may embed that interface implementation without increasing the size of the GCed struct placeholder, but still adding necessary methods to it. The hacky part here is that I use a pointer to an empty struct and assuming that it points to some meaningful location. That kind of behaviour is not specified by the Go specification. But so far it works. Here is the description of a mess generated for interfaces (let's assume our interface is called Foo): FooLike - Analogous to object interface for generated functions and methods. Foo - Object derived struct which represents an object which implements that interface, at this point the real type of the object is unknown. FooImpl - Empty struct that implements all non-virtual methods of our interface. ToFoo - Function for upcasting/downcasting. Also FooImpl has a special method of that form: ImplementsFoo() *C.Foo it serves the same purpose as similar object method - implicit downcasting. 2.1. Status Implemented: - Objects implementing interfaces - Non-virtual methods TODO: - Providing custom interfaces implementations from Go 3. STRUCTURES Structures are implemented simply as byte blobs. The size should match the real C struct size, but gobject-introspection at the moment provides wrong size in some cases (no support for C bit fields). Also it is possible to override C structures definitions if it's necessary. Fields for struct are generated as well. If it's required to wrap the field before using it, the wrapper method is generated instead. Name matches. For example gdk.EventMotion has method `Window() *Window` for accessing its `window` fields. But for simple things like float64 it has fields: `X` and `Y` as an example. Structs memory management problem is complicated. At the moment no memory management is being done and in most cases structs are allocated on the stack as values (Go supports that, it makes sense). For many structs like TreeIter or TextIter it's a perfect variant, but it is possible that there are other structs which are dynamically allocated by gobject-based library and are in a form of boxed value. It is uncertain how it is possible to make a line here, between structs which require dynamic memory management and structs which are ok with stack storage. 3.1. Status Implemented: - Structs as byte blobs - Struct methods - Struct fields - Struct fields accessors TODO: - Make a final decision about structs memory management go-gir-generator-master/documentation/WhyWaf.txt000066400000000000000000000054241414263242200223430ustar00rootroot00000000000000Why am I using the waf build system? First let's point out what were the alternatives: 1. Go tool. Asks for a lots of ugly conventions, ignores the complicated world, pretends everything is simple. Their answer to things that go tool can't handle is "use something else". Good. 2. Make. Too simple even to handle implicit dependencies. Windows developers don't like it. 3. CMake. Good tool in general, but it is built around C/C++ approach to compilers, where one source file means one translation unit and can be compiled separately. Therefore it is not possible to define a custom compiler which takes multiple files at once. You can create custom commands and all that, but let's just say no. 4. SCons. Known to be slow. There is no point to spend time on a system which will suck on large projects anyway. 5. Autotools. ^_^ 6. ??? As you can see, there are not so many things to choose from. Here are some of the benefits from using waf: 1. Waf, despite the first impression, is a very simple tool, you need to learn only 5 concepts in order to use it easily: Context, ConfigSet, Task, TaskGen, Node. The core of the waf is very small, sure it has a complicated task generation and execution scheme, but you don't have to know it very well in order to use it. Things that matters for an end user are simple. Just look into the source code, read the docs. 2. It's written in python, which makes it very flexible, because you can even hack the waf itself in order to make it a better tool for your particular job. Distribution model (you distribute the whole tool with your project) allows that and encourages that. 3. Can handle practically anything I had a need for: - Implicit dependencies: no problem, Go, C and even mix of these for CGo. You can make a scanner for your tasks in python. - Multiple files at once: no problem. - Various very complex scenarios: build a generator, generate sources, build sources. No problem. 4. Despite the fact that it's written in python, waf is fast. Yes it uses hashes, but I believe you can hack it and force mtime usage if you want to (for example if you build gigabytes of assets). 5. It's has a truly beautiful design internally, which allows you to make all kinds of crazy mixes very quickly. For example I can easily use built-in implicit C dependency scanner for cgo files. I don't have to write everything from scratch for common things like 'uselib' system, binaries, static/shared libraries. 6. Debugging is very easy too. It matters a lot for very dynamic python-based (or any other dynamic lanaguge based) systems. Sure, maybe I could also say that is has certain parts that I disagree with or think of them as "bad decisions", but hey, time will show. At the moment waf is the _only_ sane choice for any more or less complicated build process. go-gir-generator-master/gogtk-demo/000077500000000000000000000000001414263242200175545ustar00rootroot00000000000000go-gir-generator-master/gogtk-demo/apple-red.png000066400000000000000000000067311414263242200221420ustar00rootroot00000000000000PNG  IHDR00WgAMA a IDATx[]Wyk9s8 N)JڄڨB>pE WK R@@@BqS+8v3sk}>31^|֞9e{^tvy_Tz߇} r޽cksM?p<p+E>*ܾ֏ W]vfgvw>yv!'+_dLom]aD֭G7L#ͯ굿>tbލW-,.{>E,&+֬h /ڳ{^>߄z;?/ ;po}U.tKGŇf6)o]EZ91|}~ W--7C4 ;%씍ozۍ! g|aNgnMo,VKU!@0G|׶nڱk5pJog&;W5B8tpao;[6:׽O\ 2R wͮr|Ο=ZEB|[aղ,ꭿw~x VmB)Fhcݷ}\In}GSefc"vԪg/-3j"`wogpr>Aqow;7O ̄ & AXA۰ض8pS9pMNwnmჃja~n,v?s{v}7ُOP v4!tTUMOh[( 0 :4uȢ(;'yn9?Scbጙ!|'/͛7+Wu_իNH)D^'jFĪBĐ,h.%49 0ofH_ CSv&/ʁnzhɖtJ?ܽ^q6]^~ӣ&5)G1!@2 ĺۖzf r\饊6?7=_ޓwַ/;w'W7y'^jc wzCDqbO1H!޴a f曖cP26,dhRЀص0hO~ί{r/VOMVl^}5#ey_\3*1D7*Jx*4+Dƨ$",X^SxAJpǏvpǏ8Gݍ׮YmeM޲zr\ǎ1?L NɈq X4L Iz!u$Dw!P!X(3J⺫~w>*;o; fLթѦO{ A?MtzU:z47"qsHNDS@8ɜn5A75e<3atH` _ v:,~J;I`U"* af#Pp wD0US"Vka`9zT5^W/8Ognl?P2⠥Qs8;A T"J9%3^]vݫ )%@_jBxɘ9w'fT(0 -/lpaAAi#aEN0NKm7]E;tz`@~$Zɘ`xD^1CQƱoN@pu,@z%jS6:ઔEk)e  "`h "TFPv,GbrJ>5ZS TP'4QuGlb*-+18ʨ>L Uǣ",*V1,E, *U;Ή@&D "Ǐљ&}a5\ )"JF0U3 sh БB+isa+  J)-M:&Xɸ "y4âd-TrD@#Ȱ(q@S<ܶwŧULЛYE*J.D B#%Cdb`#j0#qZUT)h}7kCPK VfZaoI@PB iA ֩#  F Q>JdŽP1IP"XTlXE"ia"Z@<hsaЎgyhCL_) LMttzb|[{v0Fԕ*A"E" 'U(G3.ElPSZsD %;١B1rch&3Ԅ%$D9FbwƓ963{;ydb vXs<2N80qY?fza\!9zTr;O97c2~ie8]щblE˜ |\IENDB`go-gir-generator-master/gogtk-demo/assistant.go000066400000000000000000000077071414263242200221270ustar00rootroot00000000000000// Assistant // // Demonstrates a sample multi-step assistant. Assistants are used to divide // an operation into several simpler sequential steps, and to guide the user // through these steps. package assistant import "gobject/gdk-3.0" import "gobject/gtk-3.0" import "fmt" import "time" var assistant *gtk.Assistant var progress_bar *gtk.ProgressBar func on_assistant_apply() { // Start a timer to simulate changes taking a few seconds to apply. go func() { for { gdk.ThreadsEnter() // Work, work, work... fraction := progress_bar.GetFraction() fraction += 0.05 if fraction < 1.0 { progress_bar.SetFraction(fraction) } else { // Close automatically once changes are fully applied. assistant.Destroy() gdk.ThreadsLeave() return } gdk.ThreadsLeave() time.Sleep(100 * time.Millisecond) } }() } func on_assistant_prepare() { n_pages := assistant.GetNPages() page_n := assistant.GetCurrentPage() title := fmt.Sprintf("Sample assistant (%d of %d)", page_n+1, n_pages) assistant.SetTitle(title) // The fourth page (counting from zero) is the progress page. The // user clicked Apply to get here so we tell the assistant to commit, // which means the changes up to this point are permanent and cannot // be cancelled or revisited. if page_n == 3 { assistant.Commit() } } func create_page1(assistant *gtk.Assistant) { box := gtk.NewBox(gtk.OrientationHorizontal, 12) box.SetBorderWidth(12) label := gtk.NewLabel("You must fill out this entry to continue:") box.PackStart(label, false, false, 0) entry := gtk.NewEntry() entry.SetActivatesDefault(true) box.PackStart(entry, true, true, 0) entry.Connect("changed", func() { page_n := assistant.GetCurrentPage() cur_page := assistant.GetNthPage(page_n) if entry.GetTextLength() > 0 { assistant.SetPageComplete(cur_page, true) } else { assistant.SetPageComplete(cur_page, false) } }) box.ShowAll() assistant.AppendPage(box) assistant.SetPageTitle(box, "Page 1") assistant.SetPageType(box, gtk.AssistantPageTypeIntro) } func create_page2(assistant *gtk.Assistant) { box := gtk.NewBox(gtk.OrientationVertical, 12) box.SetBorderWidth(12) checkbutton := gtk.NewCheckButtonWithLabel("This is optional data, you may continue " + "even if you do not check this") box.PackStart(checkbutton, false, false, 0) box.ShowAll() assistant.AppendPage(box) assistant.SetPageComplete(box, true) assistant.SetPageTitle(box, "Page 2") } func create_page3(assistant *gtk.Assistant) { label := gtk.NewLabel("This is confirmation page, press 'Apply' to apply changes") label.Show() assistant.AppendPage(label) assistant.SetPageType(label, gtk.AssistantPageTypeConfirm) assistant.SetPageComplete(label, true) assistant.SetPageTitle(label, "Confirmation") } func create_page4(assistant *gtk.Assistant) { progress_bar = gtk.NewProgressBar() progress_bar.SetHAlign(gtk.AlignCenter) progress_bar.SetVAlign(gtk.AlignCenter) progress_bar.Show() assistant.AppendPage(progress_bar) assistant.SetPageType(progress_bar, gtk.AssistantPageTypeProgress) assistant.SetPageTitle(progress_bar, "Applying changes") // This prevents the assistant window from being // closed while we're "busy" applying changes. assistant.SetPageComplete(progress_bar, false) } func Do(mainwin *gtk.Window) *gtk.Window { if assistant == nil { assistant = gtk.NewAssistant() assistant.SetDefaultSize(-1, 300) assistant.SetScreen(mainwin.GetScreen()) assistant.Connect("destroy", func() { assistant = nil progress_bar = nil }) create_page1(assistant) create_page2(assistant) create_page3(assistant) create_page4(assistant) close_cancel := func() { assistant.Destroy() } assistant.Connect("cancel", close_cancel) assistant.Connect("close", close_cancel) assistant.Connect("apply", on_assistant_apply) assistant.Connect("prepare", on_assistant_prepare) } if !assistant.GetVisible() { assistant.ShowAll() } else { assistant.Destroy() } return gtk.ToWindow(assistant) } go-gir-generator-master/gogtk-demo/background.jpg000066400000000000000000000533131414263242200224020ustar00rootroot00000000000000JFIFHHCreated with The GIMPC    $.' ",#(7),01444'9=82<.342C  2!!22222222222222222222222222222222222222222222222222"8!1AQ"a2q#BR3rbC1 ?T[C GzFh ʎ^h| lFT{(v4 TQ|Q ¡KHylmUw$"G4dvEL C1H2;ށY $=3Y4pVM'UDkYR#B@X㘧X"A8$rB Kиd֩1`Np˛MTDL~)oϊ%%FQ"-ó<P \(@E/zg[}ST-ɌpD* $EV$~7U ` {U-yZTꍻk :ԃD!7@`5{~(1`vֲ0ݤ}N[ͰPb"7"1 rfV $Oo~Pe5'HqTfڠXEgU27?)7fW]ۉ?mos9 hb$CYQG-3]:sRH;սXf$}YڶB[Pr$G N,T4hx>iFER*@=sb;k|*(O>(P$S aN<2UpXK&v^*=Fse{]t߭e-胯WeqM@~t{ u-ҳqmAjX&O5@W ڝyp*ʾ;hrI =C!9g(ǚ 3X:46P c h46P1:Hd{ EDnH:XE; Pn- OZxB2Ց1#>H1Hӏ(3b]0H:TɽԶ(L#ɥZùa{im-ZKPm?.ucʁRKT-[npX3 k-9\x CSnDSڣNrQ(~(`K UuQv)aseTI2)e+a{$W>৐;U ߎi+P꣰t= :{p8ULZ*k$My N_q&^MFy:N嶽Ř0PtUBuH=Ywz̈%)PzpX!\\'jt9 W\*i$ ' WOhl/K{@`d~h`@2y)K,-UB} ) c梳gdbDH)B@M>GYh -剃<^e{ZgMm-HU'Pfh P#9g; 'GH؊e]V._%DkTobvh:` cMs\`Ph99 ~ᕰ@=A[%Ǹ:*)>cE lF܍H2'4l<:+^%m9ƷLtU@QIJ) r?={. ?[p9-7Mmn:b].ۻY!wU ˃ <]zFڤ*2'B2cnRދ9b7ⅲ}H=sxs@m*-W[;1 ~p *ΉhX悳75,4$x5FPg114 1ދLS.:> Pˤvu9"t4Od|ċi,H"=1K2R{οXu2OĞ>k)!8wTPd yb`5^S[rqgg4[CkԎ2vڨ+dL FKb*=v*YXD I~@A}R΢V٠mȂb5qU@}5VcځllKx@U@-r7'g$h?5 ˘S\zxxs3UhQDe&vf1(HCl6Si@8("o[캤KxUn[Sy`椷K=5%pvhnUd hB TsZ+'.40LcwGqjȝ ,nط[>ªbuAඡ@&;P"1P@*"I<,CL~GuInkF -S)wü zfڵZv ?W0Xb}؏hIKVГ6>dOl@#Ku h?{HDH #E@*K 11As Y v,VmP fl(]*?o\[}: P;-KKA ?;eFIրImRAPǽrݫCI~5pYeK}g@ v ӕB$w!| e r1 S1v3(* #=b'KSIrNKyTnތfU"u:~( [H/RI2I317)ڏbOo`L{(i3tk J+;!Ҵq*!yـLB+cڟ#&c*& РGQ@B'Qa0=I6t&d 䊨,nط[>ªbuAඡ@&;TR*I$)}21dy~T>6:Tkx0`2|; ~nͫ]5`p>jLn &*)݈DTo 0+0#cDH6̴9P̶aT@D 9 Tx[;bN eJb`vlU2 ~Ojnbq۲31F5ŷӮ ð^ jAszFThĝh E$ { -ڴ?`q?Q 6^'{b 9T,NZqojXֹ`m< v!m+;zmw$UXȘR[{ i.9Z:nap+q#KGdx^=EИT\׮qz{Nxaڼuze6Ŷq֦ rO›*qle5\(UQu|Q޵K\r} A(83,g[;GޑWӑ8 ==:M$GP)v(@sW SG$=C1ԁ$fi_UMmVDӺgp-dDk5' A(=TqY$ַm3  U fv"qS*`Bݏ?OyZP=c&g3h LE Ŏ,s1kY N(6*< 7X sO>ɓ'A- EIv o+ DLbk7S 3LAQLWitτ! >aIڃ*=T5[ ?K([f{P)9?jֹ`m< v!m+;zmw$U)%[`5ȗ bz_{4xN] Omz hyW W]gSl[i'jj*^ w$)|Gk0Pc\P͜}QUh0']η=\@T G42; A2ɌuHKaTxqM9P܃ڭcJ )A m>P f {(^>PH>)L<9ղXAYE_VITT̘biQQ=z|,2P*P\dR[y$N⢂(Y$qvE-?޶6n\8}^womc Ѵ{y1ոu=O4ޡԨ{J81{'k*CNF 􂋬ξcܚA$F5UFpX7Hf׶\6vKq>)A m>P f {(^>PH>)L<9ղXAYE_VITT̘biQQ=z|,2P*P\dR[y$N⢂(Y$qvE-?޶6n\8}^womc Ѵ{y1\EtonsEZ*?UGlbR.w :W%D&1Q{z MHwwn8^Z l)$5 Z|S?4!-+V( \ĉ1Y%wi-ALU]axX-+r}6UOj RVia*JݲOrP% Yై5@팪b;H@2\" e(PHzWp"ډ1t8;,++\c5O4 t6B:4Urv(qU<- r>;QM'<_IϨ lg( $ncof6ӥ*e B^~hP:f5QqSݸ.3l QBTsFtœ f9WPyEk :'&OmtzyLXzS>N;iReUq/En~ہ@үQY-qL3q2k/\ A⹺wf׻q&893,H␲Rg,4UWP\P@B2b`KF_oimP/к#gAUSXˀ<8fŲI&gj Gڎ0YV  UP{2a汶 2y 5T[]?LL3$r; j95PPX2Z3q'PҰiR/{{@Ы@H9l* @TfX !e)ɢ2ϘXi@*d1YP0,>f_u$# F` yrN>ؤg%R~)U 2ۍNPlG n2,]V!)R.NG~ G:ɊtLkY_$*[v$h a=iF. @'02IcX$ӥ@ ?j5`ANyWǸ`a-)N⋹!f{M#x۞Oڛ ,dyB[9?4WrA#T#[M*n@)Ҥ:Ivs)P'FbΦ˾D.8ԽhDT)OHKAƝL|Q=*i0 vMf[4" EbqT,,xb!x[aP;%?!-ROv'1G0Y/i5nFg#G _ @'zk2V6;_@a,kĚ/̷Qw7&Z FFPAb-j4@b;^f1Vjjl^^ ~sEGӴ0R:q:WL¬€2 X7fAjı8vbnԅ!53ж"<RT Umo6cڵ7oV`|df"džMJ9 Ub9=-r֡)`)0&55<5@]D=kpl? -rZDRPpuUM#`lsk m7ʆkV@5HΪ 1<$P"LGv(Iv,< 2+9lڊ>p@WC)"KhwUIk,1se[P; KK;d 5U7L[NA^.L)Gi2$p/ AUE(ñ:2.kvRfL6&IX80$ʑW׹E۷Qvy[iQӲ-[>3?5Q4:v&&A|ǦO5y"B0[ĝE⵷gkPa1+{ ds ip]GTy>h[Li(~Y'T q588*4H>Kmq@I3?PIi8QdyDS"*+N"`ڀ$YĒq$qYR촋kwnx NLDOsA*\')BvQJ}(hB/;$@ؖhl@$a@@UBAk-솝"c(arFB{&rV:QHRn(2N5飻!Mh@qAD1}o` 4$R]Ndn>*_='@J;gm753ikǓiDYLfO}TSnB! Nк!bL;UwpKiPhj`chTA rA>&Icj}GC@#7sN s^bm#gt1O4Taʏ$UCV䝘nР(9:8Q.oLs!Ar#u%dVwOg7ٮ{6LY().ZN4&>*a 梪O4 +@Y?]#Hb&!'Fnx NLDOsA*\')BvQJ}(hB/;$@ؖhl@$a@@UBAk-솝"c(arFB{&rV:QHRn(2N5飻!Mh@qAD1}o` 4$R]Ndn>*_='@J;gm753ikǓiDYLfO}TSnB! Nк!bL;UwpKiPPKr@ :pf}ܓM)wA;m-#tm#(w{xp o\ޟfw'@*S6[ޙY\E(UTJ2Di46 {UF V ʼnf*:IHM1gGu5l"FB0Ŷ8&GbPJj&fh vbp5!*1\CR}G$tfi d4cftwQMsV)9d*Nc [cM2l4v 4ffH`'f)\Rn0=y4='rI'C+cjq'z'f6'>")[;i[eN "-y1bFTT3DA&h}CB(aR5kV`~$$p?4PỸfPT!Ʃ`" >hYsm4IOdIX ?zP$ (ղ@?+*ǙQ2i~4V.C\=D*# @1X;k"2mРF̬@S}SNŷ1ʠP"a@;a.޳΢M *b?ZկF%}dɬTO H*, !j'SL>#ǓAmEQZiK*O>!mL Dl(S:קҪɮvMr?yuO&uC7aAzt-xdž2-4 M%3ykV}DZIf 9KjGjqp8xJ)LAuv"~yn(#{e*P*O 4~Xk Z`+hjSB?P`8 ,fALd(AfcrcTH4, $觲O$I(fcj LIcj(b4H!݀ Ѭ[L5I6hP#fVw)SbۈYeP(|@LD\|zYQJ&PD±fڭjףhHvvqo'Qm D9a#q+*;z4Ŧp 9'B椑!w{رPI[lG"!tI<T$ߚY>h| lFT{(v4 TQ|Q ¡KHylmUw$"G4dvEL C1H2;ށY $=3Y4pVM'UDkYR#B@X㘧X"A8$rB Kиd֩1`Np˛MTDL~)oϊ%%FQ"-ó<P \(@E/zg[}ST-ɌpD* $EV$~7U ` {U-yZTꍻk :ԃD!7@`5{~(1`vֲ0ݤ}N[ͰPb"7"1 rfV $Oo~Pe5'HqTfڠXEgU27?)7fW]ۉ?mos9 hb$CYQG-3]:sRH;սXf$}YڶB[Pr$G N,T4hx>iFER*@=sb;k|*(O>(P$S aN<2UpXK&v^*=Fse{]t߭e-胯WeqM@~t{ u-ҳqmAjX&O5@W ڝyp*ʾ;hrI =C!9g(ǚ 3X:46P c h46P1:Hd{ EDnH:XE; Pn- OZxB2Ց1#>H1Hӏ(3b]0H:TɽԶ(L#ɥZùa{im-ZKPm?.ucʁRKT-[npX3 k-9\x CSnDSڣNrQ(~(`K UuQv)aseTI2)e+a{$W>৐;U ߎi+P꣰t= :{p8ULZ*k$My N_q&^MFy:N嶽Ř0PtUBuH=Ywz̈%)PzpX!\\'jt9 W\*i$ ' WOhl/K{@`d~h`@2y)K,-UB} ) c梳gdbDH)B@M>GYh -剃<^e{ZgMm-HU'Pfh P#9g; 'GH؊e]V._%DkTobvh:` cMs\`Ph99 ~ᕰ@=A[%Ǹ:*)>cE lF܍H2'4l<:+^%m9ƷLtU@QIJ) r?={. ?[p9-7Mmn:b].ۻY!wU ˃ <]zFڤ*2'B2cnRދ9b7ⅲ}H=sxs@m*-W[;1 ~p *ΉhX悳75,4$x5FPg114 1ދLS.:> Pˤvu9"t4Od|ċi,H"=1K2R{οXu2OĞ>k)!8wTPd yb`5^S[rqgg4[CkԎ2vڨ+dL FKb*=v*YXD I~@A}R΢V٠mȂb5qU@}5VcځllKx@U@-r7'g$h?5 ˘S\zxxs3UhQDe&vf1(HCl6Si@8("o[캤KxUn[Sy`椷K=5%pvhnUd hB TsZ+'.40LcwGqjȝ ,nط[>ªbuAඡ@&;P"1P@*"I<,CL~GuInkF -S)wü zfڵZv ?W0Xb}؏hIKVГ6>dOl@#Ku h?{HDH #E@*K 11As Y v,VmP fl(]*?o\[}: P;-KKA ?;eFIրImRAPǽrݫCI~5pYeK}g@ v ӕB$w!| e r1 S1v3(* #=b'KSIrNKyTnތfU"u:~( [H/RI2I317)ڏbOo`L{(i3tk J+;!Ҵq*!yـLB+cڟ#&c*& РGQ@B'Qa0=I6t&d 䊨,nط[>ªbuAඡ@&;TR*I$)}21dy~T>6:Tkx0`2|; ~nͫ]5`p>jLn &*)݈DTo 0+0#cDH6̴9P̶aT@D 9 Tx[;bN eJb`vlU2 ~Ojnbq۲31F5ŷӮ ð^ jAszFThĝh E$ { -ڴ?`q?Q 6^'{b 9T,NZqojXֹ`m< v!m+;zmw$UXȘR[{ i.9Z:nap+q#KGdx^=EИT\׮qz{Nxaڼuze6Ŷq֦ rO›*qle5\(UQu|Q޵K\r} A(83,g[;GޑWӑ8 ==:M$GP)v(@sW SG$=C1ԁ$fi_UMmVDӺgp-dDk5' A(=TqY$ַm3  U fv"qS*`Bݏ?OyZP=c&g3h LE Ŏ,s1kY N(6*< 7X sO>ɓ'A- EIv o+ DLbk7S 3LAQLWitτ! >aIڃ*=T5[ ?K([f{P)9?jֹ`m< v!m+;zmw$U)%[`5ȗ bz_{4xN] Omz hyW W]gSl[i'jj*^ w$)|Gk0Pc\P͜}QUh0']η=\@T G42; A2ɌuHKaTxqM9P܃ڭcJ )A m>P f {(^>PH>)L<9ղXAYE_VITT̘biQQ=z|,2P*P\dR[y$N⢂(Y$qvE-?޶6n\8}^womc Ѵ{y1ոu=O4ޡԨ{J81{'k*CNF 􂋬ξcܚA$F5UFpX7Hf׶\6vKq>)A m>P f {(^>PH>)L<9ղXAYE_VITT̘biQQ=z|,2P*P\dR[y$N⢂(Y$qvE-?޶6n\8}^womc Ѵ{y1\EtonsEZ*?UGlbR.w :W%D&1Q{z MHwwn8^Z l)$5 Z|S?4!-+V( \ĉ1Y%wi-ALU]axX-+r}6UOj RVia*JݲOrP% Yై5@팪b;H@2\" e(PHzWp"ډ1t8;,++\c5O4 t6B:4Urv(qU<- r>;QM'<_IϨ lg( $ncof6ӥ*e B^~hP:f5QqSݸ.3l QBTsFtœ f9WPyEk :'&OmtzyLXzS>N;iReUq/En~ہ@үQY-qL3q2k/\ A⹺wf׻q&893,H␲Rg,4UWP\P@B2b`KF_oimP/к#gAUSXˀ<8fŲI&gj Gڎ0YV  UP{2a汶 2y 5T[]?LL3$r; j95PPX2Z3q'PҰiR/{{@Ы@H9l* @TfX !e)ɢ2ϘXi@*d1YP0,>f_u$# F` yrN>ؤg%R~)U 2ۍNPlG n2,]V!)R.NG~ G:ɊtLkY_$*[v$h a=iF. @'02IcX$ӥ@ ?j5`ANyWǸ`a-)N⋹!f{M#x۞Oڛ ,dyB[9?4WrA#Tgo-gir-generator-master/gogtk-demo/builder.go000066400000000000000000000017761414263242200215440ustar00rootroot00000000000000// Builder // // Demonstrates an interface loaded from a XML description. package builder import "gobject/gtk-3.0" import "./gogtk-demo/common" var window *gtk.Window var builder *gtk.Builder type dummy struct{} func (*dummy) QuitActivate(action *gtk.Action) { window := gtk.ToWidget(builder.GetObject("window1")) window.Destroy() } func (*dummy) AboutActivate(action *gtk.Action) { about_dlg := gtk.ToDialog(builder.GetObject("aboutdialog1")) about_dlg.Run() about_dlg.Hide() } func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { builder = gtk.NewBuilder() _, err := builder.AddFromFile(common.FindFile("demo.ui")) if err != nil { println("ERROR: ", err.Error()) return nil } builder.ConnectSignals((*dummy)(nil)) window = gtk.ToWindow(builder.GetObject("window1")) window.SetScreen(mainwin.GetScreen()) window.Connect("destroy", func() { window = nil builder = nil }) } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window } go-gir-generator-master/gogtk-demo/button_boxes.go000066400000000000000000000045561414263242200226300ustar00rootroot00000000000000// Button Boxes // // The Button Box widgets are used to arrange buttons with padding. package button_boxes import "gobject/gtk-3.0" var window *gtk.Window func create_bbox(orient gtk.Orientation, title string, spacing int, layout gtk.ButtonBoxStyle) *gtk.Frame { frame := gtk.NewFrame(title) bbox := gtk.NewButtonBox(orient) bbox.SetBorderWidth(5) frame.Add(bbox) bbox.SetLayout(layout) bbox.SetSpacing(spacing) var button *gtk.Button button = gtk.NewButtonFromStock(gtk.StockOk) bbox.Add(button) button = gtk.NewButtonFromStock(gtk.StockCancel) bbox.Add(button) button = gtk.NewButtonFromStock(gtk.StockHelp) bbox.Add(button) return frame } func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetTitle("Button Boxes") window.Connect("destroy", func() { window = nil }) window.SetBorderWidth(10) main_vbox := gtk.NewBox(gtk.OrientationVertical, 0) window.Add(main_vbox) frame_horz := gtk.NewFrame("Horizontal Button Boxes") main_vbox.PackStart(frame_horz, true, true, 10) vbox := gtk.NewBox(gtk.OrientationVertical, 0) vbox.SetBorderWidth(10) frame_horz.Add(vbox) vbox.PackStart( create_bbox(gtk.OrientationHorizontal, "Spread", 40, gtk.ButtonBoxStyleSpread), true, true, 0) vbox.PackStart( create_bbox(gtk.OrientationHorizontal, "Edge", 40, gtk.ButtonBoxStyleEdge), true, true, 5) vbox.PackStart( create_bbox(gtk.OrientationHorizontal, "Start", 40, gtk.ButtonBoxStyleStart), true, true, 5) vbox.PackStart( create_bbox(gtk.OrientationHorizontal, "End", 40, gtk.ButtonBoxStyleEnd), true, true, 5) frame_vert := gtk.NewFrame("Vertical Button Boxes") main_vbox.PackStart(frame_vert, true, true, 10) hbox := gtk.NewBox(gtk.OrientationHorizontal, 0) hbox.SetBorderWidth(10) frame_vert.Add(hbox) hbox.PackStart( create_bbox(gtk.OrientationVertical, "Spread", 30, gtk.ButtonBoxStyleSpread), true, true, 0) hbox.PackStart( create_bbox(gtk.OrientationVertical, "Edge", 30, gtk.ButtonBoxStyleEdge), true, true, 5) hbox.PackStart( create_bbox(gtk.OrientationVertical, "Start", 30, gtk.ButtonBoxStyleStart), true, true, 5) hbox.PackStart( create_bbox(gtk.OrientationVertical, "End", 30, gtk.ButtonBoxStyleEnd), true, true, 5) } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window } go-gir-generator-master/gogtk-demo/color_selector.go000066400000000000000000000036141414263242200231250ustar00rootroot00000000000000// Color Selector // // GtkColorSelection lets the user choose a color. GtkColorSelectionDialog is // a prebuilt dialog containing a GtkColorSelection. package color_selector import "gobject/gtk-3.0" import "gobject/gdk-3.0" import "gobject/cairo-1.0" import "gobject/gobject-2.0" var color gdk.RGBA var window *gtk.Window func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { color = gdk.RGBA{0, 0, 1, 1} window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetScreen(mainwin.GetScreen()) window.SetTitle("Color Selection") window.Connect("destroy", func() { window = nil }) window.SetBorderWidth(8) vbox := gtk.NewBox(gtk.OrientationVertical, 8) vbox.SetBorderWidth(8) window.Add(vbox) // Create the color swatch area frame := gtk.NewFrame(gobject.NilString) frame.SetShadowType(gtk.ShadowTypeIn) vbox.PackStart(frame, true, true, 0) da := gtk.NewDrawingArea() da.Connect("draw", func(da *gtk.DrawingArea, cr *cairo.Context) bool { gdk.CairoSetSourceRGBA(cr, &color) cr.Paint() // unref explicitly, can't rely on GC here, leaks like crazy cr.Unref() return true }) // set a minimum size da.SetSizeRequest(200, 200) frame.Add(da) button := gtk.NewButtonWithMnemonic("_Change the above color") button.SetHAlign(gtk.AlignEnd) button.SetVAlign(gtk.AlignCenter) vbox.PackStart(button, false, false, 0) button.Connect("clicked", func() { dialog := gtk.NewColorSelectionDialog("Changing color") dialog.SetTransientFor(window) colorsel := gtk.ToColorSelection(dialog.GetColorSelection()) colorsel.SetPreviousRGBA(&color) colorsel.SetCurrentRGBA(&color) colorsel.SetHasPalette(true) response := dialog.Run() if response == gtk.ResponseTypeOk { color = colorsel.GetCurrentRGBA() da.QueueDraw() } dialog.Destroy() }) } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window } go-gir-generator-master/gogtk-demo/combo_boxes.go000066400000000000000000000146471414263242200224160ustar00rootroot00000000000000// Combo boxes // // The ComboBox widget allows to select one option out of a list. // The ComboBoxEntry additionally allows the user to enter a value // that is not in the list of options. // // How the options are displayed is controlled by cell renderers. package combo_boxes import "gobject/gobject-2.0" import "gobject/gtk-3.0" import "gobject/gdk-3.0" import "gobject/gdkpixbuf-2.0" import "strings" import "regexp" var window *gtk.Window const ( pixbuf_column = iota text_column ) func create_stock_icon_store() *gtk.TreeModel { stock_ids := []string{ gtk.StockDialogWarning, gtk.StockStop, gtk.StockNew, gtk.StockClear, gobject.NilString, gtk.StockOpen, } cellview := gtk.NewCellView() store := gtk.NewListStore(gdkpixbuf.PixbufGetType(), gobject.String) for _, id := range stock_ids { if id != gobject.NilString { pixbuf := cellview.RenderIconPixbuf(id, int(gtk.IconSizeButton)) item, _ := gtk.StockLookup(id) label := strings.Replace(item.Label, "_", "", -1) store.Append(pixbuf, label) } else { store.Append((*gdkpixbuf.Pixbuf)(nil), "separator") } } return gtk.ToTreeModel(store) } // A GtkCellLayoutDataFunc that demonstrates how one can control // sensitivity of rows. This particular function does nothing // useful and just makes the second row insensitive. func set_sensitive(cell_layout *gtk.CellLayout, cell *gtk.CellRenderer, model *gtk.TreeModel, iter *gtk.TreeIter) { path := model.GetPath(iter) _, indices := path.GetIndices() sensitive := indices[0] != 1 cell.SetProperty("sensitive", sensitive) } // A GtkTreeViewRowSeparatorFunc that demonstrates how rows can be // rendered as separators. This particular function does nothing // useful and just turns the fourth row into a separator. func is_separator(model *gtk.TreeModel, iter *gtk.TreeIter) bool { path := model.GetPath(iter) _, indices := path.GetIndices() result := indices[0] == 4 return result } func create_capital_store() *gtk.TreeModel { capitals := []struct{ name string capitals []string }{ {"A - B", []string{ "Albany", "Annapolis", "Atlanta", "Augusta", "Austin", "Baton Rouge", "Bismarck", "Boise", "Boston", }}, {"C - D", []string{ "Carson City", "Charleston", "Cheyenne", "Columbia", "Columbus", "Concord", "Denver", "Des Moines", "Dover", }}, {"E - J", []string{ "Frankfort", "Harrisburg", "Hartford", "Helena", "Honolulu", "Indianapolis", "Jackson", "Jefferson City", "Juneau", }}, {"K - O", []string{ "Lansing", "Lincoln", "Little Rock", "Madison", "Montgomery", "Montpelier", "Nashville", "Oklahoma City", "Olympia", }}, {"P - S", []string{ "Phoenix", "Pierre", "Providence", "Raleigh", "Richmond", "Sacramento", "Salem", "Salt Lake City", "Santa Fe", "Springfield", "St. Paul", }}, {"T - Z", []string{ "Tallahassee", "Topeka", "Trenton", }}, } store := gtk.NewTreeStore(gobject.String) for _, group := range capitals { iter := store.Append(nil, group.name) for _, capital := range group.capitals { store.Append(&iter, capital) } } return gtk.ToTreeModel(store) } func is_capital_sensitive(cell_layout *gtk.CellLayout, cell *gtk.CellRenderer, model *gtk.TreeModel, iter *gtk.TreeIter) { sensitive := !model.IterHasChild(iter) cell.SetProperty("sensitive", sensitive) } func fill_combo_entry(combo *gtk.ComboBoxText) { combo.AppendText("One") combo.AppendText("Two") combo.AppendText("2½") combo.AppendText("Three") } func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetScreen(mainwin.GetScreen()) window.SetTitle("Combo boxes") window.Connect("destroy", func() { window = nil }) window.SetBorderWidth(10) vbox := gtk.NewBox(gtk.OrientationVertical, 2) window.Add(vbox) // A combobox demonstrating cell renderers, separators and // insensitive rows frame := gtk.NewFrame("Some stock icons") vbox.PackStart(frame, false, false, 0) box := gtk.NewBox(gtk.OrientationVertical, 0) box.SetBorderWidth(5) frame.Add(box) model := create_stock_icon_store() combo := gtk.NewComboBoxWithModel(model) box.Add(combo) rp := gtk.NewCellRendererPixbuf() combo.PackStart(rp, false) combo.SetAttributes(rp, "pixbuf", pixbuf_column) combo.SetCellDataFunc(rp, set_sensitive) rt := gtk.NewCellRendererText() combo.PackStart(rt, true) combo.SetAttributes(rt, "text", text_column) combo.SetCellDataFunc(rt, set_sensitive) combo.SetRowSeparatorFunc(is_separator) combo.SetActive(0) // A combobox demonstrating trees. frame = gtk.NewFrame("Where are we ?") vbox.PackStart(frame, false, false, 0) box = gtk.NewBox(gtk.OrientationVertical, 0) box.SetBorderWidth(5) frame.Add(box) model = create_capital_store() combo = gtk.NewComboBoxWithModel(model) box.Add(combo) rt = gtk.NewCellRendererText() combo.PackStart(rt, true) combo.SetAttributes(rt, "text", 0) combo.SetCellDataFunc(rt, is_capital_sensitive) path := gtk.NewTreePathFromIndices(0, 8) iter, _ := model.GetIter(path) path.Free() combo.SetActiveIter(&iter) // A GtkComboBoxEntry with validation. frame = gtk.NewFrame("Editable") vbox.PackStart(frame, false, false, 0) box = gtk.NewBox(gtk.OrientationVertical, 0) box.SetBorderWidth(5) frame.Add(box) combotext := gtk.NewComboBoxTextWithEntry() fill_combo_entry(combotext) box.Add(combotext) // A simple validating entry entry := gtk.ToEntry(combotext.GetChild()) entry.Connect("changed", func(entry *gtk.Entry) { error_color := gdk.RGBA{0.8, 0, 0, 1} text := entry.GetText() re := regexp.MustCompile(`^([0-9]*|One|Two|2½|Three)$`) if re.MatchString(text) { entry.OverrideColor(0, nil) } else { entry.OverrideColor(0, &error_color) } }) // A combobox with string IDs frame = gtk.NewFrame("Editable") vbox.PackStart(frame, false, false, 0) box = gtk.NewBox(gtk.OrientationVertical, 0) box.SetBorderWidth(5) frame.Add(box) combotext = gtk.NewComboBoxText() combotext.Append("never", "Not visible") combotext.Append("when-active", "Visible when active") combotext.Append("always", "Always visible") box.Add(combotext) entry = gtk.NewEntry() gobject.ObjectBindProperty( combotext, "active-id", entry, "text", gobject.BindingFlagsBidirectional) box.Add(entry) } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window }go-gir-generator-master/gogtk-demo/common.go000066400000000000000000000001531414263242200213720ustar00rootroot00000000000000package common func FindFile(name string) string { // TODO: no path finding heuristic yet return name } go-gir-generator-master/gogtk-demo/demo.ui000066400000000000000000000276071414263242200210530ustar00rootroot00000000000000 John Doe 25 This is the John Doe row Mary Unknown 50 This is the Mary Unknown row Copy Copy selected object into the clipboard gtk-copy Cut Cut selected object into the clipboard gtk-cut EditMenu _Edit FileMenu _File New Create a new file gtk-new Open Open a file gtk-open Paste Paste object from the Clipboard gtk-paste Quit Quit the program gtk-quit Save True Save a file gtk-save SaveAs Save with a different name gtk-save-as HelpMenu _Help About gtk-about GtkBuilder demo 250 440 GtkBuilder demo True True The menubar False True The toolbar False 1 automatic in True automatic True liststore1 3 Name list A list of person with name, surname and age columns Name 0 Surname 1 Age 2 2 True False 3 go-gir-generator-master/gogtk-demo/demos.go000066400000000000000000000053741414263242200212230ustar00rootroot00000000000000package main import "gobject/gtk-3.0" import ( "./gogtk-demo/assistant" "./gogtk-demo/builder" "./gogtk-demo/button_boxes" "./gogtk-demo/color_selector" "./gogtk-demo/entry_buffer" "./gogtk-demo/expander" "./gogtk-demo/info_bar" "./gogtk-demo/links" "./gogtk-demo/list_store" "./gogtk-demo/main_window" "./gogtk-demo/paned_widgets" "./gogtk-demo/pickers" "./gogtk-demo/size_groups" "./gogtk-demo/spinner" "./gogtk-demo/stock_browser" "./gogtk-demo/menus" "./gogtk-demo/entry_completion" "./gogtk-demo/drawing_area" "./gogtk-demo/combo_boxes" "./gogtk-demo/dialog" "./gogtk-demo/search_entry" "./gogtk-demo/iconview_edit" "./gogtk-demo/iconview" "./gogtk-demo/pixbufs" ) type DemoFunc func(mainwin *gtk.Window) *gtk.Window type DemoDesc struct { Title string Filename string Func DemoFunc Children []*DemoDesc } var demos = []*DemoDesc{ {Title: "Application main window", Filename: "main_window.go", Func: main_window.Do}, {Title: "Assistant", Filename: "assistant.go", Func: assistant.Do}, {Title: "Builder", Filename: "builder.go", Func: builder.Do}, {Title: "Button Boxes", Filename: "button_boxes.go", Func: button_boxes.Do}, {Title: "Color Selector", Filename: "color_selector.go", Func: color_selector.Do}, {Title: "Combo boxes", Filename: "combo_boxes.go", Func: combo_boxes.Do}, {Title: "Dialog and Message Boxes", Filename: "dialog.go", Func: dialog.Do}, {Title: "Drawing Area", Filename: "drawing_area.go", Func: drawing_area.Do}, {Title: "Entry", Children: []*DemoDesc{ {Title: "Entry Buffer", Filename: "entry_buffer.go", Func: entry_buffer.Do}, {Title: "Entry Completion", Filename: "entry_completion.go", Func: entry_completion.Do}, {Title: "Search Entry", Filename: "search_entry.go", Func: search_entry.Do}, }}, {Title: "Expander", Filename: "expander.go", Func: expander.Do}, {Title: "Icon View", Children: []*DemoDesc{ {Title: "Icon View Basics", Filename: "iconview.go", Func: iconview.Do}, {Title: "Editing and Drag-and-Drop", Filename: "iconview_edit.go", Func: iconview_edit.Do}, }}, {Title: "Info bar", Filename: "info_bar.go", Func: info_bar.Do}, {Title: "Links", Filename: "links.go", Func: links.Do}, {Title: "Menus", Filename: "menus.go", Func: menus.Do}, {Title: "Paned Widgets", Filename: "paned_widgets.go", Func: paned_widgets.Do}, {Title: "Pickers", Filename: "pickers.go", Func: pickers.Do}, {Title: "Pixbufs", Filename: "pixbufs.go", Func: pixbufs.Do}, {Title: "Size Groups", Filename: "size_groups.go", Func: size_groups.Do}, {Title: "Spinner", Filename: "spinner.go", Func: spinner.Do}, {Title: "Stock Item and Icon Browser", Filename: "stock_browser.go", Func: stock_browser.Do}, {Title: "Tree View", Children: []*DemoDesc{ {Title: "List Store", Filename: "list_store.go", Func: list_store.Do}, }}, } go-gir-generator-master/gogtk-demo/dialog.go000066400000000000000000000070171414263242200213470ustar00rootroot00000000000000// Dialog and Message Boxes // // Dialog widgets are used to pop up a transient window for user feedback. package dialog import "gobject/gtk-3.0" var window *gtk.Window var entry1 *gtk.Entry var entry2 *gtk.Entry var i = 1 func message_dialog_clicked() { dialog := gtk.NewMessageDialog(window, gtk.DialogFlagsModal | gtk.DialogFlagsDestroyWithParent, gtk.MessageTypeInfo, gtk.ButtonsTypeOk, "This message box has been popped up the following\nnumber of times:") dialog.FormatSecondaryText("%d", i) dialog.Run() dialog.Destroy() i++ } func interactive_dialog_clicked() { dialog := gtk.NewDialogWithButtons("Interactive Dialog", window, gtk.DialogFlagsModal | gtk.DialogFlagsDestroyWithParent, gtk.StockOk, gtk.ResponseTypeOk, "_Non-stock Button", gtk.ResponseTypeCancel) content_area := gtk.ToBox(dialog.GetContentArea()) hbox := gtk.NewBox(gtk.OrientationHorizontal, 8) hbox.SetBorderWidth(8) content_area.PackStart(hbox, false, false, 0) stock := gtk.NewImageFromStock(gtk.StockDialogQuestion, int(gtk.IconSizeDialog)) hbox.PackStart(stock, false, false, 0) table := gtk.NewGrid() table.SetRowSpacing(4) table.SetColumnSpacing(4) hbox.PackStart(table, true, true, 0) label := gtk.NewLabelWithMnemonic("_Entry 1") table.Attach(label, 0, 0, 1, 1) local_entry1 := gtk.NewEntry() local_entry1.SetText(entry1.GetText()) table.Attach(local_entry1, 1, 0, 1, 1) label.SetMnemonicWidget(local_entry1) label = gtk.NewLabelWithMnemonic("E_ntry 2") table.Attach(label, 0, 1, 1, 1) local_entry2 := gtk.NewEntry() local_entry2.SetText(entry2.GetText()) table.Attach(local_entry2, 1, 1, 1, 1) label.SetMnemonicWidget(local_entry2) hbox.ShowAll() response := dialog.Run() if response == gtk.ResponseTypeOk { entry1.SetText(local_entry1.GetText()) entry2.SetText(local_entry2.GetText()) } dialog.Destroy() } func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetScreen(mainwin.GetScreen()) window.SetTitle("Dialogs") window.Connect("destroy", func() { window = nil entry1 = nil entry2 = nil i = 1 }) window.SetBorderWidth(8) frame := gtk.NewFrame("Dialogs") window.Add(frame) vbox := gtk.NewBox(gtk.OrientationVertical, 8) vbox.SetBorderWidth(8) frame.Add(vbox) // Standard message dialog hbox := gtk.NewBox(gtk.OrientationHorizontal, 8) vbox.PackStart(hbox, false, false, 0) button := gtk.NewButtonWithMnemonic("_Message Dialog") button.Connect("clicked", message_dialog_clicked) hbox.PackStart(button, false, false, 0) vbox.PackStart(gtk.NewSeparator(gtk.OrientationHorizontal), false, false, 0) // Interactive dialog hbox = gtk.NewBox(gtk.OrientationHorizontal, 8) vbox.PackStart(hbox, false, false, 0) vbox2 := gtk.NewBox(gtk.OrientationVertical, 0) button = gtk.NewButtonWithMnemonic("_Interactive Dialog") button.Connect("clicked", interactive_dialog_clicked) hbox.PackStart(vbox2, false, false, 0) vbox2.PackStart(button, false, false, 0) table := gtk.NewGrid() table.SetRowSpacing(4) table.SetColumnSpacing(4) hbox.PackStart(table, false, false, 0) label := gtk.NewLabelWithMnemonic("_Entry 1") table.Attach(label, 0, 0, 1, 1) entry1 = gtk.NewEntry() table.Attach(entry1, 1, 0, 1, 1) label.SetMnemonicWidget(entry1) label = gtk.NewLabelWithMnemonic("E_ntry 2") table.Attach(label, 0, 1, 1, 1) entry2 = gtk.NewEntry() table.Attach(entry2, 1, 1, 1, 1) label.SetMnemonicWidget(entry2) } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window }go-gir-generator-master/gogtk-demo/drawing_area.go000066400000000000000000000130641414263242200225320ustar00rootroot00000000000000// Drawing Area // // GtkDrawingArea is a blank area where you can draw custom displays // of various kinds. // // This demo has two drawing areas. The checkerboard area shows // how you can just draw something; all you have to do is write // a signal handler for expose_event, as shown here. // // The "scribble" area is a bit more advanced, and shows how to handle // events such as button presses and mouse motion. Click the mouse // and drag in the scribble area to draw squiggles. Resize the window // to clear the area. package drawing_area import "gobject/gdk-3.0" import "gobject/gtk-3.0" import "gobject/cairo-1.0" import "gobject/gobject-2.0" var window *gtk.Window var surface *cairo.Surface var cr *cairo.Context func checkerboard_draw(da *gtk.DrawingArea, cr *cairo.Context) bool { const spacing = 2 const check_size = 10 // At the start of a draw handler, a clip region has been set on // the Cairo context, and the contents have been cleared to the // widget's background color. The docs for // gdk_window_begin_paint_region() give more details on how this // works. xcount := 0 width := da.GetAllocatedWidth() height := da.GetAllocatedHeight() i := spacing for i < width { j := spacing ycount := xcount % 2 // start with even/odd depending on row for j < height { if ycount % 2 != 0 { cr.SetSourceRGB(0.45777, 0, 0.45777) } else { cr.SetSourceRGB(1, 1, 1) } // If we're outside the clip, this will do nothing. cr.Rectangle(float64(i), float64(j), check_size, check_size) cr.Fill() j += check_size + spacing ycount++ } i += check_size + spacing xcount++ } // return TRUE because we've handled this event, so no // further processing is required. return true } // Create a new surface of the appropriate size to store out scribbles func scribble_configure_event(widget *gtk.Widget, event *gdk.EventConfigure) bool { allocation := widget.GetAllocation() surface = widget.GetWindow().CreateSimilarSurface(cairo.ContentColor, int(allocation.Width), int(allocation.Height)) // Initialize the surface to white cr = cairo.NewContext(surface) cr.SetSourceRGB(1, 1, 1) cr.Paint() // We've handled the configure event, no need for further processing. return true } // Redraw the screen from the surface func scribble_draw(widget *gtk.Widget, cr *cairo.Context) bool { cr.SetSourceSurface(surface, 0, 0) cr.Paint() return false } // Draw a rectangle on the screen func draw_brush(widget *gtk.Widget, x, y float64) { update_rect := cairo.RectangleInt{int32(x) - 3, int32(y) - 3, 6, 6} gdk.CairoRectangle(cr, &update_rect) cr.SetSourceRGB(0, 0, 0) cr.Fill() widget.GetWindow().InvalidateRect(&update_rect, false) } func scribble_button_press_event(widget *gtk.Widget, event *gdk.EventButton) bool { if surface == nil { // paranoia check, in case we haven't gotten a configure event return false } if event.Button == 1 { draw_brush(widget, event.X, event.Y) } // We've handled the event, stop processing return true } func scribble_motion_notify_event(widget *gtk.Widget, event *gdk.EventMotion) bool { if surface == nil { // paranoia check, in case we haven't gotten a configure event return false } // This call is very important; it requests the next motion event. // If you don't call gdk_window_get_pointer() you'll only get // a single motion event. The reason is that we specified // GDK_POINTER_MOTION_HINT_MASK to gtk_widget_set_events(). // If we hadn't specified that, we could just use event->x, event->y // as the pointer location. But we'd also get deluged in events. // By requesting the next event as we handle the current one, // we avoid getting a huge number of events faster than we // can cope. x, y, state, _ := event.Window().GetPointer() if state & gdk.ModifierTypeButton1Mask != 0 { draw_brush(widget, float64(x), float64(y)) } // We've handled the event, stop processing return true } func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetScreen(mainwin.GetScreen()) window.SetTitle("Drawing Area") window.Connect("destroy", func() { window = nil surface = nil cr = nil }) window.SetBorderWidth(8) vbox := gtk.NewBox(gtk.OrientationVertical, 8) vbox.SetBorderWidth(8) window.Add(vbox) // Create the checkerboard area label := gtk.NewLabel(gobject.NilString) label.SetMarkup("Checkerboard patter") vbox.PackStart(label, false, false, 0) frame := gtk.NewFrame(gobject.NilString) frame.SetShadowType(gtk.ShadowTypeIn) vbox.PackStart(frame, true, true, 0) da := gtk.NewDrawingArea() da.SetSizeRequest(100, 100) frame.Add(da) da.Connect("draw", checkerboard_draw) // Create the scribble area label = gtk.NewLabel(gobject.NilString) label.SetMarkup("Scribble area") vbox.PackStart(label, false, false, 0) frame = gtk.NewFrame(gobject.NilString) frame.SetShadowType(gtk.ShadowTypeIn) vbox.PackStart(frame, true, true, 0) da = gtk.NewDrawingArea() da.SetSizeRequest(100, 100) frame.Add(da) // Signals used to handle backing surface da.Connect("draw", scribble_draw) da.Connect("configure-event", scribble_configure_event) // Event signals da.Connect("motion-notify-event", scribble_motion_notify_event) da.Connect("button-press-event", scribble_button_press_event) da.SetEvents(int(gdk.EventMask(da.GetEvents()) | gdk.EventMaskLeaveNotifyMask | gdk.EventMaskButtonPressMask | gdk.EventMaskPointerMotionMask | gdk.EventMaskPointerMotionHintMask)) } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window }go-gir-generator-master/gogtk-demo/entry_buffer.go000066400000000000000000000023361414263242200226010ustar00rootroot00000000000000// Entry/Entry Buffer // // GtkEntryBuffer provides the text content in a GtkEntry. package entry_buffer import "gobject/gtk-3.0" import "gobject/gobject-2.0" var dialog *gtk.Dialog func Do(mainwin *gtk.Window) *gtk.Window { if dialog == nil { dialog = gtk.NewDialogWithButtons("GtkEntryBuffer", mainwin, 0, gtk.StockClose, gtk.ResponseTypeNone) dialog.SetResizable(false) dialog.Connect("response", func() { dialog.Destroy() }) dialog.Connect("destroy", func() { dialog = nil }) content_area := gtk.ToBox(dialog.GetContentArea()) vbox := gtk.NewBox(gtk.OrientationVertical, 5) content_area.PackStart(vbox, true, true, 0) vbox.SetBorderWidth(5) label := gtk.NewLabel("Entries share a buffer. Typing in one is reflected in the other.") vbox.PackStart(label, false, false, 0) // Create a buffer buffer := gtk.NewEntryBuffer(gobject.NilString, 0) // Create our first entry entry := gtk.NewEntryWithBuffer(buffer) vbox.PackStart(entry, false, false, 0) // Create the second entry entry = gtk.NewEntryWithBuffer(buffer) entry.SetVisibility(false) vbox.PackStart(entry, false, false, 0) } if !dialog.GetVisible() { dialog.ShowAll() } else { dialog.Destroy() } return gtk.ToWindow(dialog) } go-gir-generator-master/gogtk-demo/entry_completion.go000066400000000000000000000032271414263242200235010ustar00rootroot00000000000000// Entry/Entry Completion // // GtkEntryCompletion provides a mechanism for adding support for // completion in GtkEntry. package entry_completion import "gobject/gtk-3.0" import "gobject/gobject-2.0" func create_completion_model() *gtk.TreeModel { store := gtk.NewListStore(gobject.String) // Append few words store.Append("GNOME") store.Append("total") store.Append("totally") return gtk.ToTreeModel(store) } var dialog *gtk.Dialog func Do(mainwin *gtk.Window) *gtk.Window { if dialog == nil { dialog = gtk.NewDialogWithButtons("GtkEntryCompletion", mainwin, 0, gtk.StockClose, gtk.ResponseTypeNone) dialog.SetResizable(false) dialog.Connect("response", func() { dialog.Destroy() }) dialog.Connect("destroy", func() { dialog = nil }) content_area := gtk.ToBox(dialog.GetContentArea()) vbox := gtk.NewBox(gtk.OrientationVertical, 5) content_area.PackStart(vbox, true, true, 0) vbox.SetBorderWidth(5) label := gtk.NewLabel(gobject.NilString) label.SetMarkup("Completion demo, try writing total or gnome for example.") vbox.PackStart(label, false, false, 0) // Create our entry entry := gtk.NewEntry() vbox.PackStart(entry, false, false, 0) // Create the completion object completion := gtk.NewEntryCompletion() // Assign the completion to the entry entry.SetCompletion(completion) // Create a tree model and use it as the completion model completion_model := create_completion_model() completion.SetModel(completion_model) // Use model column 0 as the text column completion.SetTextColumn(0) } if !dialog.GetVisible() { dialog.ShowAll() } else { dialog.Destroy() } return gtk.ToWindow(dialog) }go-gir-generator-master/gogtk-demo/expander.go000066400000000000000000000021331414263242200217100ustar00rootroot00000000000000// Expander // // GtkExpander allows to provide additional content that is initially hidden. // This is also known as "disclosure triangle". package expander import "gobject/gtk-3.0" var dialog *gtk.Dialog func Do(mainwin *gtk.Window) *gtk.Window { if dialog == nil { dialog = gtk.NewDialogWithButtons("GtkExpander", mainwin, 0, gtk.StockClose, gtk.ResponseTypeNone) dialog.SetResizable(false) dialog.Connect("response", func() { dialog.Destroy() }) dialog.Connect("destroy", func() { dialog = nil }) content_area := gtk.ToBox(dialog.GetContentArea()) vbox := gtk.NewBox(gtk.OrientationVertical, 5) content_area.PackStart(vbox, true, true, 0) vbox.SetBorderWidth(5) label := gtk.NewLabel("Expander demo. Click on the triangle for details.") vbox.PackStart(label, false, false, 0) // Create the expander expander := gtk.NewExpander("Details") vbox.PackStart(expander, false, false, 0) label = gtk.NewLabel("Details can be shown or hidden.") expander.Add(label) } if !dialog.GetVisible() { dialog.ShowAll() } else { dialog.Destroy() } return gtk.ToWindow(dialog) } go-gir-generator-master/gogtk-demo/gnome-applets.png000066400000000000000000000060221414263242200230350ustar00rootroot00000000000000PNG  IHDR00WgAMA abKGD pHYs``zxEtIME ( IDATxYuګg㐢9ҖdkMіI@ӒF 'P q^b=F I6<Yk I @L٢hQ#҈Ԉξw5}(e<) ={#qs$L.KgK v\&H a-'r#pUVW cs1,'og])6˽~ @c[ : (&POsp3_:z|dxp4Ȓ4':NZeMo}ߘ]XY3B|y@.ρ|sy޽_$,H( <ϱ]vX[>G/nN(9&P*/=ra0**,!!IRB_쯹 +baGRR/dS*?{ķ+}5,)nj]R7 4%Mb$%NRUS/.Cȥw}TT*S)K覉a訪,ɿ$4!c8!c8ŕ;%l3j>?w\R*)U*eR4Q5EQd.$邕}(8ˆLKzk}}^o| Ǟ{_꺎ii J ib)2 ,S)Ұt+N9voinʲhF ,Q*WɃYӻ໱/ ,QT$uMes;B6x@Ldp edY)2cPUwH2xId Y\'N*$2YzRra/ۥ'}x"K3,#R,,f4%C|&+!4#R$EcyI(Wpz`Rӿ*2 {AަXS#it2EDa@xv| €(KӘ$Iӄ4MIqyxq7/ӱ]TMR.?݌mj8ꮰQݕw\s|}K" C(&j54z^z;Flj☡a\Ͽ/xAډHdOA@{xظݱpm ױ|;>( g}}3gޣ^gV\,rIݮ= +]iE!Bs=_feNt=/~SJ uD*] U(Cǧ/ֱ]xg"e]iJr|qXZ\4?ȓ?JLN& >]CܵGf׮a'2,bychl!{>A!I8V==X6M�{8*f9 xWJ%Iqˬ?ÿ4X= I,ϒ)aF1AA1iS2M8V#lľW_}N`nvCCyȲ Ο'==? ʪ!q#2%äJozw}yusl^[[[a RNZ1l{ &'%BR 45$&Ŭq% $ } ZZ\4c>{`˲fFFF5A (lvnzSo}͖mwszr;BAk*"$ i"+2*aP_K˫/ߚ8juj'F!%{T;%IUUZa*W):r0體 RVjhɩ19nZoO>.^n(HpZFFmfQ{l CM쯡j*#JwKt72y?\v♶ ' m멅# V,ˆg C3TEsuM!YQU)#m+_܈?%! @C^>kR(uc3e՞]lA_x)n/o+uhZQ`Q,<liOU cg7yA|527]B9p @xq bo?ڧE~p{ ցtc Ř5.a[A}/ ef b\GYD@6$-<E/E,E=<VD8q//.!<+dM`PV<}Cvwb}HB&*za+9B{z4zQ$Pr8C7ze^)|oթ {y շX~o$QajmӢ "EBbxvPZs|EkS؎%_X{.^52* @NwBhJiO{]XdZ8'Z O YG2Ad;@zooAkIENDB`go-gir-generator-master/gogtk-demo/gnome-calendar.png000066400000000000000000000053031414263242200231370ustar00rootroot00000000000000PNG  IHDR00WgAMA1_ zIDATx]lWwvvwNvc7֤}B"TDAVT臢ҨQ Ayh)BB R>ѠTb'󹉿];wwfa7N*Du5;wN;Nnn0;x}?&Ex @twRJ"T!@QW @ a H_(yJ6'C""a$ BuZ BiM* *=ܪD;ϏweBB E*es8N2H)A6/O^ZJ)[?J%#/hl34*aH(ω|>*c76 $2'\O6.8y}B1aᅊmsu'X aHB|rןP(J(^)RԑRDJNDΗ^ac_kG-VVW6l |#bhm!ne~ye9FhfA^G#7)rp$^<|] QJ"py2 KV^o $ʈ C;Qؐ{Iȥnc2}8ڭ;rk LdGui 8ƃ@ "Z!&7ֽ@^xO,k*)-l ]o[fMCz8@oܸ K;7ę v(d6LJxh-`Oˌ]5MdU`PHw@1c; 9D5#M@.}@7vg):?yyF+C ? lSKl =˓R)/fYZ)JgDeYZXbbGF@o84ށX5e!J:OS)N)w3ccdYv 180H+Mm֢@QNtR|'C^_Cgzt%eTkÐZ25;5эIXخh&BrĻt[jEZjc'ak*ͮa1yKTu]T%onl(r  ~ضrC4d'Ƅ:o!:zGcXd&zI} !ҩh+-G7 I4[=`ŵ $Mce_ܿ'F{1>7wccۀ^k1.Z\10ŁNVdf9v)c|t=< 3ccL̔1E94y0nzz=Du:3?2T ,T\0s _e/ׇ o>Н:qj^ڷo߉mXpd WMjo1W[?kll,cСT*5:6M$eW2ob x3}3}xgPUjI3&c+wM& rտ%v{v$+Q):ښNƘUOdΑ/R7ODzHKR"xDb!zKAHiY0 RedLU(fyQݵr]] Cj6ѪU!J-a>奂Jz|q 琈E0ym{A=J|7xx#luS6}Wz6#gޘ%r[%-Mi|Zov,e |YQp"z}_wԪ_hUvyc ѦY|)B&_; qիtMb\^cϏ& G}F+8nu;hdhp6Zbew7%5 3 3j`*-nxw-8ph$Rwmcg.#\ٚmd몂g Kdj,J(*}k_z~'H^sk#-dz7vq5_VONKF8%5*'Qc]Xioiٟĥûo岹#vDP0Ƕ`YoozVYT?/l$,D!M%c-V0̟lV+T%drL\0y?mlВ'FGL%4D2IEM MF>Oy3׳ݽ}X|wo_o,l biuS/#[(=948Ǡ`zz{a[aYGPIg,# Hu^-Cm]X_;+{>VWU mX0, ϣ4C<ЪW`Y"Fni|e̤Pk $>\|r=N"6  CJYǒb!ǶZ@MC#\V˫V)c=vjn̻ [5 VIa[xAqD1׶ XYZd2gr[AWfD/Wk3GiZeyx'eBD1D8%kkeL%OO<^-Fޜ$ 1-;єdhF$EmS'eQ]Ӊm0M,g2x8v,~7|/jf0ֽ%ю^0l8$-I (J=j;.XaZbMo;MC| -Q8<< .Zv9^[O|7~GQTm[TCHW"I*x5 9`aaq6ti_L>y8~a\{-'Z +D*A~6W^S?чwoajB§?ukA0 ~,Sԇ5k<ǷE[ {`3w??H3g[_UUfg^rBNv!ڝ"jꂣZBqQGg?{sal,B vU2+FwQ3ǞDq,cTD&L`jpoEM+bA /Vxs5d D:NTgE]);1 GɊ4O#]0\=AZ+ƝW$T;m t}eg bU mJ(Q7+cb,)gJ]tfRDOxIa%m2A1Wxigt!2kfi: .4$< ]90Lh6A;@P\.ٕ6L#0q\Gs|fS Xˤ2;V )(VĂ-] -0A\!CfDp MgCV+ }fK2X{(iUUD﹬,LӪ+}f!Xvb$O X@N v%%V_t[ˮ;aJl-j`AԐ{~G|uU9pULI.^x  Vh5_|H֍em=5Eg9ǙӿF@nO~OL>p8sM M|1TҹMBYC"O=6jڟoMzy} Qs;[o&$J X*U7 tEIz|=uFM֖cWrޢ>kαs_MGCIENDB`go-gir-generator-master/gogtk-demo/gnome-fs-regular.png000066400000000000000000000034031414263242200234340ustar00rootroot00000000000000PNG  IHDR04̓bKGDCIDATx՚KoWC4³*HtEʢ,RB+O]Y#P%XtQHx4< MTv`ĵӅ3;wSP+d߹w|?5w,N`u wP(|b(cccrQ_{@*VܺuKDDfffފ@Jr,bQdttW8%R!"H* ="ɰyf._ X Mlݺu^G\-[044DkkSЗ۷oϋ~abbLM6q :::J~y58yGww77~M85Bs&0 J%sccc\zRĆ ݜ:u {`O&hDhڪy_#GP,QY={| Ju.D>/_N.X\8q߸dF<zlP=QpF_]+!JQTi<8v.`B.rTz*j"U* |t/7,6`*y5SumۦYE8x2ո(fhnnv"(Tbd2&=S_+W.t67ѬEĚ@{}I9'ۿe$,1q>veO|jTytXD)U|DWDXL2,\kI5 $;w͛׆2.Nf`%X!+"ݻϟ%AH~:--UH*(HI|hDbg.\8ϲe^@$fۘML&@H)RT,ʈ5F6%B LNd׮ŋ5HB8i\LNZsZzp\B^'ĶCzXHk. $p?ԜkqUUx$!U}fr1IRcbDgYjM2 [j\Lb&-[IaWJ !vOgwe+l$k KYbbqR"S\4Bgck(Y(Da:khhrָ%Mk!~^|QFљ8؊ð)/ǡCd'B##tiFK(n&6MBJ&S(Ξ=Ú5%$Z%sypn)MCg9n[rp0'C/[ܫ*"ўXOnQ|b"̙_Xv]rzPv۞!Bx߾rO-r}ŵopkJnϟ?GW (Lpzh˸[Xӧfݺ=$0;--u34rps=٩WÇIC\ڀL.~}]rIeޅ)!Т.!k)0CHP*MZ0/dm(C@eIENDB`go-gir-generator-master/gogtk-demo/gnome-gimp.png000066400000000000000000000065221414263242200223260ustar00rootroot00000000000000PNG  IHDR00WgAMA1_ IDATxYk]u>{9w޶gllc#ǯ_Qܹu7up,+ k, !]?w @u ܴry=>ّ/$~IDhxm~Gȱ=fR.w'{ˡC"_"#acv*KDv ܂VK6Wztl0[; . 9<ckGn΍lR;y介~ &/xԙ ~w:$\":An(EFW~#AcR)ĭ4\OKs{&R@*=tӪW|B$BDp-xgp7zK~RH ѢrW\OBy񟟞Ǔ4++ݟ~xWQ,Z`olRZ2-v hJC g@ 0`O\!8 3v3X 0zE_s]^fvy\o<ЦMz^0o-[~ c8ȤDIdR!,j9ic_[6#)fݼaÆm޼!!Dqbb?=ȶKF|/b``{ޏ5kǐJǖ-[ƪP*VR1Z[Jz3WpdTMdldS*wx===m۶GǽfIo&q<?ժxWh~~vi^{m?8رcꫯBJVR R*( h֒Ʊ='20I.gN;HCyQyBvr''=Z vڅF3'`Fm<3={e&$A;IIJ({f0$GV (mb 0V:@rhrrB,_ѣGP,šs@>q߃a֭\SOhnRf}uՙ0l#٩T*-uM08O*ܝ=== fFehZ(J(9ϝ93'0n~i(RJT 8{}Π^  &VfX &fgseג3|߇Ð(Bp hPڇo}+ex~ԅSHJkZm IښU@BfÜ_Lkqaya!mU'mhـ=`6`f,? Vl$j ApY)rԇs1ro}c}ɞi4˲waE{{zz0 Q.GbCZITPy>=erJkLL]TIq3|fnqTux+ֺZT (ðJa I\CYV AAlIHc뚶p2z y5@4<5}nב˦pM?qx^R{dyZIΜG&SHrk@+ĄnNF sqnb}3VZZkRv;[P!`if[`f9;;{xHISiFJ* CiTJ0;W<.^Z@d-(B/Stz@n/5̘jg<9덎]` ۼqL |,H6ՆBT,T*7BO="Sgr0}SK0H3zjSU^uWu~NLW̧0iORIENDB`go-gir-generator-master/gogtk-demo/gnome-gmush.png000066400000000000000000000062541414263242200225170ustar00rootroot00000000000000PNG  IHDR00WgAMA1_ cIDATx[$YNU{{qlbK"1R2QL B ͑xKH<8h`@/+lǻk{޹LwOwuu9UU }|O/}O ĭh(.]X}[W; <_^qƜȄX02#Lcŕ+kzk\Gw}?Ǔp2&N1iFuvIuvr;\{ |鯭4ӉQXd֐KRg5֊VCFϾ'CLXpzWGɬa0걺&=Y*_K+ǎ羓c̘I(c9\{k-)vGC$h 88K__xWWgW't-" .XLvb+Ng0Ƣ2Eeh8kqIz]T2Gd6%"@nY>| `oFX^=vxƚek-ΝEj @f22kU|as <5d$Z-~@RcF޴,:ۼ|GzrTfIZ!|: 8p 91a@Jߗx+6][=Ӧj>pOn_" bc3?ϛukO!DQkuffZlnl> RiΟybҌԦh2 Gl.hxW^wMDŽ " C(Bk &;;=]u4 ֮T*:œqfKssdWw>?v۝}tZ$nR*?x {!koƯ-?ܳ{rHNSGvIRa8  ~#&qL$R0ers7h$NXťuV$J&WrX._M9<|ߗ~K)58ILb,Zn#ʼni$ J}y`1j s*qȷomR)v{sp/oH?[~qX!RJj*RqOiA)d2A)E$ycZs 9GZ%X\gqao.κ<=stؗŷD>Rz{D)>t|cDQDE$IB) jlr!.-h68r mh6:O|=|?k8VۯGkY$ Ks$Ii2 DQD(A0;3#8~|޲Gfnрtww|LN\B<[?~+? q;h6xO|| \),T*cPJ!GUG @NI!:>rC t]qB̀f3'G'~~OwָcJBeH)B0L}BCkspFYufm_]^!tuG/4GK9RT*8Bnׅ!ֲHE0Dx<RzD⯟},BxX~+~u2c}U/dxkR1뽑V@D¿)i>ed!0 ihQJM H)WIFfIoZGn&js\*x-'FkHd$v>iRΎ1fZE'2zkܠ9Ph-'PX,0Okb–IL&&;|7W 9rUˣ_ρmw#$I SZk8- $sV2[/H)d$J81Sŗ <.diZOZ_rљ#Ϝ9R 9HӔ4M}cJGQV[l4K`MI&|^B»x7x,g~Swoߟk03֫6Y,bMWr?[?;j1񪴜S|zoY|쳷S;s%>sj\3Җ\+A {?+%y2 P/=S .>٘cƘ2j;_ 'VF;k wN;njYo9-dG-ӿw?ӟ=B()9 4&0L.~$%KL(K~| _ѹ|h#B4xۍKx`Fi猆F?Ikm!qcQ%7 BY`x)uJRc|'g8w:{S@6s:.&R0 =y;zRJß[޲t_}&[i؋.YoKU!Ejg;*sf[)y@E ^G٠L^B6v@$9J@YJ@cp@hs;}jP `8V\Ib+~fժR9֘0r#?chEb5USб2wdЙBDEF(ՠ-4ƶu ra"nR͜>Y1U @2q{78asC^,yr\ģ'\kW!WbJCvFdIJjDS2B #l\S8IMJV@]e߳83lu2mu6ZYÿvW녙th6jLLX{wNgy=;wd#lm'Y,}T[ 6NsD:bj^tG)ǟ{Mo󙝇{.[Fxt+(M AElZET'12nF/"QlҜ02J+%Am D)C~l"oKm! dn[yǹOyԣ%!)RjV)5jK)kRJ8L]" i昭nil M3"݄"OZVc6F.[#7UPxSDq[kSkmbst!D@<ߪv:;f4ZG(9Α) /Í#$'eZbkAx>.v^ @^޶ֶMkmZ+1Ba1BITn+$:vgjT3p$(c'h3Mr&&4 HPiz6%t N;jZkT!Xp55afvVhCE4Mb"Ռ7N:!hk3\ Jr$PF;* 6|k1L5!D0?9uY>@1nRIiĒ:6/ʉ Ɉ2ֶhQ8r\g*h^1b!D`E`3U @=v޴V0M "I $ 2.f[ `uu{W[Bkg^ ,hkB$Z;֎$W|?Ԭ7pGjz}أO<,mFWu̥O]{l#3-R=И^ZI+~`6t kur>dZ֒8Ɋ3T̬\3*_;w.6?:p`f9zDgnĮKk)ԆfBXJ Zztx{n޿w5g1IT+dy&,#I0 |$[7 n[H^ѷΏN8%>Zq^sw~) !zvb(pd:H(4IyFRE IZQ=.TZpZ%^+x:򖛿!If)I>3\Gh)cTZ)cGQz@զ2rGKkkHuNIApn˅^R7a@ݡ.QuԽ];vuZ!T}jQNRT+UfXC 0&' B?LKRnsu^\yJ yv~1qFCbðpq1 !B@K)m!)W.|;}?QS 4,JV~ okwN33^zb8)q]Yx2a%b !TVTRqr)egi9#o$4Ea,Q<ׄQ\|+eƽ®z@$GIL/c&J~TN\^VmR1h!e/4OQ ]$q]_x^Dh1'{&o f@&`%4j.)!DF 4n)4ιJڻ0n^@eB'qa_|9?R5-oL Jkgѣ␰4`aaA}l6fxӾVn_LLy^8 +)," }MR]gU/mCCҀ/ \KylA[_/M-uǽv%Jy#҄Dv @tpPKQq?66*y |tKRRUVen~bՊ5.emmqAI}y`=Nm+_ϾNiJg3ޤW e)q+|%Ķ;^s1aIENDB`go-gir-generator-master/gogtk-demo/gnu-keys.png000066400000000000000000000074141414263242200220320ustar00rootroot00000000000000PNG  IHDR00WgAMA aIDATxkt]e゙[rr-M&i4IoŦC;DgPQTTguleP^Ҧ-msk~9Im}y|)̗:~yy}.qK\2C^Fd"弋Kt᪵UrL+ͷRu-YVV^zU+W (=ݽo `L-(`Fy9&NaYV왳vmۏ:/L/zefB01o2jy_8Pϱup H)B0qm_[ ȿV;@V(\{^fr(6 IG{x3cKս( *H$|)T4h?]ȂeneY9kjx4Jbd+W^y%լhB L  [|aIl2F~~+&OG @Uө|A< _ 8nSOn$I1UfV^~<`wn~ t4'8͞-ZXYyށT{߽ۿ_qǎR\RȬJ Il[8y%e^UQ5Mc_EVvϕxK"yn /﮻iK,554k>+cY=\mOw0 xmO~/P Be``}r!ʊ)- 3blя[i%hF*$LcuTcP⒊;>u{)j0%yyB` p㉸퇿]WWWwBǁQ`rJn'7†jB4E4Lo߫4kp$/w]MP5b$q|tb嗱kҲr=elt_="GeG7tM0M'߽;~rt]G"IA4¡0hhlzFF 3:$ccc$IFc8z9zG BB&Mرc<.馛)/+W||f9pEQP <.ӿxb&8ҊoRinm&77Jj-_Ƽy9s4gΝ"JY8R"}qʦa&j`A4Mlذk\k  ԾZolDUUt]_}}RL7^L@G>2EUPu.+ZJBz{zof$6JEE% ;.' ˪g΂HC "Yz@0H__/CA=ơCعs'K,acض͑#u}ctL%Oxɼ@QQQov(G&]]]]Pe1HSPX+0LښhhlॗvHũcH.iiiq,*QUΞսGbYAx|;w$;7p(*斪yϝxd0 x _bf/H_y_|'<9Bcǎ8y3˙;gPs &pl}G3RK v5V>3tZ͆O~7^/f(=>.\wI àa&M/}TM#;+#?EQQ*̟;˗zΎNod*Iii2~n}.**gdh+HOjo.a 7\rY"&6>55<.<ץ-?žp7QZVi o=B:==Xu,KpUܱAR{`?wE 'OP6ן"#QtM! 12CʛKco}wc) R0u #%'4 U?>D"Yy_?? ,kf:ōm[+k&pmTTT,]=[(x3SE_8R88I*"@+_FW\=|v4 ,\W M -郵ugsrm7d mݽ횪BP@(hB;u…5?=x'uyjS_kOYpݡ:+>6M>۾d;O5;{}#6//oY''UTTT3L'lK}ACRJ%A kBg[ԌT4hzo>JhBkVjUSÙL DUU;?vTaYvȡc=gN7=='yiT]m-mV 3KhqCowL&0 NCDz.L\Τ/y۽e˗rsM5.b$ Dcx}k+V.Ng{cC#4y/x'QV]ʫYZZꍌ Y{Q~WRnaswkwD"&w?K\{;$誂IENDB`go-gir-generator-master/gogtk-demo/gtk-logo-rgb.gif000066400000000000000000000144331414263242200225430ustar00rootroot00000000000000GIF89ak󪫹ԏƹ/L\lux 4# "7x:Z5d Y$]'+4 ."dܻҼ-E76Z7nNdlG7]9$7L 5(4=`-LE*48  ; &M=r2fpz$L-M>v!C %e)<9 H FE,)7 IKj)%6#&89;4P 4E&@4ޕpA YhPJ,A~(t,0C&Η"Cwa9 ۔ @5qGZpX@QH"\6eSdX:bR\T 2AdvP0CM p% pRBYDMwlBL h6l5zP10abK%qE9JY@+,6儳G[j72YЀtVa-:#,4!*}51a "mBNh[V0vC0A TIZp&: *L(",h:1B[?8[;B: L֭;n|pΗ$#F*`EuY >CF9BCJ7 C#(0BBG@fCd6tuCsyNDWA[zv'%Ԡ7\]凇sSQTa[`hR".Ye-d, BӡJAqAv`0@i,UA<@\b'^ʐcDƝQPp6" zk|U)L\A #(y B !.PB>0\&n`Cbv`->`k0A a@ @H#!~"Y> RWۂ&Q>TzGJWX(c%-%JP xjb[R? E|@$@:\c @AVpOXĀn~I{i"NЁ x"P#` Xo6(nK IVG7@2ˆAREp I! .X `+c,AC?qQrO~% otDAyiBڇ ^N @$$ి",C.tR$$` d4(t&v  Եk]fv^Ć>xS#U <1`"7{N#ȠS5쌷\pA {ݐH$Ћ$KGZPP֠I$Ӈqy8hwum WЇ~C PK VZo!A @HWl{!q` [s r|Eݵ F ыK@o2}ѵrpq #<Ƹ t@~EAM)^o`un "ems H` p y|pqЀ~0[$x_H~47U` 6r `6Pr_#Wt < 3@27UtPcA}x !0U6``` gW `dO@2@}YRPct&j 16`|px `O ) l9j2$ mIZa0o @|~ ؚG~ p P @A $0o밓{ UplJ/ n  X.Lm~ߐQr`Y rĠ UQq.҃)8iJ@RtًAG `6P%; ]ʀR b lRܠ j0mov~飊@j`H` %FAȐ _hbUwФ叛 {Xm kjtrPtʦ ڐAY`Đ lb)Z!7pqeq" Y|4Un``p`pj6 f` UC`r '/yH[W5 O wh*ʰ<$oqQ"}PUTJ(FS% `ZdZ%0.Apg2 OG`. ZlmخK6e!7 °`GW֤N:Щp.7^Xv{ZRnpl&fAp Y ͺ(d",+ 嚮ٕf_! c+ɛؓ`ЭI [m3$+~@sz]WBP!K yڀ&XVJ ^PkmW[Zi ZbG+4`>2\l!GP (+`Ep[hXWR7+["yfo 2 !g] Q D`|G^f7} 1˛ٖu> !0h}j`km˚Z|tp%o&ЅUj au[m~ / , (V$P{`w% Q 7`` kqC6pgxv7ً[f0ʶ f2%`)7b`Wt A$0f⢐c YY& `H7p !`&PܲwɎP #\)`Ƥ  v WTL3[kUP lbzˋ؈T7 Mo! ΜMǰ DMrI 7נZ^h% ;\X;L3٬ -됡^m k6)!F@ GE4t name_b: return 1 } } return 0 } func create_store() *gtk.ListStore { store := gtk.NewListStore( gobject.String, gobject.String, gdkpixbuf.PixbufGetType(), gobject.Boolean) // Set sort column and function store.SetDefaultSortFunc(sort_func) store.SetSortColumnID(-1, gtk.SortTypeAscending) return store } func fill_store(store *gtk.ListStore) { // temporarily disable sorting store.SetSortColumnID(-2, gtk.SortTypeAscending) defer store.SetSortColumnID(-1, gtk.SortTypeAscending) store.Clear() dir, err := os.Open(parent) if err != nil { println(err.Error()) return } defer dir.Close() entries, err := dir.Readdir(0) if err != nil { return } for _, entry := range entries { display_name := entry.Name() if strings.HasPrefix(display_name, ".") { // We ignore hidden files that start with a '.' continue } path := filepath.Join(parent, display_name) is_dir := entry.IsDir() var pixbuf *gdkpixbuf.Pixbuf if is_dir { pixbuf = folder_pixbuf } else { pixbuf = file_pixbuf } store.Append(path, display_name, pixbuf, is_dir) } } func item_activated(icon_view *gtk.IconView, tree_path *gtk.TreePath) { store := gtk.ToListStore(icon_view.GetModel()) iter, _ := store.GetIter(tree_path) var is_dir bool var path string store.Get(&iter, col_path, &path, col_is_directory, &is_dir) if !is_dir { return } // Replace parent with path and re-fill the model parent = path fill_store(store) // Sensitize the up button up_button.SetSensitive(true) } func up_clicked(store *gtk.ListStore) { parent = filepath.Dir(parent) fill_store(store) // Maybe de-sensitize the up button up_button.SetSensitive(parent != "/") } func home_clicked(store *gtk.ListStore) { parent = os.Getenv("HOME") fill_store(store) // Sensitize the up button up_button.SetSensitive(true) } func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetDefaultSize(650, 400) window.SetScreen(mainwin.GetScreen()) window.SetTitle("GtkIconView demo") window.Connect("destroy", func() { window = nil up_button = nil }) if err := load_pixbufs(); err != nil { dialog := gtk.NewMessageDialog(window, gtk.DialogFlagsDestroyWithParent, gtk.MessageTypeError, gtk.ButtonsTypeClose, "Failed to load an image: %s", err) dialog.Connect("response", func() { dialog.Destroy() }) dialog.Show() goto done } vbox := gtk.NewBox(gtk.OrientationVertical, 0) window.Add(vbox) tool_bar := gtk.NewToolbar() vbox.PackStart(tool_bar, false, false, 0) up_button = gtk.ToToolItem(gtk.NewToolButtonFromStock(gtk.StockGoUp)) up_button.SetIsImportant(true) up_button.SetSensitive(false) tool_bar.Insert(up_button, -1) home_button := gtk.NewToolButtonFromStock(gtk.StockHome) home_button.SetIsImportant(true) tool_bar.Insert(home_button, -1) sw := gtk.NewScrolledWindow(nil, nil) sw.SetShadowType(gtk.ShadowTypeEtchedIn) sw.SetPolicy(gtk.PolicyTypeAutomatic, gtk.PolicyTypeAutomatic) vbox.PackStart(sw, true, true, 0) // Create the store and fill it with the contents of '/' parent = "/" store := create_store() fill_store(store) icon_view := gtk.NewIconViewWithModel(store) icon_view.SetSelectionMode(gtk.SelectionModeMultiple) // Connect to the "clicked" signal of the "Up" tool button up_button.Connect("clicked", func() { up_clicked(store) }) // Connect to the "clicked" signal of the "Home" tool button home_button.Connect("clicked", func() { home_clicked(store) }) // We now set which model columns that correspond to the text // and pixbuf of each item icon_view.SetTextColumn(col_display_name) icon_view.SetPixbufColumn(col_pixbuf) // Connect to the "item-activated" signal icon_view.Connect("item-activated", item_activated) sw.Add(icon_view) icon_view.GrabFocus() } done: if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window }go-gir-generator-master/gogtk-demo/iconview_edit.go000066400000000000000000000041331414263242200227340ustar00rootroot00000000000000// Icon View/Editing and Drag-and-Drop // // The GtkIconView widget supports Editing and Drag-and-Drop. // This example also demonstrates using the generic GtkCellLayout // interface to set up cell renderers in an icon view. package iconview_edit import "gobject/gtk-3.0" import "gobject/gdk-3.0" import "gobject/gobject-2.0" import "gobject/gdkpixbuf-2.0" var window *gtk.Window func create_store() *gtk.ListStore { store := gtk.NewListStore(gobject.String) for _, item := range []string{"Red", "Green", "Blue", "Yellow"} { store.Append(item) } return store } func set_cell_color(cell_layout *gtk.CellLayout, cell *gtk.CellRenderer, model *gtk.TreeModel, iter *gtk.TreeIter) { var text string var pixel int model.Get(iter, 0, &text) if color, ok := gdk.ColorParse(text); ok { pixel = int(color.Red >> 8) << 24 | int(color.Green >> 8) << 16 | int(color.Blue >> 8) << 8 } pixbuf := gdkpixbuf.NewPixbuf(gdkpixbuf.ColorspaceRGB, false, 8, 24, 24) pixbuf.Fill(pixel) cell.SetProperty("pixbuf", pixbuf) } func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetScreen(mainwin.GetScreen()) window.SetTitle("Editing and Drag-and-Drop") window.Connect("destroy", func() { window = nil }) store := create_store() icon_view := gtk.NewIconViewWithModel(store) icon_view.SetSelectionMode(gtk.SelectionModeSingle) icon_view.SetItemOrientation(gtk.OrientationHorizontal) icon_view.SetColumns(2) icon_view.SetReorderable(true) r := gtk.ToCellRenderer(gtk.NewCellRendererPixbuf()) icon_view.PackStart(r, true) icon_view.SetCellDataFunc(r, set_cell_color) r = gtk.ToCellRenderer(gtk.NewCellRendererText()) icon_view.PackStart(r, true) r.SetProperty("editable", true) r.Connect("edited", func(cell *gtk.CellRendererText, path, text string) { p := gtk.NewTreePathFromString(path) iter, _ := store.GetIter(p) store.Set(&iter, 0, text) p.Free() }) icon_view.SetAttributes(r, "text", 0) window.Add(icon_view) } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window }go-gir-generator-master/gogtk-demo/info_bar.go000066400000000000000000000050341414263242200216640ustar00rootroot00000000000000// Info bar // // Info bar widgets are used to report important messages to the user. package info_bar import "gobject/gtk-3.0" var window *gtk.Window func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetScreen(mainwin.GetScreen()) window.SetTitle("Info Bars") window.Connect("destroy", func() { window = nil }) window.SetBorderWidth(8) vbox := gtk.NewBox(gtk.OrientationVertical, 0) window.Add(vbox) bar := gtk.NewInfoBar() vbox.PackStart(bar, false, false, 0) bar.SetMessageType(gtk.MessageTypeInfo) label := gtk.NewLabel("This is an info bar with message type GTK_MESSAGE_INFO") gtk.ToBox(bar.GetContentArea()).PackStart(label, false, false, 0) bar = gtk.NewInfoBar() vbox.PackStart(bar, false, false, 0) bar.SetMessageType(gtk.MessageTypeWarning) label = gtk.NewLabel("This is an info bar with message type GTK_MESSAGE_WARNING") gtk.ToBox(bar.GetContentArea()).PackStart(label, false, false, 0) bar = gtk.NewInfoBarWithButtons(gtk.StockOk, gtk.ResponseTypeOk) bar.Connect("response", func(info_bar *gtk.InfoBar, response_id gtk.ResponseType) { dialog := gtk.NewMessageDialog(window, gtk.DialogFlagsModal|gtk.DialogFlagsDestroyWithParent, gtk.MessageTypeInfo, gtk.ButtonsTypeOk, "You clicked a button on an info bar") dialog.FormatSecondaryText("Your response has id %d", response_id) dialog.Run() dialog.Destroy() }) vbox.PackStart(bar, false, false, 0) bar.SetMessageType(gtk.MessageTypeQuestion) label = gtk.NewLabel("This is an info bar with message type GTK_MESSAGE_QUESTION") gtk.ToBox(bar.GetContentArea()).PackStart(label, false, false, 0) bar = gtk.NewInfoBar() vbox.PackStart(bar, false, false, 0) bar.SetMessageType(gtk.MessageTypeError) label = gtk.NewLabel("This is an info bar with message type GTK_MESSAGE_ERROR") gtk.ToBox(bar.GetContentArea()).PackStart(label, false, false, 0) bar = gtk.NewInfoBar() vbox.PackStart(bar, false, false, 0) bar.SetMessageType(gtk.MessageTypeWarning) label = gtk.NewLabel("This is an info bar with message type GTK_MESSAGE_WARNING") gtk.ToBox(bar.GetContentArea()).PackStart(label, false, false, 0) frame := gtk.NewFrame("Info bars") vbox.PackStart(frame, false, false, 8) vbox2 := gtk.NewBox(gtk.OrientationVertical, 8) vbox2.SetBorderWidth(8) frame.Add(vbox2) label = gtk.NewLabel("An example of different info bars") vbox2.PackStart(label, false, false, 0) } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window } go-gir-generator-master/gogtk-demo/links.go000066400000000000000000000026501414263242200212260ustar00rootroot00000000000000// Links // // GtkLabel can show hyperlinks. The default action is to call // gtk_show_uri() on their URI, but it is possible to override // this with a custom handler. package links import "gobject/gtk-3.0" var window *gtk.Window const label_text = `Some text may be marked up as hyperlinks, which can be clicked or activated via keynav` const dialog_text = `The term keynav is a shorthand for ` + `keyboard navigation and refers to the process of using ` + `a program (exclusively) via keyboard input.` func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetTitle("Links") window.Connect("destroy", func() { window = nil }) window.SetBorderWidth(12) label := gtk.NewLabel(label_text) label.SetUseMarkup(true) label.Connect("activate-link", activate_link) window.Add(label) } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window } func activate_link(label *gtk.Label, uri string) bool { if uri == "keynav" { parent := gtk.ToWindow(label.GetParent()) dialog := gtk.NewMessageDialogWithMarkup(parent, gtk.DialogFlagsDestroyWithParent, gtk.MessageTypeInfo, gtk.ButtonsTypeOk, dialog_text) dialog.Present() dialog.Connect("response", func() { dialog.Destroy() }) return true } return false } go-gir-generator-master/gogtk-demo/list_store.go000066400000000000000000000131271414263242200222760ustar00rootroot00000000000000// Tree View/List Store // // The GtkListStore is used to store data in list form, to be used // later on by a GtkTreeView to display it. This demo builds a // simple GtkListStore and displays it. See the Stock Browser // demo for a more advanced example. package list_store import ( "gobject/gdk-3.0" "gobject/gobject-2.0" "gobject/gtk-3.0" "time" ) var window *gtk.Window type bug struct { fixed bool number int severity string description string } const ( column_fixed = iota column_number column_severity column_description column_pulse column_icon column_active column_sensitive ) var data = []bug{ {false, 60482, "Normal", "scrollable notebooks and hidden tabs"}, {false, 60620, "Critical", "gdk_window_clear_area (gdkwindow-win32.c) is not thread-safe"}, {false, 50214, "Major", "Xft support does not clean up correctly"}, {true, 52877, "Major", "GtkFileSelection needs a refresh method. "}, {false, 56070, "Normal", "Can't click button after setting in sensitive"}, {true, 56355, "Normal", "GtkLabel - Not all changes propagate correctly"}, {false, 50055, "Normal", "Rework width/height computations for TreeView"}, {false, 58278, "Normal", "gtk_dialog_set_response_sensitive () doesn't work"}, {false, 55767, "Normal", "Getters for all setters"}, {false, 56925, "Normal", "Gtkcalender size"}, {false, 56221, "Normal", "Selectable label needs right-click copy menu"}, {true, 50939, "Normal", "Add shift clicking to GtkTextView"}, {false, 6112, "Enhancement", "netscape-like collapsable toolbars"}, {false, 1, "Normal", "First bug :=)"}, } func pulse(ticker *time.Ticker, cancel chan int, list_store *gtk.ListStore) { for { select { case <-ticker.C: gdk.ThreadsEnter() var pulse int iter, _ := list_store.GetIterFirst() list_store.Get(&iter, column_pulse, &pulse) if pulse == 99999 { pulse = 0 } else { pulse++ } list_store.Set(&iter, column_pulse, pulse, column_active, true) gdk.ThreadsLeave() case <-cancel: return } } } func create_model() *gtk.ListStore { store := gtk.NewListStore(gobject.Boolean, gobject.Int, gobject.String, gobject.String, gobject.Int, gobject.String, gobject.Boolean, gobject.Boolean) for i := range data { var icon_name string var sensitive = true if i == 1 || i == 3 { icon_name = "battery-caution-charging-symbolic" } if i == 3 { sensitive = false } store.Append(data[i].fixed, data[i].number, data[i].severity, data[i].description, 0, icon_name, false, sensitive) } return store } func add_columns(treeview *gtk.TreeView, model *gtk.ListStore) { var r gtk.CellRendererLike var c *gtk.TreeViewColumn // column for fixed toggles toggle := gtk.NewCellRendererToggle() toggle.Connect("toggled", func(cell *gtk.CellRendererToggle, path_str string) { path := gtk.NewTreePathFromString(path_str) iter, _ := model.GetIter(path) var checked bool model.Get(&iter, column_fixed, &checked) model.Set(&iter, column_fixed, !checked) }) c = gtk.NewTreeViewColumnWithAttributes("Fixed?", toggle, "active", column_fixed) // set this column to a fixed sizing (of 50 pixels) c.SetSizing(gtk.TreeViewColumnSizingFixed) c.SetFixedWidth(50) treeview.AppendColumn(c) // column for bug numbers r = gtk.NewCellRendererText() c = gtk.NewTreeViewColumnWithAttributes("Bug number", r, "text", column_number) c.SetSortColumnID(column_number) treeview.AppendColumn(c) // column for severities r = gtk.NewCellRendererText() c = gtk.NewTreeViewColumnWithAttributes("Severity", r, "text", column_severity) c.SetSortColumnID(column_severity) treeview.AppendColumn(c) // column for description r = gtk.NewCellRendererText() c = gtk.NewTreeViewColumnWithAttributes("Description", r, "text", column_description) c.SetSortColumnID(column_description) treeview.AppendColumn(c) // column for spinner r = gtk.NewCellRendererSpinner() c = gtk.NewTreeViewColumnWithAttributes("Spinning", r, "pulse", column_pulse, "active", column_active) c.SetSortColumnID(column_pulse) treeview.AppendColumn(c) // column for symbolic icon pixbuf := gtk.NewCellRendererPixbuf() pixbuf.SetProperty("follow-state", true) c = gtk.NewTreeViewColumnWithAttributes("Symbolic icon", pixbuf, "icon-name", column_icon, "sensitive", column_sensitive) c.SetSortColumnID(column_icon) treeview.AppendColumn(c) } func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { ticker := time.NewTicker(80 * time.Millisecond) cancel := make(chan int) window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetTitle("gtk.ListStore demo") window.Connect("destroy", func() { window = nil }) window.SetBorderWidth(8) vbox := gtk.NewBox(gtk.OrientationVertical, 8) window.Add(vbox) label := gtk.NewLabel("This is the bug list (note: not based on real data, it would be nice to have a nice ODBC interface to bugzilla or so, though).") vbox.PackStart(label, false, false, 0) sw := gtk.NewScrolledWindow(nil, nil) sw.SetShadowType(gtk.ShadowTypeEtchedIn) sw.SetPolicy(gtk.PolicyTypeNever, gtk.PolicyTypeAutomatic) vbox.PackStart(sw, true, true, 0) // create tree model model := create_model() // create tree view treeview := gtk.NewTreeViewWithModel(model) treeview.SetRulesHint(true) treeview.SetSearchColumn(column_description) sw.Add(treeview) // add column to the tree view add_columns(treeview, model) // finish & show window.SetDefaultSize(280, 250) window.Connect("delete-event", func() { ticker.Stop() cancel <- 0 }) go pulse(ticker, cancel, model) } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window } go-gir-generator-master/gogtk-demo/main.go000066400000000000000000000222011414263242200210240ustar00rootroot00000000000000package main import ( "bytes" "go/ast" "go/parser" "go/scanner" "go/token" "gobject/gdk-3.0" "gobject/gdkpixbuf-2.0" "gobject/gobject-2.0" "gobject/gtk-3.0" "gobject/pango-1.0" "io/ioutil" "os" "strings" "./gogtk-demo/common" ) const ( title_column = iota filename_column func_column style_column ) var infobuf *gtk.TextBuffer var sourcebuf *gtk.TextBuffer func create_tree_view() *gtk.Widget { model := gtk.NewTreeStore( gobject.String, // title gobject.String, // filename gobject.GoInterface, // app gobject.Int, // style ) tree_view := gtk.NewTreeViewWithModel(model) selection := tree_view.GetSelection() selection.SetMode(gtk.SelectionModeBrowse) tree_view.SetSizeRequest(200, -1) for _, demo := range demos { iter := model.Append(nil, demo.Title, demo.Filename, demo.Func, pango.StyleNormal) for _, cdemo := range demo.Children { model.Append(&iter, cdemo.Title, cdemo.Filename, cdemo.Func, pango.StyleNormal) } } r := gtk.NewCellRendererText() c := gtk.NewTreeViewColumnWithAttributes("Widget (double click for demo)", r, "text", title_column, "style", style_column) tree_view.AppendColumn(c) iter, _ := model.GetIterFirst() selection.SelectIter(&iter) selection.Connect("changed", func(selection *gtk.TreeSelection) { _, iter, ok := selection.GetSelected() if !ok { return } var filename string model.Get(&iter, filename_column, &filename) if filename != "" { load_file(filename) } }) tree_view.Connect("row-activated", func(tree_view *gtk.TreeView, path *gtk.TreePath) { iter, _ := model.GetIter(path) var app interface{} var style pango.Style model.Get(&iter, func_column, &app, style_column, &style) if style == pango.StyleItalic { style = pango.StyleNormal } else { style = pango.StyleItalic } if app.(DemoFunc) == nil { return } model.Set(&iter, style_column, style) w := app.(DemoFunc)(gtk.ToWindow(tree_view.GetToplevel())) if w != nil { w.Connect("destroy", func() { var style pango.Style model.Get(&iter, style_column, &style) if style == pango.StyleItalic { model.Set(&iter, style_column, pango.StyleNormal) } }) } }) tree_view.CollapseAll() tree_view.SetHeadersVisible(false) scrolled_window := gtk.NewScrolledWindow(nil, nil) scrolled_window.SetPolicy(gtk.PolicyTypeNever, gtk.PolicyTypeAutomatic) scrolled_window.Add(tree_view) label := gtk.NewLabel("Widget (double click for demo)") nb := gtk.NewNotebook() nb.AppendPage(scrolled_window, label) tree_view.GrabFocus() return gtk.ToWidget(nb) } func create_text(is_source bool) (*gtk.ScrolledWindow, *gtk.TextBuffer) { sw := gtk.NewScrolledWindow(nil, nil) sw.SetPolicy(gtk.PolicyTypeAutomatic, gtk.PolicyTypeAutomatic) sw.SetShadowType(gtk.ShadowTypeIn) tv := gtk.NewTextView() sw.Add(tv) buf := gtk.NewTextBuffer(nil) tv.SetBuffer(buf) tv.SetEditable(false) tv.SetCursorVisible(false) if is_source { font_desc := pango.FontDescriptionFromString( "BitStream Vera Sans Mono, Monaco, Consolas, Courier New, monospace 9") tv.OverrideFont(font_desc) tv.SetWrapMode(gtk.WrapModeNone) } else { tv.SetWrapMode(gtk.WrapModeWord) tv.SetPixelsAboveLines(2) tv.SetPixelsBelowLines(2) } return sw, buf } func setup_default_icon() { filename := common.FindFile("gtk-logo-rgb.gif") pixbuf, err := gdkpixbuf.NewPixbufFromFile(filename) if err != nil { dialog := gtk.NewMessageDialog(nil, 0, gtk.MessageTypeError, gtk.ButtonsTypeClose, "Failed to read icon file: %s", err) dialog.Connect("response", func() { dialog.Destroy() }) dialog.ShowAll() } else { pixbuf = pixbuf.AddAlpha(true, 0xFF, 0xFF, 0xFF) gtk.WindowSetDefaultIcon(pixbuf) } } var current_file string var go_highlighter_idents = map[string]string{ "true": "predefined", "false": "predefined", "iota": "predefined", "nil": "predefined", } type go_highlighter struct { fset *token.FileSet buf *gtk.TextBuffer file *ast.File data []byte } func (this *go_highlighter) highlight(tag string, beg, end token.Pos) { begp := this.fset.Position(beg) endp := this.fset.Position(end) begc, endc := begp.Column-1, endp.Column-1 begl, endl := begp.Line-1, endp.Line-1 if begl < 0 { return } begi := this.buf.GetIterAtLineOffset(begl, begc) endi := this.buf.GetIterAtLineOffset(endl, endc) this.buf.ApplyTagByName(tag, &begi, &endi) } func (this *go_highlighter) highlight_file() { var s scanner.Scanner fset := token.NewFileSet() s.Init(fset.AddFile(current_file, fset.Base(), len(this.data)), this.data, nil, 0) for { pos, tok, str := s.Scan() if tok == token.EOF { break } if tok.IsKeyword() { this.highlight("keyword", pos, pos+token.Pos(len(str))) } } ast.Inspect(this.file, func(node ast.Node) bool { switch n := node.(type) { case *ast.BasicLit: switch n.Kind { case token.STRING, token.CHAR: this.highlight("string", n.Pos(), n.End()) case token.INT, token.FLOAT, token.IMAG: this.highlight("number", n.Pos(), n.End()) } case *ast.Ident: if tag, ok := go_highlighter_idents[n.Name]; ok { this.highlight(tag, n.Pos(), n.End()) break } if n.Obj != nil && n.Obj.Pos() == n.Pos() { if n.Obj.Kind == ast.Fun { this.highlight("function", n.Pos(), n.End()) } else { this.highlight("declaration", n.Pos(), n.End()) } } case *ast.CallExpr: switch f := n.Fun.(type) { case *ast.Ident: this.highlight("funcall", f.Pos(), f.End()) case *ast.SelectorExpr: this.highlight("funcall", f.Sel.Pos(), f.Sel.End()) } } return true }) for _, cg := range this.file.Comments { this.highlight("comment", cg.Pos(), cg.End()) } } func fontify(data []byte) { fset := token.NewFileSet() file, err := parser.ParseFile(fset, current_file, data, parser.ParseComments) if err != nil { println("failed to parse file: ", err.Error()) return } x := go_highlighter{fset, sourcebuf, file, data} x.highlight_file() } func set_info(info string) { var para bytes.Buffer iter := infobuf.GetStartIter() lines := strings.Split(info, "\n") for i, line := range lines { switch i { case 0: infobuf.InsertWithTagsByName(&iter, line, -1, "title") infobuf.Insert(&iter, "\n", -1) case 1: continue default: if line == "" { // flush paragraph on empty lines para.WriteString("\n") infobuf.Insert(&iter, para.String(), -1) para.Reset() continue } // by default append to paragraph buffer if para.Len() != 0 { para.WriteString(" ") } para.WriteString(line) // flush on last like as well: if line != "" && i == len(lines)-1 { para.WriteString("\n") infobuf.Insert(&iter, para.String(), -1) para.Reset() } } } } func load_file(filename string) { if current_file == filename { return } current_file = filename // clear info and source buffers beg, end := infobuf.GetBounds() infobuf.Delete(&beg, &end) beg, end = sourcebuf.GetBounds() sourcebuf.Delete(&beg, &end) // find file filename_full := common.FindFile(filename) if filename_full == "" { println("failed to find file: ", filename) return } // load file data, err := ioutil.ReadFile(filename_full) if err != nil { println("failed to read file: ", err.Error()) return } // figure out package info and starting offset fset := token.NewFileSet() file, err := parser.ParseFile(fset, current_file, data, parser.ParseComments|parser.PackageClauseOnly) if err != nil { println("failed to parse package clause: ", err.Error()) return } var offset int if file.Doc != nil { set_info(strings.TrimSpace(file.Doc.Text())) pos := fset.Position(file.Doc.End()) offset = pos.Offset + 1 } beg = sourcebuf.GetStartIter() sourcebuf.Insert(&beg, string(data[offset:]), -1) fontify(data[offset:]) } func main() { gdk.ThreadsInit() gtk.Init(os.Args) setup_default_icon() window := gtk.NewWindow(gtk.WindowTypeToplevel) window.SetTitle("GoGTK Code Demos") window.Connect("destroy", func() { gtk.MainQuit() }) window.SetDefaultSize(600, 400) hbox := gtk.NewHBox(false, 3) window.Add(hbox) // treeview tree_view := create_tree_view() hbox.PackStart(tree_view, false, false, 0) // notebook notebook := gtk.NewNotebook() hbox.PackStart(notebook, true, true, 0) // info var sw *gtk.ScrolledWindow sw, infobuf = create_text(false) notebook.AppendPage(sw, gtk.NewLabelWithMnemonic("_Info")) infobuf.CreateTag("title", "font", "Sans 18") // source sw, sourcebuf = create_text(true) notebook.AppendPage(sw, gtk.NewLabelWithMnemonic("_Source")) sourcebuf.CreateTag("comment", "foreground", "#0066FF") sourcebuf.CreateTag("declaration", "foreground", "#318495") sourcebuf.CreateTag("funcall", "foreground", "#3C4C72", "weight", pango.WeightBold) sourcebuf.CreateTag("string", "foreground", "#036A07") sourcebuf.CreateTag("keyword", "weight", pango.WeightBold, "foreground", "#0707FF") sourcebuf.CreateTag("function", "weight", pango.WeightBold, "foreground", "#0000A2") sourcebuf.CreateTag("number", "weight", pango.WeightBold, "foreground", "#C5060B") sourcebuf.CreateTag("predefined", "weight", pango.WeightBold, "foreground", "#585CF6") window.ShowAll() load_file(demos[0].Filename) gdk.ThreadsEnter() gtk.Main() gdk.ThreadsLeave() } go-gir-generator-master/gogtk-demo/main_window.go000066400000000000000000000172261414263242200224260ustar00rootroot00000000000000// Application main window // // Demonstrates a typical application window with menubar, toolbar, statusbar. package main_window import "gobject/gobject-2.0" import "gobject/gtk-3.0" import "gobject/gdkpixbuf-2.0" import "fmt" import "./gogtk-demo/common" var window *gtk.Window var infobar *gtk.InfoBar var messagelabel *gtk.Label var mgr *gtk.UIManager func activate_action(action *gtk.Action) { name := action.GetName() typename := action.GetType().String() if name == "DarkTheme" { value := gtk.ToToggleAction(action).GetActive() settings := gtk.SettingsGetDefault() settings.SetProperty("gtk-application-prefer-dark-theme", value) return } dialog := gtk.NewMessageDialog(window, gtk.DialogFlagsDestroyWithParent, gtk.MessageTypeInfo, gtk.ButtonsTypeClose, `You activated action: "%s" of type "%s"`, name, typename) dialog.Connect("response", func() { dialog.Destroy() }) dialog.Show() } func about_cb() { // TODO: implement gtk_show_about_dialog and better about dialog dialog := gtk.NewAboutDialog() dialog.SetName("GoGTK Demo") dialog.SetCopyright("© Copyright 201x nsf ") dialog.SetWebsite("http://github.com/nsf/gogobject") dialog.Connect("response", func() { dialog.Destroy() }) dialog.Show() } var entries = []gtk.ActionEntry{ {Name: "FileMenu", Label: "_File"}, {Name: "OpenMenu", Label: "_Open"}, {Name: "PreferencesMenu", Label: "_Preferences"}, {Name: "ColorMenu", Label: "_Color"}, {Name: "ShapeMenu", Label: "_Shape"}, {Name: "HelpMenu", Label: "_Help"}, {"New", gtk.StockNew, "_New", "N", "Create a new file", activate_action}, {"Open", gtk.StockOpen, "_Open", "O", "Open a new file", activate_action}, {"Save", gtk.StockSave, "_Save", "S", "Save current file", activate_action}, {"SaveAs", gtk.StockSave, "Save _As...", gobject.NilString, "Save to a file", activate_action}, {"Quit", gtk.StockQuit, "_Quit", "Q", "Quit", activate_action}, {"About", gobject.NilString, "_About", "A", "About", about_cb}, {"Logo", "demo-gtk-logo", gobject.NilString, gobject.NilString, "GTK+", activate_action}, } var toggle_entries = []gtk.ToggleActionEntry{ {"Bold", gtk.StockBold, "_Bold", "B", "Bold", activate_action, true}, {"DarkTheme", gobject.NilString, "_Prefer Dark Theme", gobject.NilString, "Prefer Dark Theme", activate_action, false}, } const ( color_red = iota color_green color_blue ) var color_entries = []gtk.RadioActionEntry{ {"Red", gobject.NilString, "_Red", "R", "Blood", color_red}, {"Green", gobject.NilString, "_Green", "G", "Grass", color_green}, {"Blue", gobject.NilString, "_Blue", "B", "Sky", color_blue}, } const ( shape_square = iota shape_rectangle shape_oval ) var shape_entries = []gtk.RadioActionEntry{ {"Square", gobject.NilString, "_Square", "S", "Square", shape_square}, {"Rectangle", gobject.NilString, "_Rectangle", "R", "Rectangle", shape_rectangle}, {"Oval", gobject.NilString, "_Oval", "O", "Egg", shape_oval}, } var ui_info = ` ` var stock_icons_registered bool func register_stock_icons() { if stock_icons_registered { return } items := []gtk.StockItem{ {"demo-gtk-logo", "_GTK!", 0, 0, gobject.NilString}, } stock_icons_registered = true gtk.StockAddItems(items) factory := gtk.NewIconFactory() factory.AddDefault() pixbuf, err := gdkpixbuf.NewPixbufFromFile(common.FindFile("gtk-logo-rgb.gif")) if err != nil { println("failed to load GTK logo for toolbar") return } transparent := pixbuf.AddAlpha(true, 0xFF, 0xFF, 0xFF) icon_set := gtk.NewIconSetFromPixbuf(transparent) factory.Add("demo-gtk-logo", icon_set) } func activate_radio_action(action *gtk.Action, current *gtk.RadioAction) { name := current.GetName() typename := current.GetType().String() active := current.GetActive() value := current.GetCurrentValue() if active { text := fmt.Sprintf("You activated radio action: \"%s\" of type \"%s\".\n"+ "Current value: %d", name, typename, value) messagelabel.SetText(text) infobar.SetMessageType(gtk.MessageType(value)) infobar.Show() } } func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { register_stock_icons() // Create the toplevel window window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetScreen(mainwin.GetScreen()) window.SetTitle("Application Window") window.SetIconName("document-open") window.Connect("destroy", func() { window = nil infobar = nil messagelabel = nil mgr = nil }) table := gtk.NewGrid() window.Add(table) // Create the menubar and toolbar action_group := gtk.NewActionGroup("AppWindowActions") action_group.AddActions(entries) action_group.AddToggleActions(toggle_entries) action_group.AddRadioActions(color_entries, color_red, activate_radio_action) action_group.AddRadioActions(shape_entries, shape_square, activate_radio_action) mgr = gtk.NewUIManager() mgr.InsertActionGroup(action_group, 0) window.AddAccelGroup(mgr.GetAccelGroup()) _, err := mgr.AddUIFromString(ui_info, -1) if err != nil { println("building menus failed: ", err.Error()) } bar := mgr.GetWidget("/MenuBar") bar.Show() bar.SetHAlign(gtk.AlignFill) table.Attach(bar, 0, 0, 1, 1) bar = mgr.GetWidget("/ToolBar") bar.Show() bar.SetHAlign(gtk.AlignFill) table.Attach(bar, 0, 1, 1, 1) // Create document infobar = gtk.NewInfoBar() infobar.SetNoShowAll(true) messagelabel = gtk.NewLabel(gobject.NilString) messagelabel.Show() gtk.ToBox(infobar.GetContentArea()).PackStart(messagelabel, true, true, 0) infobar.AddButton(gtk.StockOk, gtk.ResponseTypeOk) infobar.Connect("response", func() { infobar.Hide() }) infobar.SetHAlign(gtk.AlignFill) table.Attach(infobar, 0, 2, 1, 1) sw := gtk.NewScrolledWindow(nil, nil) sw.SetPolicy(gtk.PolicyTypeAutomatic, gtk.PolicyTypeAutomatic) sw.SetShadowType(gtk.ShadowTypeIn) sw.SetHAlign(gtk.AlignFill) sw.SetVAlign(gtk.AlignFill) sw.SetHExpand(true) sw.SetVExpand(true) table.Attach(sw, 0, 3, 1, 1) window.SetDefaultSize(200, 200) contents := gtk.NewTextView() sw.Add(contents) contents.GrabFocus() // Create statusbar statusbar := gtk.NewStatusbar() statusbar.SetHAlign(gtk.AlignFill) table.Attach(statusbar, 0, 4, 1, 1) // Show text widget info in the statusbar buffer := contents.GetBuffer() update_statusbar := func() { statusbar.Pop(0) count := buffer.GetCharCount() iter := buffer.GetIterAtMark(buffer.GetInsert()) row := iter.GetLine() col := iter.GetLineOffset() msg := fmt.Sprintf("Cursor at row %d column %d - %d chars in document", row, col, count) statusbar.Push(0, msg) } buffer.Connect("changed", update_statusbar) buffer.Connect("mark_set", update_statusbar) update_statusbar() } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window } go-gir-generator-master/gogtk-demo/menus.go000066400000000000000000000077521414263242200212450ustar00rootroot00000000000000// Menus // // There are several widgets involved in displaying menus. The // GtkMenuBar widget is a menu bar, which normally appears horizontally // at the top of an application, but can also be layed out vertically. // The GtkMenu widget is the actual menu that pops up. Both GtkMenuBar // and GtkMenu are subclasses of GtkMenuShell; a GtkMenuShell contains // menu items (GtkMenuItem). Each menu item contains text and/or images // and can be selected by the user. // // There are several kinds of menu item, including plain GtkMenuItem, // GtkCheckMenuItem which can be checked/unchecked, GtkRadioMenuItem // which is a check menu item that's in a mutually exclusive group, // GtkSeparatorMenuItem which is a separator bar, GtkTearoffMenuItem // which allows a GtkMenu to be torn off, and GtkImageMenuItem which // can place a GtkImage or other widget next to the menu text. // // A GtkMenuItem can have a submenu, which is simply a GtkMenu to pop // up when the menu item is selected. Typically, all menu items in a menu bar // have submenus. // // GtkUIManager provides a higher-level interface for creating menu bars // and menus; while you can construct menus manually, most people don't // do that. There's a separate demo for GtkUIManager. package menus import "gobject/gtk-3.0" import "fmt" func create_menu(depth int, tearoff bool) *gtk.Menu { if depth < 1 { return nil } menu := gtk.NewMenu() if tearoff { menuitem := gtk.NewTearoffMenuItem() menu.Append(menuitem) menuitem.Show() } // var group *gtk.RadioMenuItem for i, j := 0, 1; i < 5; i, j = i+1, j+1 { label := fmt.Sprintf("item %2d - %d", depth, j) // TODO: groups var menuitem *gtk.RadioMenuItem menuitem = gtk.NewRadioMenuItemWithLabel(nil, label) // if i == 0 { // group = menuitem // } menu.Append(menuitem) menuitem.Show() if i == 3 { menuitem.SetSensitive(false) } menuitem.SetSubmenu(create_menu(depth-1, true)) } return menu } func change_orientation(button *gtk.Widget, menubar *gtk.MenuBar) { parent := gtk.ToOrientable(menubar.GetParent()) orientation := parent.GetOrientation() if orientation == gtk.OrientationVertical { menubar.SetProperty("pack-direction", gtk.PackDirectionTtb) parent.SetOrientation(gtk.OrientationHorizontal) } else { menubar.SetProperty("pack-direction", gtk.PackDirectionLtr) parent.SetOrientation(gtk.OrientationVertical) } } var window *gtk.Window func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetScreen(mainwin.GetScreen()) window.SetTitle("Menus") window.Connect("destroy", func() { window = nil }) accel_group := gtk.NewAccelGroup() window.AddAccelGroup(accel_group) window.SetBorderWidth(0) box := gtk.NewBox(gtk.OrientationHorizontal, 0) window.Add(box) box.Show() box1 := gtk.NewBox(gtk.OrientationVertical, 0) box.Add(box1) box1.Show() menubar := gtk.NewMenuBar() box1.PackStart(menubar, false, true, 0) menubar.Show() menu := create_menu(2, true) menuitem := gtk.NewMenuItemWithLabel("test\nline2") menuitem.SetSubmenu(menu) menubar.Append(menuitem) menuitem.Show() menuitem = gtk.NewMenuItemWithLabel("foo") menuitem.SetSubmenu(create_menu(3, true)) menubar.Append(menuitem) menuitem.Show() menuitem = gtk.NewMenuItemWithLabel("bar") menuitem.SetSubmenu(create_menu(4, true)) menubar.Append(menuitem) menuitem.Show() box2 := gtk.NewBox(gtk.OrientationVertical, 10) box2.SetBorderWidth(10) box1.PackStart(box2, false, true, 0) box2.Show() button := gtk.NewButtonWithLabel("Flip") button.Connect("clicked", func(button *gtk.Widget) { change_orientation(button, menubar) }) box2.PackStart(button, true, true, 0) button.Show() button = gtk.NewButtonWithLabel("Close") button.Connect("clicked", func() { window.Destroy() }) box2.PackStart(button, true, true, 0) button.SetCanDefault(true) button.GrabDefault() button.Show() } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window }go-gir-generator-master/gogtk-demo/paned_widgets.go000066400000000000000000000067541414263242200227340ustar00rootroot00000000000000// Paned Widgets // // The GtkHPaned and GtkVPaned Widgets divide their content // area into two panes with a divider in between that the // user can adjust. A separate child is placed into each // pane. // // There are a number of options that can be set for each pane. // This test contains both a horizontal (HPaned) and a vertical // (VPaned) widget, and allows you to adjust the options for // each side of each widget. package paned_widgets import "gobject/gobject-2.0" import "gobject/gtk-3.0" var window *gtk.Window func toggle(child *gtk.Widget, toggle_shrink, toggle_resize bool) { paned := gtk.ToPaned(child.GetParent()) // we can do that because there's only one Go representation // of every gobject is_child1 := child == paned.GetChild1() var resize, shrink bool paned.ChildGet(child, "resize", &resize, "shrink", &shrink) if toggle_resize { resize = !resize } if toggle_shrink { shrink = !shrink } paned.Remove(child) if is_child1 { paned.Pack1(child, resize, shrink) } else { paned.Pack2(child, resize, shrink) } } func create_pane_options(paned *gtk.Paned, frame_label, label1, label2 string) *gtk.Widget { child1 := paned.GetChild1() child2 := paned.GetChild2() frame := gtk.NewFrame(frame_label) frame.SetBorderWidth(4) table := gtk.NewGrid() frame.Add(table) label := gtk.NewLabel(label1) table.Attach(label, 0, 0, 1, 1) check_button := gtk.NewCheckButtonWithMnemonic("_Resize") table.Attach(check_button, 0, 1, 1, 1) check_button.Connect("toggled", func() { toggle(child1, false, true) }) check_button = gtk.NewCheckButtonWithMnemonic("_Shrink") table.Attach(check_button, 0, 2, 1, 1) check_button.SetActive(true) check_button.Connect("toggled", func() { toggle(child1, true, false) }) label = gtk.NewLabel(label2) table.Attach(label, 1, 0, 1, 1) check_button = gtk.NewCheckButtonWithMnemonic("_Resize") table.Attach(check_button, 1, 1, 1, 1) check_button.SetActive(true) check_button.Connect("toggled", func() { toggle(child2, false, true) }) check_button = gtk.NewCheckButtonWithMnemonic("_Shrink") table.Attach(check_button, 1, 2, 1, 1) check_button.SetActive(true) check_button.Connect("toggled", func() { toggle(child2, true, false) }) return gtk.ToWidget(frame) } func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetScreen(mainwin.GetScreen()) window.Connect("destroy", func() { window = nil }) window.SetTitle("Panes") window.SetBorderWidth(0) vbox := gtk.NewBox(gtk.OrientationVertical, 0) window.Add(vbox) vpaned := gtk.NewPaned(gtk.OrientationVertical) vbox.PackStart(vpaned, true, true, 0) vpaned.SetBorderWidth(5) hpaned := gtk.NewPaned(gtk.OrientationHorizontal) vpaned.Add1(hpaned) frame := gtk.NewFrame(gobject.NilString) frame.SetShadowType(gtk.ShadowTypeIn) frame.SetSizeRequest(60, 60) hpaned.Add1(frame) button := gtk.NewButtonWithMnemonic("_Hi there") frame.Add(button) frame = gtk.NewFrame(gobject.NilString) frame.SetShadowType(gtk.ShadowTypeIn) frame.SetSizeRequest(80, 60) hpaned.Add2(frame) frame = gtk.NewFrame(gobject.NilString) frame.SetShadowType(gtk.ShadowTypeIn) frame.SetSizeRequest(60, 80) vpaned.Add2(frame) vbox.PackStart(create_pane_options(hpaned, "Horizontal", "Left", "Right"), false, false, 0) vbox.PackStart(create_pane_options(vpaned, "Vertical", "Top", "Bottom"), false, false, 0) vbox.ShowAll() } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window } go-gir-generator-master/gogtk-demo/pickers.go000066400000000000000000000030071414263242200215430ustar00rootroot00000000000000// Pickers // // These widgets are mainly intended for use in preference dialogs. // They allow to select colors, fonts, files, directories and applications. package pickers import "gobject/gtk-3.0" var window *gtk.Window func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetTitle("Pickers") window.Connect("destroy", func() { window = nil }) window.SetBorderWidth(10) table := gtk.NewGrid() table.SetRowSpacing(3) table.SetColumnSpacing(10) window.Add(table) table.SetBorderWidth(10) make_label := func(label string) *gtk.Label { l := gtk.NewLabel(label) l.SetHAlign(gtk.AlignStart) l.SetVAlign(gtk.AlignCenter) l.SetHExpand(true) return l } table.Attach(make_label("Color:"), 0, 0, 1, 1) table.Attach(gtk.NewColorButton(), 1, 0, 1, 1) table.Attach(make_label("Font:"), 0, 1, 1, 1) table.Attach(gtk.NewFontButton(), 1, 1, 1, 1) table.Attach(make_label("File:"), 0, 2, 1, 1) table.Attach(gtk.NewFileChooserButton("Pick a File", gtk.FileChooserActionOpen), 1, 2, 1, 1) table.Attach(make_label("Folder:"), 0, 3, 1, 1) table.Attach(gtk.NewFileChooserButton("Pick a Folder", gtk.FileChooserActionSelectFolder), 1, 3, 1, 1) mail_picker := gtk.NewAppChooserButton("x-scheme-handler/mailto") mail_picker.SetShowDialogItem(true) table.Attach(make_label("Mail:"), 0, 4, 1, 1) table.Attach(mail_picker, 1, 4, 1, 1) } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window } go-gir-generator-master/gogtk-demo/pixbufs.go000066400000000000000000000110641414263242200215650ustar00rootroot00000000000000// Pixbufs // // A GdkPixbuf represents an image, normally in RGB or RGBA format. // Pixbufs are normally used to load files from disk and perform // image scaling. // // This demo is not all that educational, but looks cool. It was written // by Extreme Pixbuf Hacker Federico Mena Quintero. It also shows // off how to use GtkDrawingArea to do a simple animation. // // Look at the Image demo for additional pixbuf usage examples. package pixbufs import "gobject/gtk-3.0" import "gobject/gdk-3.0" import "gobject/gdkpixbuf-2.0" import "gobject/cairo-1.0" import "math" import "time" import "sync" import "./gogtk-demo/common" const frame_delay = 50 const background_name = "background.jpg" var image_names = []string{ "apple-red.png", "gnome-applets.png", "gnome-calendar.png", "gnome-foot.png", "gnome-gmush.png", "gnome-gimp.png", "gnome-gsame.png", "gnu-keys.png", } var window *gtk.Window var background *gdkpixbuf.Pixbuf var images []*gdkpixbuf.Pixbuf var back_width int var back_height int var frame_lock sync.Mutex var frame *gdkpixbuf.Pixbuf var da *gtk.DrawingArea func load_pixbufs() error { if background != nil { return nil // already loaded earlier } var err error background, err = gdkpixbuf.NewPixbufFromFile(common.FindFile(background_name)) if err != nil { return err } back_width = background.GetWidth() back_height = background.GetHeight() images = make([]*gdkpixbuf.Pixbuf, len(image_names)) for i, name := range image_names { images[i], err = gdkpixbuf.NewPixbufFromFile(common.FindFile(name)) if err != nil { return err } } return nil } // Expose callback for the drawing area func draw_cb(widget *gtk.Widget, cr *cairo.Context) bool { frame_lock.Lock() gdk.CairoSetSourcePixbuf(cr, frame, 0, 0) cr.Paint() frame_lock.Unlock() // unref explicitly, can't rely on GC here, leaks like crazy cr.Unref() return true } const cycle_len = 60 var frame_num int func draw_one_frame() { background.CopyArea(0, 0, back_width, back_height, frame, 0, 0) f := float64(frame_num % cycle_len) / cycle_len xmid := float64(back_width) / 2 ymid := float64(back_height) / 2 radius := math.Min(xmid, ymid) / 2 for i, image := range images { ang := 2 * math.Pi * float64(i) / float64(len(images)) - f * 2 * math.Pi iw := image.GetWidth() ih := image.GetHeight() r := radius + (radius / 3) * math.Sin(f * 2 * math.Pi) xpos := math.Floor(xmid + r * math.Cos(ang) - float64(iw) / 2 + 0.5) ypos := math.Floor(ymid + r * math.Sin(ang) - float64(ih) / 2 + 0.5) var k, alpha float64 if i & 1 != 0 { k = math.Sin(f * 2 * math.Pi) alpha = math.Max(127, math.Abs(255 * math.Sin(f * 2 * math.Pi))) } else { k = math.Cos(f * 2 * math.Pi) alpha = math.Max(127, math.Abs(255 * math.Cos(f * 2 * math.Pi))) } k = 2 * k * k k = math.Max(0.25, k) r1 := cairo.RectangleInt{ int32(xpos), int32(ypos), int32(float64(iw) * k), int32(float64(ih) * k), } r2 := cairo.RectangleInt{ 0, 0, int32(back_width), int32(back_height), } if dest, ok := gdk.RectangleIntersect(&r1, &r2); ok { frame_lock.Lock() image.Composite(frame, int(dest.X), int(dest.Y), int(dest.Width), int(dest.Height), xpos, ypos, k, k, gdkpixbuf.InterpTypeNearest, int(alpha)) frame_lock.Unlock() } } } func drawing_loop(cancel chan int) { ticker := time.NewTicker(frame_delay * time.Millisecond) for { select { case <-ticker.C: draw_one_frame() gdk.ThreadsEnter() da.QueueDraw() gdk.ThreadsLeave() frame_num++ case <-cancel: ticker.Stop() cancel <- 1 return } } } func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { cancel := make(chan int) window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetScreen(mainwin.GetScreen()) window.SetTitle("Pixbufs") window.SetResizable(false) window.Connect("destroy", func() { window = nil frame = nil da = nil }) if err := load_pixbufs(); err != nil { dialog := gtk.NewMessageDialog(mainwin, gtk.DialogFlagsDestroyWithParent, gtk.MessageTypeError, gtk.ButtonsTypeClose, "Failed to load an image: %s", err) dialog.Connect("response", func() { dialog.Destroy() }) dialog.Show() goto done } window.SetSizeRequest(back_width, back_height) frame = gdkpixbuf.NewPixbuf(gdkpixbuf.ColorspaceRGB, false, 8, back_width, back_height) da = gtk.NewDrawingArea() da.Connect("draw", draw_cb) window.Add(da) go drawing_loop(cancel) window.Connect("destroy", func() { // stop drawing loop cancel <- 1 <-cancel }) } done: if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window }go-gir-generator-master/gogtk-demo/search_entry.go000066400000000000000000000147441414263242200226030ustar00rootroot00000000000000// Entry/Search Entry // // GtkEntry allows to display icons and progress information. // This demo shows how to use these features in a search entry. package search_entry import "gobject/gtk-3.0" import "gobject/gdk-3.0" import "gobject/gobject-2.0" import "time" var dialog *gtk.Dialog var notebook *gtk.Notebook var entry *gtk.Entry const ( find_button_page = iota cancel_button_page ) const ( start_search_cmd = iota cancel_search_cmd stop_daemon_cmd ) func start_search_daemon(msgqueue chan int) { go func() { var progress_ticker *time.Ticker var finish_ticker *time.Ticker var progress_tick <-chan time.Time var finish_tick <-chan time.Time start_search := func() { if progress_ticker != nil { println("search in progress, start command ignored") return } progress_ticker = time.NewTicker(100 * time.Millisecond) finish_ticker = time.NewTicker(10 * time.Second) progress_tick = progress_ticker.C finish_tick = finish_ticker.C gdk.ThreadsEnter() notebook.SetCurrentPage(cancel_button_page) gdk.ThreadsLeave() } stop_search := func() { if progress_ticker == nil { return } progress_ticker.Stop() finish_ticker.Stop() progress_ticker = nil progress_tick = nil finish_ticker = nil finish_tick = nil } reset_gui := func() { gdk.ThreadsEnter() entry.SetProgressFraction(0) notebook.SetCurrentPage(find_button_page) gdk.ThreadsLeave() } done: for { select { case cmd := <-msgqueue: switch cmd { case start_search_cmd: start_search() case cancel_search_cmd: stop_search() reset_gui() case stop_daemon_cmd: stop_search() break done } case <-progress_tick: gdk.ThreadsEnter() entry.ProgressPulse() gdk.ThreadsLeave() case <-finish_tick: stop_search() reset_gui() } } msgqueue <- stop_daemon_cmd }() } func search_by_name() { entry.SetIconFromStock(gtk.EntryIconPositionPrimary, gtk.StockFind) entry.SetIconTooltipText(gtk.EntryIconPositionPrimary, "Search by name\n" + "Click here to change the search type") entry.SetPlaceholderText("name") } func search_by_description() { entry.SetIconFromStock(gtk.EntryIconPositionPrimary, gtk.StockEdit) entry.SetIconTooltipText(gtk.EntryIconPositionPrimary, "Search by description\n" + "Click here to change the search type") entry.SetPlaceholderText("description") } func search_by_file() { entry.SetIconFromStock(gtk.EntryIconPositionPrimary, gtk.StockOpen) entry.SetIconTooltipText(gtk.EntryIconPositionPrimary, "Search by file name\n" + "Click here to change the search type") entry.SetPlaceholderText("file name") } func create_search_menu() *gtk.Menu { menu := gtk.NewMenu() item := gtk.NewImageMenuItemWithMnemonic("Search by _name") image := gtk.NewImageFromStock(gtk.StockFind, int(gtk.IconSizeMenu)) item.SetImage(image) item.SetAlwaysShowImage(true) item.Connect("activate", search_by_name) menu.Append(item) item = gtk.NewImageMenuItemWithMnemonic("Search by _description") image = gtk.NewImageFromStock(gtk.StockEdit, int(gtk.IconSizeMenu)) item.SetImage(image) item.SetAlwaysShowImage(true) item.Connect("activate", search_by_description) menu.Append(item) item = gtk.NewImageMenuItemWithMnemonic("Search by _file name") image = gtk.NewImageFromStock(gtk.StockOpen, int(gtk.IconSizeMenu)) item.SetImage(image) item.SetAlwaysShowImage(true) item.Connect("activate", search_by_file) menu.Append(item) menu.ShowAll() return menu } func entry_populate_popup(entry *gtk.Entry, menu *gtk.Menu) { has_text := entry.GetTextLength() > 0 item := gtk.ToMenuItem(gtk.NewSeparatorMenuItem()) item.Show() menu.Append(item) item = gtk.NewMenuItemWithMnemonic("C_lear") item.Show() item.Connect("activate", func() { entry.SetText("") }) menu.Append(item) item.SetSensitive(has_text) search_menu := create_search_menu() item = gtk.NewMenuItemWithLabel("Search by") item.Show() item.SetSubmenu(search_menu) menu.Append(item) } func Do(mainwin *gtk.Window) *gtk.Window { if dialog == nil { msgqueue := make(chan int) start_search_daemon(msgqueue) dialog = gtk.NewDialogWithButtons("Search Entry", mainwin, 0, gtk.StockClose, gtk.ResponseTypeNone) dialog.SetResizable(false) dialog.Connect("response", func() { dialog.Destroy() }) dialog.Connect("destroy", func() { msgqueue <- stop_daemon_cmd <-msgqueue dialog = nil notebook = nil entry = nil }) content_area := gtk.ToBox(dialog.GetContentArea()) vbox := gtk.NewBox(gtk.OrientationVertical, 5) content_area.PackStart(vbox, true, true, 0) vbox.SetBorderWidth(5) label := gtk.NewLabel(gobject.NilString) label.SetMarkup("Search entry demo") vbox.PackStart(label, false, false, 0) hbox := gtk.NewBox(gtk.OrientationHorizontal, 10) vbox.PackStart(hbox, true, true, 0) hbox.SetBorderWidth(0) // Create our entry entry = gtk.NewEntry() hbox.PackStart(entry, false, false, 0) // Create the find and cancel buttons notebook = gtk.NewNotebook() notebook.SetShowTabs(false) notebook.SetShowBorder(false) hbox.PackStart(notebook, false, false, 0) find_button := gtk.NewButtonWithLabel("Find") find_button.Connect("clicked", func() { msgqueue <- start_search_cmd }) notebook.AppendPage(find_button, nil) find_button.Show() cancel_button := gtk.NewButtonWithLabel("Cancel") cancel_button.Connect("clicked", func() { msgqueue <- cancel_search_cmd }) notebook.AppendPage(cancel_button, nil) cancel_button.Show() // Set up the search icon search_by_name() // Set up the clear icon entry.SetIconFromStock(gtk.EntryIconPositionSecondary, gtk.StockClear) entry.SetIconSensitive(gtk.EntryIconPositionSecondary, false) find_button.SetSensitive(false) // Create the menu menu := create_search_menu() menu.AttachToWidget(entry) entry.Connect("icon-press", func(e *gtk.Entry, pos gtk.EntryIconPosition, ev *gdk.EventButton) { if pos == gtk.EntryIconPositionPrimary { menu.Popup(nil, nil, nil, int(ev.Button), int(ev.Time)) } else { e.SetText("") } }) entry.Connect("notify::text", func() { has_text := entry.GetTextLength() > 0 entry.SetIconSensitive(gtk.EntryIconPositionSecondary, has_text) find_button.SetSensitive(has_text) }) entry.Connect("activate", func() { msgqueue <- start_search_cmd }) entry.Connect("populate-popup", entry_populate_popup) button := dialog.GetWidgetForResponse(int(gtk.ResponseTypeNone)) button.GrabFocus() } if !dialog.GetVisible() { dialog.ShowAll() } else { dialog.Destroy() } return gtk.ToWindow(dialog) }go-gir-generator-master/gogtk-demo/size_groups.go000066400000000000000000000070341414263242200224600ustar00rootroot00000000000000// Size Groups // // GtkSizeGroup provides a mechanism for grouping a number of // widgets together so they all request the same amount of space. // This is typically useful when you want a column of widgets to // have the same size, but you can't use a GtkTable widget. // // Note that size groups only affect the amount of space requested, // not the size that the widgets finally receive. If you want the // widgets in a GtkSizeGroup to actually be the same size, you need // to pack them in such a way that they get the size they request // and not more. For example, if you are packing your widgets // into a table, you would not include the GTK_FILL flag. package size_groups import "gobject/gtk-3.0" var dialog *gtk.Dialog // Convenience function to create a combo box holding a number of strings func create_combo_box(strings []string) *gtk.ComboBoxText { combo_box := gtk.NewComboBoxText() for _, s := range strings { combo_box.AppendText(s) } combo_box.SetActive(0) return combo_box } func add_row(table *gtk.Grid, row int, size_group *gtk.SizeGroup, label_text string, options []string) { label := gtk.NewLabelWithMnemonic(label_text) label.SetHAlign(gtk.AlignStart) label.SetVAlign(gtk.AlignEnd) label.SetHExpand(true) table.Attach(label, 0, row, 1, 1) combo_box := create_combo_box(options) label.SetMnemonicWidget(combo_box) size_group.AddWidget(combo_box) table.Attach(combo_box, 1, row, 1, 1) } var color_options = []string{ "Red", "Green", "Blue", } var dash_options = []string{ "Solid", "Dashed", "Dotted", } var end_options = []string{ "Square", "Round", "Arrow", } func Do(mainwin *gtk.Window) *gtk.Window { if dialog == nil { dialog = gtk.NewDialogWithButtons("GtkSizeGroup", mainwin, 0, gtk.StockClose, gtk.ResponseTypeNone) dialog.SetResizable(false) dialog.Connect("response", func() { dialog.Destroy() }) dialog.Connect("destroy", func() { dialog = nil }) content_area := gtk.ToBox(dialog.GetContentArea()) vbox := gtk.NewBox(gtk.OrientationVertical, 5) content_area.PackStart(vbox, true, true, 0) vbox.SetBorderWidth(5) size_group := gtk.NewSizeGroup(gtk.SizeGroupModeHorizontal) // Create one frame holding color options frame := gtk.NewFrame("Color Options") vbox.PackStart(frame, true, true, 0) table := gtk.NewGrid() table.SetBorderWidth(5) table.SetRowSpacing(5) table.SetColumnSpacing(10) frame.Add(table) add_row(table, 0, size_group, "_Foreground", color_options) add_row(table, 1, size_group, "_Background", color_options) // And another frame holding line style options frame = gtk.NewFrame("Line Options") vbox.PackStart(frame, false, false, 0) table = gtk.NewGrid() table.SetBorderWidth(5) table.SetRowSpacing(5) table.SetColumnSpacing(10) frame.Add(table) add_row(table, 0, size_group, "_Dashing", dash_options) add_row(table, 1, size_group, "_Line ends", end_options) // And a check button to turn grouping on and off check_button := gtk.NewCheckButtonWithMnemonic("_Enable grouping") vbox.PackStart(check_button, false, false, 0) check_button.SetActive(true) check_button.Connect("toggled", func() { var new_mode gtk.SizeGroupMode // GTK_SIZE_GROUP_NONE is not generally useful, but is useful // here to show the effect of GTK_SIZE_GROUP_HORIZONTAL by // contrast. if check_button.GetActive() { new_mode = gtk.SizeGroupModeHorizontal } else { new_mode = gtk.SizeGroupModeNone } size_group.SetMode(new_mode) }) } if !dialog.GetVisible() { dialog.ShowAll() } else { dialog.Destroy() } return gtk.ToWindow(dialog) } go-gir-generator-master/gogtk-demo/spinner.go000066400000000000000000000030341414263242200215610ustar00rootroot00000000000000// Spinner // // GtkSpinner allows to show that background activity is on-going. package spinner import "gobject/gtk-3.0" var dialog *gtk.Dialog func Do(mainwin *gtk.Window) *gtk.Window { if dialog == nil { dialog = gtk.NewDialogWithButtons("GtkSpinner", mainwin, 0, gtk.StockClose, gtk.ResponseTypeNone) dialog.SetResizable(false) dialog.Connect("response", func() { dialog.Destroy() }) dialog.Connect("destroy", func() { dialog = nil }) content_area := gtk.ToBox(dialog.GetContentArea()) vbox := gtk.NewBox(gtk.OrientationVertical, 5) content_area.PackStart(vbox, true, true, 0) vbox.SetBorderWidth(5) var hbox *gtk.Box // Sensitive hbox = gtk.NewBox(gtk.OrientationHorizontal, 5) spinner_sensitive := gtk.NewSpinner() hbox.Add(spinner_sensitive) hbox.Add(gtk.NewEntry()) vbox.Add(hbox) // Disabled hbox = gtk.NewBox(gtk.OrientationHorizontal, 5) spinner_unsensitive := gtk.NewSpinner() hbox.Add(spinner_unsensitive) hbox.Add(gtk.NewEntry()) vbox.Add(hbox) hbox.SetSensitive(false) button := gtk.NewButtonFromStock(gtk.StockMediaPlay) button.Connect("clicked", func() { spinner_sensitive.Start() spinner_unsensitive.Start() }) vbox.Add(button) button = gtk.NewButtonFromStock(gtk.StockMediaStop) button.Connect("clicked", func() { spinner_sensitive.Stop() spinner_unsensitive.Stop() }) vbox.Add(button) spinner_sensitive.Start() spinner_unsensitive.Start() } if !dialog.GetVisible() { dialog.ShowAll() } else { dialog.Destroy() } return gtk.ToWindow(dialog) } go-gir-generator-master/gogtk-demo/stock_browser.go000066400000000000000000000172271414263242200230020ustar00rootroot00000000000000// Stock Item and Icon Browser // // This source code for this demo doesn't demonstrate anything // particularly useful in applications. The purpose of the "demo" is // just to provide a handy place to browse the available stock icons // and stock items. package stock_browser import "gobject/gtk-3.0" import "gobject/gobject-2.0" import "gobject/gdkpixbuf-2.0" import "fmt" import "sort" import "bytes" import "strings" var window *gtk.Window type stock_item_info struct { id string item gtk.StockItem small_icon *gdkpixbuf.Pixbuf constant string accel_str string } type stock_item_display struct { type_label *gtk.Label constant_label *gtk.Label id_label *gtk.Label label_accel_label *gtk.Label icon_image *gtk.Image } func id_to_constant(id string) string { var out bytes.Buffer if strings.HasPrefix(id, "gtk-") { out.WriteString("gtk.Stock") id = id[4:] } for _, word := range strings.Split(id, "-") { word = strings.ToLower(word) if len(word) == 1 { out.WriteString(strings.ToUpper(word)) } else { out.WriteString(strings.ToUpper(word[:1])) out.WriteString(word[1:]) } } return out.String() } func create_model() *gtk.TreeModel { store := gtk.NewListStore(gobject.GoInterface, gobject.String) ids := gtk.StockListIDs() sort.Strings(ids) for _, id := range ids { var info stock_item_info info.id = id if item, ok := gtk.StockLookup(id); ok { info.item = item } else { info.item.Label = gobject.NilString info.item.StockID = gobject.NilString info.item.Modifier = 0 info.item.Keyval = 0 info.item.TranslationDomain = gobject.NilString } // only show icons for stock IDs that have default icons icon_set := gtk.IconFactoryLookupDefault(info.id) if icon_set != nil { // See what sizes this stock icon really exists at sizes := icon_set.GetSizes() // Use menu size if it exists, otherwise first size found size := sizes[0] for _, s := range sizes { if gtk.IconSize(s) == gtk.IconSizeMenu { size = int(gtk.IconSizeMenu) break } } info.small_icon = window.RenderIconPixbuf(info.id, size) if gtk.IconSize(size) != gtk.IconSizeMenu { // Make the result the proper size for our thumbnail w, h, _ := gtk.IconSizeLookup(int(gtk.IconSizeMenu)) scaled := info.small_icon.ScaleSimple(w, h, gdkpixbuf.InterpTypeBilinear) info.small_icon = scaled } } else { info.small_icon = nil } if info.item.Keyval != 0 { info.accel_str = gtk.AcceleratorName( int(info.item.Keyval), info.item.Modifier) } else { info.accel_str = "" } info.constant = id_to_constant(info.id) store.Append(&info, info.id) } return gtk.ToTreeModel(store) } // Finds the largest size at which the given image stock id is // available. This would not be useful for a normal application func get_largest_size(id string) int { set := gtk.IconFactoryLookupDefault(id) sizes := set.GetSizes() best_size := int(gtk.IconSizeInvalid) best_pixels := 0 for _, size := range sizes { w, h, _ := gtk.IconSizeLookup(size) if w*h > best_pixels { best_size = size best_pixels = w * h } } return best_size } func selection_changed(selection *gtk.TreeSelection, display *stock_item_display) { if model, iter, ok := selection.GetSelected(); ok { var infoi interface{} model.Get(&iter, 0, &infoi) info := infoi.(*stock_item_info) switch { case info.small_icon != nil && info.item.Label != gobject.NilString: display.type_label.SetText("Icon and Item") case info.small_icon != nil: display.type_label.SetText("Icon Only") case info.item.Label != gobject.NilString: display.type_label.SetText("Item Only") default: display.type_label.SetText("???????") } display.constant_label.SetText(info.constant) display.id_label.SetText(info.id) if info.item.Label != gobject.NilString { str := fmt.Sprintf("%s %s", info.item.Label, info.accel_str) display.label_accel_label.SetTextWithMnemonic(str) } else { display.label_accel_label.SetText("") } if info.small_icon != nil { display.icon_image.SetFromStock(info.id, get_largest_size(info.id)) } else { display.icon_image.Clear() } } else { display.type_label.SetText("No selected item") display.constant_label.SetText("") display.id_label.SetText("") display.label_accel_label.SetText("") display.icon_image.Clear() } } func constant_set_func_text(tree_column *gtk.TreeViewColumn, cell *gtk.CellRenderer, model *gtk.TreeModel, iter *gtk.TreeIter) { var infoi interface{} model.Get(iter, 0, &infoi) info := infoi.(*stock_item_info) cell.SetProperty("text", info.constant) } func id_set_func(tree_column *gtk.TreeViewColumn, cell *gtk.CellRenderer, model *gtk.TreeModel, iter *gtk.TreeIter) { var infoi interface{} model.Get(iter, 0, &infoi) info := infoi.(*stock_item_info) cell.SetProperty("text", info.id) } func accel_set_func(tree_column *gtk.TreeViewColumn, cell *gtk.CellRenderer, model *gtk.TreeModel, iter *gtk.TreeIter) { var infoi interface{} model.Get(iter, 0, &infoi) info := infoi.(*stock_item_info) cell.SetProperty("text", info.accel_str) } func label_set_func(tree_column *gtk.TreeViewColumn, cell *gtk.CellRenderer, model *gtk.TreeModel, iter *gtk.TreeIter) { var infoi interface{} model.Get(iter, 0, &infoi) info := infoi.(*stock_item_info) cell.SetProperty("text", info.item.Label) } func Do(mainwin *gtk.Window) *gtk.Window { if window == nil { window = gtk.NewWindow(gtk.WindowTypeToplevel) window.SetScreen(mainwin.GetScreen()) window.SetTitle("Stock Icons and Items") window.SetDefaultSize(-1, 500) window.Connect("destroy", func() { window = nil }) window.SetBorderWidth(8) hbox := gtk.NewBox(gtk.OrientationHorizontal, 8) window.Add(hbox) sw := gtk.NewScrolledWindow(nil, nil) sw.SetPolicy(gtk.PolicyTypeNever, gtk.PolicyTypeAutomatic) hbox.PackStart(sw, false, false, 0) model := create_model() treeview := gtk.NewTreeViewWithModel(model) sw.Add(treeview) var r *gtk.CellRenderer c := gtk.NewTreeViewColumn() c.SetTitle("Constant") r = gtk.ToCellRenderer(gtk.NewCellRendererPixbuf()) c.PackStart(r, false) c.SetAttributes(r, "stock-id", 1) r = gtk.ToCellRenderer(gtk.NewCellRendererText()) c.PackStart(r, true) c.SetCellDataFunc(r, constant_set_func_text) treeview.AppendColumn(c) r = gtk.ToCellRenderer(gtk.NewCellRendererText()) treeview.InsertColumnWithDataFunc(-1, "Label", r, label_set_func) r = gtk.ToCellRenderer(gtk.NewCellRendererText()) treeview.InsertColumnWithDataFunc(-1, "Accel", r, accel_set_func) r = gtk.ToCellRenderer(gtk.NewCellRendererText()) treeview.InsertColumnWithDataFunc(-1, "ID", r, id_set_func) frame := gtk.NewFrame("Selected Item") frame.SetVAlign(gtk.AlignStart) hbox.PackEnd(frame, false, false, 0) vbox := gtk.NewBox(gtk.OrientationVertical, 8) vbox.SetBorderWidth(4) frame.Add(vbox) display := &stock_item_display{ type_label: gtk.NewLabel(gobject.NilString), constant_label: gtk.NewLabel(gobject.NilString), id_label: gtk.NewLabel(gobject.NilString), label_accel_label: gtk.NewLabel(gobject.NilString), icon_image: gtk.NewImage(), // empty image } vbox.PackStart(display.type_label, false, false, 0) vbox.PackStart(display.icon_image, false, false, 0) vbox.PackStart(display.label_accel_label, false, false, 0) vbox.PackStart(display.constant_label, false, false, 0) vbox.PackStart(display.id_label, false, false, 0) selection := treeview.GetSelection() selection.SetMode(gtk.SelectionModeSingle) selection.Connect("changed", func(sel *gtk.TreeSelection) { selection_changed(sel, display) }) } if !window.GetVisible() { window.ShowAll() } else { window.Destroy() } return window } go-gir-generator-master/gogtk-demo/wscript000066400000000000000000000004661414263242200212000ustar00rootroot00000000000000# -*- python -*- def build(bld): for demoapp in bld.path.ant_glob('*.go', excl=['demos.go', 'main.go']): bld( features='go', source=demoapp, target=demoapp.name[:-3], ) bld( features='go goprogram', source='main.go demos.go', target='gogtk-demo', install_path=None, # don't install ) go-gir-generator-master/lib.in/000077500000000000000000000000001414263242200166725ustar00rootroot00000000000000go-gir-generator-master/lib.in/atk-1.0/000077500000000000000000000000001414263242200177455ustar00rootroot00000000000000go-gir-generator-master/lib.in/atk-1.0/atk.go.in000066400000000000000000000002751414263242200214640ustar00rootroot00000000000000package atk /* #include "atk.gen.h" [<.g_object_ref_unref>] [<.g_error_free>] [<.g_free>] */ import "C" import "unsafe" import ( "gobject/gobject-2.0" ) [<.go_utils>] [<.go_bindings>]go-gir-generator-master/lib.in/atk-1.0/config.json000066400000000000000000000007701414263242200221110ustar00rootroot00000000000000{ "namespace": "Atk", "version": "1.0", "blacklist": { "functions": [ "attribute_set_free", "text_free_ranges" ], "structs": [ "_RegistryClass", "_Registry" ] }, "method-blacklist": { "Document": [ "get_attributes" ], "Object": [ "get_attributes" ], "StateSet": [ "add_states", "contains_states" ], "StreamableContent": [ "get_stream" ], "Text": [ "get_default_attributes", "get_run_attributes" ], "Relation": [ "get_target" ] } }go-gir-generator-master/lib.in/cairo-1.0/000077500000000000000000000000001414263242200202635ustar00rootroot00000000000000go-gir-generator-master/lib.in/cairo-1.0/cairo.c000066400000000000000000000012031414263242200215200ustar00rootroot00000000000000#include "_cgo_export.h" cairo_surface_t * _cairo_image_surface_create_from_png_stream(void *closure) { return cairo_image_surface_create_from_png_stream(io_reader_wrapper, closure); } cairo_status_t _cairo_surface_write_to_png_stream(cairo_surface_t *surface, void *closure) { return cairo_surface_write_to_png_stream(surface, (cairo_write_func_t)io_writer_wrapper, closure); } cairo_surface_t *_cairo_pdf_surface_create_for_stream(void *closure, double width_in_points, double height_in_points) { return cairo_pdf_surface_create_for_stream((cairo_write_func_t)io_writer_wrapper, closure, width_in_points, height_in_points); } go-gir-generator-master/lib.in/cairo-1.0/cairo.go000066400000000000000000003341161414263242200217170ustar00rootroot00000000000000// Full cairo bindings. Made in a stupid fashion (i.e. no sugar). But bits of // memory management are here (GC finalizer hooks). package cairo /* #include #include #include #include extern cairo_surface_t * _cairo_image_surface_create_from_png_stream(void *closure); extern cairo_status_t _cairo_surface_write_to_png_stream(cairo_surface_t *surface, void *closure); extern cairo_surface_t *_cairo_pdf_surface_create_for_stream(void *closure, double width_in_points, double height_in_points); #cgo pkg-config: cairo-gobject cairo-png */ import "C" import "runtime" import "strings" import "reflect" import "unsafe" import "io" import ( "gobject/gobject-2.0" ) //---------------------------------------------------------------------------- // GObject types //---------------------------------------------------------------------------- // structs // cairo_gobject_context_get_type (void); func (*Context) GetStaticType() gobject.Type { return gobject.Type(C.cairo_gobject_context_get_type()) } func ContextGetType() gobject.Type { return (*Context)(nil).GetStaticType() } // cairo_gobject_device_get_type (void); // cairo_gobject_pattern_get_type (void); func (*Pattern) GetStaticType() gobject.Type { return gobject.Type(C.cairo_gobject_pattern_get_type()) } func PatternGetType() gobject.Type { return (*Pattern)(nil).GetStaticType() } // cairo_gobject_surface_get_type (void); func (*Surface) GetStaticType() gobject.Type { return gobject.Type(C.cairo_gobject_surface_get_type()) } func SurfaceGetType() gobject.Type { return (*Surface)(nil).GetStaticType() } // cairo_gobject_rectangle_get_type (void); // cairo_gobject_scaled_font_get_type (void); func (*ScaledFont) GetStaticType() gobject.Type { return gobject.Type(C.cairo_gobject_scaled_font_get_type()) } func ScaledFontGetType() gobject.Type { return (*ScaledFont)(nil).GetStaticType() } // cairo_gobject_font_face_get_type (void); func (*FontFace) GetStaticType() gobject.Type { return gobject.Type(C.cairo_gobject_font_face_get_type()) } func FontFaceGetType() gobject.Type { return (*FontFace)(nil).GetStaticType() } // cairo_gobject_font_options_get_type (void); func (*FontOptions) GetStaticType() gobject.Type { return gobject.Type(C.cairo_gobject_font_options_get_type()) } func FontOptionsGetType() gobject.Type { return (*FontOptions)(nil).GetStaticType() } // cairo_gobject_rectangle_int_get_type (void); // cairo_gobject_region_get_type (void); func (*Region) GetStaticType() gobject.Type { return gobject.Type(C.cairo_gobject_region_get_type()) } func RegionGetType() gobject.Type { return (*Region)(nil).GetStaticType() } // TODO: No need for these? // enums // cairo_gobject_status_get_type (void); // cairo_gobject_content_get_type (void); // cairo_gobject_operator_get_type (void); // cairo_gobject_antialias_get_type (void); // cairo_gobject_fill_rule_get_type (void); // cairo_gobject_line_cap_get_type (void); // cairo_gobject_line_join_get_type (void); // cairo_gobject_text_cluster_flags_get_type (void); // cairo_gobject_font_slant_get_type (void); // cairo_gobject_font_weight_get_type (void); // cairo_gobject_subpixel_order_get_type (void); // cairo_gobject_hint_style_get_type (void); // cairo_gobject_hint_metrics_get_type (void); // cairo_gobject_font_type_get_type (void); // cairo_gobject_path_data_type_get_type (void); // cairo_gobject_device_type_get_type (void); // cairo_gobject_surface_type_get_type (void); // cairo_gobject_format_get_type (void); // cairo_gobject_pattern_type_get_type (void); // cairo_gobject_extend_get_type (void); // cairo_gobject_filter_get_type (void); // cairo_gobject_region_overlap_get_type (void); //---------------------------------------------------------------------------- // TODO MOVE //---------------------------------------------------------------------------- // Cairo C to Go reflect.Value converter (for closure marshaling) func cairo_marshaler(value *gobject.Value, t reflect.Type) (reflect.Value, bool) { if !strings.HasSuffix(t.Elem().PkgPath(), "cairo-1.0") { return reflect.Value{}, false } out := reflect.New(t) st, ok := out.Elem().Interface().(gobject.StaticTyper) if !ok { return reflect.Value{}, false } gtypedst := st.GetStaticType() var dst gobject.Value dst.Init(gtypedst) ok = dst.Transform(value) if !ok { panic("GValue is not transformable to " + t.String()) } defer dst.Unset() // TODO: is it correct that I should always grab here? switch gtypedst { case ContextGetType(): *(*unsafe.Pointer)(unsafe.Pointer(out.Pointer())) = ContextWrap(dst.GetBoxed(), true) case PatternGetType(): *(*unsafe.Pointer)(unsafe.Pointer(out.Pointer())) = PatternWrap(dst.GetBoxed(), true) case SurfaceGetType(): *(*unsafe.Pointer)(unsafe.Pointer(out.Pointer())) = SurfaceWrap(dst.GetBoxed(), true) case FontOptionsGetType(): *(*unsafe.Pointer)(unsafe.Pointer(out.Pointer())) = FontOptionsWrap(dst.GetBoxed()) case RegionGetType(): *(*unsafe.Pointer)(unsafe.Pointer(out.Pointer())) = RegionWrap(dst.GetBoxed(), true) case FontFaceGetType(): *(*unsafe.Pointer)(unsafe.Pointer(out.Pointer())) = FontFaceWrap(dst.GetBoxed(), true) case ScaledFontGetType(): *(*unsafe.Pointer)(unsafe.Pointer(out.Pointer())) = ScaledFontWrap(dst.GetBoxed(), true) default: return reflect.Value{}, false } return out.Elem(), true } func init() { gobject.CairoMarshaler = cairo_marshaler } var go_repr_cookie C.cairo_user_data_key_t type RectangleInt struct { X int32 Y int32 Width int32 Height int32 } func (this *RectangleInt) c() *C.cairo_rectangle_int_t { return (*C.cairo_rectangle_int_t)(unsafe.Pointer(this)) } //---------------------------------------------------------------------------- // Error Handling //---------------------------------------------------------------------------- type Status int const ( StatusSuccess Status = C.CAIRO_STATUS_SUCCESS StatusNoMemory Status = C.CAIRO_STATUS_NO_MEMORY StatusInvalidRestore Status = C.CAIRO_STATUS_INVALID_RESTORE StatusInvalidPopGroup Status = C.CAIRO_STATUS_INVALID_POP_GROUP StatusNoCurrentPoint Status = C.CAIRO_STATUS_NO_CURRENT_POINT StatusInvalidMatrix Status = C.CAIRO_STATUS_INVALID_MATRIX StatusInvalidStatus Status = C.CAIRO_STATUS_INVALID_STATUS StatusNullPointer Status = C.CAIRO_STATUS_NULL_POINTER StatusInvalidString Status = C.CAIRO_STATUS_INVALID_STRING StatusInvalidPathData Status = C.CAIRO_STATUS_INVALID_PATH_DATA StatusReadError Status = C.CAIRO_STATUS_READ_ERROR StatusWriteError Status = C.CAIRO_STATUS_WRITE_ERROR StatusSurfaceFinished Status = C.CAIRO_STATUS_SURFACE_FINISHED StatusSurfaceTypeMismatch Status = C.CAIRO_STATUS_SURFACE_TYPE_MISMATCH StatusPatternTypeMismatch Status = C.CAIRO_STATUS_PATTERN_TYPE_MISMATCH StatusInvalidContent Status = C.CAIRO_STATUS_INVALID_CONTENT StatusInvalidFormat Status = C.CAIRO_STATUS_INVALID_FORMAT StatusInvalidVisual Status = C.CAIRO_STATUS_INVALID_VISUAL StatusFileNotFound Status = C.CAIRO_STATUS_FILE_NOT_FOUND StatusInvalidDash Status = C.CAIRO_STATUS_INVALID_DASH StatusInvalidDscComment Status = C.CAIRO_STATUS_INVALID_DSC_COMMENT StatusInvalidIndex Status = C.CAIRO_STATUS_INVALID_INDEX StatusClipNotRepresentable Status = C.CAIRO_STATUS_CLIP_NOT_REPRESENTABLE StatusTempFileError Status = C.CAIRO_STATUS_TEMP_FILE_ERROR StatusInvalidStride Status = C.CAIRO_STATUS_INVALID_STRIDE StatusFontTypeMismatch Status = C.CAIRO_STATUS_FONT_TYPE_MISMATCH StatusUserFontImmutable Status = C.CAIRO_STATUS_USER_FONT_IMMUTABLE StatusUserFontError Status = C.CAIRO_STATUS_USER_FONT_ERROR StatusNegativeCount Status = C.CAIRO_STATUS_NEGATIVE_COUNT StatusInvalidClusters Status = C.CAIRO_STATUS_INVALID_CLUSTERS StatusInvalidSlant Status = C.CAIRO_STATUS_INVALID_SLANT StatusInvalidWeight Status = C.CAIRO_STATUS_INVALID_WEIGHT StatusInvalidSize Status = C.CAIRO_STATUS_INVALID_SIZE StatusUserFontNotImplemented Status = C.CAIRO_STATUS_USER_FONT_NOT_IMPLEMENTED StatusDeviceTypeMismatch Status = C.CAIRO_STATUS_DEVICE_TYPE_MISMATCH StatusDeviceError Status = C.CAIRO_STATUS_DEVICE_ERROR StatusLastStatus Status = C.CAIRO_STATUS_LAST_STATUS ) func (this Status) c() C.cairo_status_t { return C.cairo_status_t(this) } func (this Status) String() string { cstr := C.cairo_status_to_string(this.c()) return C.GoString(cstr) } //---------------------------------------------------------------------------- // Drawing Context //---------------------------------------------------------------------------- // typedef cairo_t; type Context struct { C unsafe.Pointer } func (this *Context) c() *C.cairo_t { return (*C.cairo_t)(this.C) } func context_finalizer(this *Context) { if gobject.FQueue.Push(unsafe.Pointer(this), context_finalizer2) { return } C.cairo_set_user_data(this.c(), &go_repr_cookie, nil, nil) C.cairo_destroy(this.c()) } func context_finalizer2(this_un unsafe.Pointer) { this := (*Context)(this_un) C.cairo_set_user_data(this.c(), &go_repr_cookie, nil, nil) C.cairo_destroy(this.c()) } func ContextWrap(c_un unsafe.Pointer, grab bool) unsafe.Pointer { if c_un == nil { return nil } c := (*C.cairo_t)(c_un) go_repr := C.cairo_get_user_data(c, &go_repr_cookie) if go_repr != nil { return unsafe.Pointer(go_repr) } context := &Context{unsafe.Pointer(c)} if grab { C.cairo_reference(c) } runtime.SetFinalizer(context, context_finalizer) status := C.cairo_set_user_data(c, &go_repr_cookie, unsafe.Pointer(context), nil) if status != C.CAIRO_STATUS_SUCCESS { panic("failed to set user data, out of memory?") } return unsafe.Pointer(context) } // cairo_t * cairo_create (cairo_surface_t *target); func NewContext(target SurfaceLike) *Context { return (*Context)(ContextWrap(unsafe.Pointer(C.cairo_create(target.InheritedFromCairoSurface().c())), false)) } // cairo_t * cairo_reference (cairo_t *cr); // void cairo_destroy (cairo_t *cr); func (this *Context) Unref() { runtime.SetFinalizer(this, nil) C.cairo_set_user_data(this.c(), &go_repr_cookie, nil, nil) C.cairo_destroy(this.c()) this.C = nil } // cairo_status_t cairo_status (cairo_t *cr); func (this *Context) Status() Status { return Status(C.cairo_status(this.c())) } // void cairo_save (cairo_t *cr); func (this *Context) Save() { C.cairo_save(this.c()) } // void cairo_restore (cairo_t *cr); func (this *Context) Restore() { C.cairo_restore(this.c()) } // cairo_surface_t * cairo_get_target (cairo_t *cr); func (this *Context) GetTarget() *Surface { return (*Surface)(SurfaceWrap(unsafe.Pointer(C.cairo_get_target(this.c())), true)) } // void cairo_push_group (cairo_t *cr); func (this *Context) PushGroup() { C.cairo_push_group(this.c()) } // void cairo_push_group_with_content (cairo_t *cr, // cairo_content_t content); func (this *Context) PushGroupWithContent(content Content) { C.cairo_push_group_with_content(this.c(), content.c()) } // cairo_pattern_t * cairo_pop_group (cairo_t *cr); func (this *Context) PopGroup() *Pattern { return (*Pattern)(PatternWrap(unsafe.Pointer(C.cairo_pop_group(this.c())), false)) } // void cairo_pop_group_to_source (cairo_t *cr); func (this *Context) PopGroupToSource() { C.cairo_pop_group_to_source(this.c()) } // cairo_surface_t * cairo_get_group_target (cairo_t *cr); func (this *Context) GetGroupTarget() *Surface { return (*Surface)(SurfaceWrap(unsafe.Pointer(C.cairo_get_group_target(this.c())), true)) } // void cairo_set_source_rgb (cairo_t *cr, // double red, // double green, // double blue); func (this *Context) SetSourceRGB(r, g, b float64) { C.cairo_set_source_rgb(this.c(), C.double(r), C.double(g), C.double(b)) } // void cairo_set_source_rgba (cairo_t *cr, // double red, // double green, // double blue, // double alpha); func (this *Context) SetSourceRGBA(r, g, b, a float64) { C.cairo_set_source_rgba(this.c(), C.double(r), C.double(g), C.double(b), C.double(a)) } // void cairo_set_source (cairo_t *cr, // cairo_pattern_t *source); func (this *Context) SetSource(source PatternLike) { C.cairo_set_source(this.c(), source.InheritedFromCairoPattern().c()) } // void cairo_set_source_surface (cairo_t *cr, // cairo_surface_t *surface, // double x, // double y); func (this *Context) SetSourceSurface(surface SurfaceLike, x, y float64) { C.cairo_set_source_surface(this.c(), surface.InheritedFromCairoSurface().c(), C.double(x), C.double(y)) } // cairo_pattern_t * cairo_get_source (cairo_t *cr); func (this *Context) GetSource() *Pattern { return (*Pattern)(PatternWrap(unsafe.Pointer(C.cairo_get_source(this.c())), true)) } // enum cairo_antialias_t; type Antialias int const ( AntialiasDefault Antialias = C.CAIRO_ANTIALIAS_DEFAULT AntialiasNone Antialias = C.CAIRO_ANTIALIAS_NONE AntialiasGray Antialias = C.CAIRO_ANTIALIAS_GRAY AntialiasSubpixel Antialias = C.CAIRO_ANTIALIAS_SUBPIXEL ) func (this Antialias) c() C.cairo_antialias_t { return C.cairo_antialias_t(this) } // void cairo_set_antialias (cairo_t *cr, // cairo_antialias_t antialias); func (this *Context) SetAntialias(antialias Antialias) { C.cairo_set_antialias(this.c(), antialias.c()) } // cairo_antialias_t cairo_get_antialias (cairo_t *cr); func (this *Context) GetAntialias() Antialias { return Antialias(C.cairo_get_antialias(this.c())) } // void cairo_set_dash (cairo_t *cr, // const double *dashes, // int num_dashes, // double offset); func (this *Context) SetDash(dashes []float64, offset float64) { var first *C.double if len(dashes) != 0 { first = (*C.double)(unsafe.Pointer(&dashes[0])) } C.cairo_set_dash(this.c(), first, C.int(len(dashes)), C.double(offset)) } // int cairo_get_dash_count (cairo_t *cr); func (this *Context) GetDashCount() int { return int(C.cairo_get_dash_count(this.c())) } // void cairo_get_dash (cairo_t *cr, // double *dashes, // double *offset); func (this *Context) GetDash() ([]float64, float64) { var first *C.double var offset C.double var dashes []float64 count := this.GetDashCount() if count != 0 { dashes = make([]float64, count) first = (*C.double)(unsafe.Pointer(&dashes[0])) } C.cairo_get_dash(this.c(), first, &offset) return dashes, float64(offset) } // enum cairo_fill_rule_t; type FillRule int const ( FillRuleWinding FillRule = C.CAIRO_FILL_RULE_WINDING FillRuleEvenOdd FillRule = C.CAIRO_FILL_RULE_EVEN_ODD ) func (this FillRule) c() C.cairo_fill_rule_t { return C.cairo_fill_rule_t(this) } // void cairo_set_fill_rule (cairo_t *cr, // cairo_fill_rule_t fill_rule); func (this *Context) SetFillRule(fill_rule FillRule) { C.cairo_set_fill_rule(this.c(), fill_rule.c()) } // cairo_fill_rule_t cairo_get_fill_rule (cairo_t *cr); func (this *Context) GetFillRule() FillRule { return FillRule(C.cairo_get_fill_rule(this.c())) } // enum cairo_line_cap_t; type LineCap int const ( LineCapButt LineCap = C.CAIRO_LINE_CAP_BUTT LineCapRound LineCap = C.CAIRO_LINE_CAP_ROUND LineCapSquare LineCap = C.CAIRO_LINE_CAP_SQUARE ) func (this LineCap) c() C.cairo_line_cap_t { return C.cairo_line_cap_t(this) } // void cairo_set_line_cap (cairo_t *cr, // cairo_line_cap_t line_cap); func (this *Context) SetLineCap(line_cap LineCap) { C.cairo_set_line_cap(this.c(), line_cap.c()) } // cairo_line_cap_t cairo_get_line_cap (cairo_t *cr); func (this *Context) GetLineCap() LineCap { return LineCap(C.cairo_get_line_cap(this.c())) } // enum cairo_line_join_t; type LineJoin int const ( LineJoinMiter LineJoin = C.CAIRO_LINE_JOIN_MITER LineJoinRound LineJoin = C.CAIRO_LINE_JOIN_ROUND LineJoinBevel LineJoin = C.CAIRO_LINE_JOIN_BEVEL ) func (this LineJoin) c() C.cairo_line_join_t { return C.cairo_line_join_t(this) } // void cairo_set_line_join (cairo_t *cr, // cairo_line_join_t line_join); func (this *Context) SetLineJoin(line_join LineJoin) { C.cairo_set_line_join(this.c(), line_join.c()) } // cairo_line_join_t cairo_get_line_join (cairo_t *cr); func (this *Context) GetLineJoin() LineJoin { return LineJoin(C.cairo_get_line_join(this.c())) } // void cairo_set_line_width (cairo_t *cr, // double width); func (this *Context) SetLineWidth(width float64) { C.cairo_set_line_width(this.c(), C.double(width)) } // double cairo_get_line_width (cairo_t *cr); func (this *Context) GetLineWidth() float64 { return float64(C.cairo_get_line_width(this.c())) } // void cairo_set_miter_limit (cairo_t *cr, // double limit); func (this *Context) SetMiterLimit(limit float64) { C.cairo_set_miter_limit(this.c(), C.double(limit)) } // double cairo_get_miter_limit (cairo_t *cr); func (this *Context) GetMiterLimit() float64 { return float64(C.cairo_get_miter_limit(this.c())) } // enum cairo_operator_t; type Operator int const ( OperatorClear Operator = C.CAIRO_OPERATOR_CLEAR OperatorSource Operator = C.CAIRO_OPERATOR_SOURCE OperatorOver Operator = C.CAIRO_OPERATOR_OVER OperatorIn Operator = C.CAIRO_OPERATOR_IN OperatorOut Operator = C.CAIRO_OPERATOR_OUT OperatorAtop Operator = C.CAIRO_OPERATOR_ATOP OperatorDest Operator = C.CAIRO_OPERATOR_DEST OperatorDestOver Operator = C.CAIRO_OPERATOR_DEST_OVER OperatorDestIn Operator = C.CAIRO_OPERATOR_DEST_IN OperatorDestOut Operator = C.CAIRO_OPERATOR_DEST_OUT OperatorDestAtop Operator = C.CAIRO_OPERATOR_DEST_ATOP OperatorXor Operator = C.CAIRO_OPERATOR_XOR OperatorAdd Operator = C.CAIRO_OPERATOR_ADD OperatorSaturate Operator = C.CAIRO_OPERATOR_SATURATE OperatorMultiply Operator = C.CAIRO_OPERATOR_MULTIPLY OperatorScreen Operator = C.CAIRO_OPERATOR_SCREEN OperatorOverlay Operator = C.CAIRO_OPERATOR_OVERLAY OperatorDarken Operator = C.CAIRO_OPERATOR_DARKEN OperatorLighten Operator = C.CAIRO_OPERATOR_LIGHTEN OperatorColorDodge Operator = C.CAIRO_OPERATOR_COLOR_DODGE OperatorColorBurn Operator = C.CAIRO_OPERATOR_COLOR_BURN OperatorHardLight Operator = C.CAIRO_OPERATOR_HARD_LIGHT OperatorSoftLight Operator = C.CAIRO_OPERATOR_SOFT_LIGHT OperatorDifference Operator = C.CAIRO_OPERATOR_DIFFERENCE OperatorExclusion Operator = C.CAIRO_OPERATOR_EXCLUSION OperatorHslHue Operator = C.CAIRO_OPERATOR_HSL_HUE OperatorHslSaturation Operator = C.CAIRO_OPERATOR_HSL_SATURATION OperatorHslColor Operator = C.CAIRO_OPERATOR_HSL_COLOR OperatorHslLuminosity Operator = C.CAIRO_OPERATOR_HSL_LUMINOSITY ) func (this Operator) c() C.cairo_operator_t { return C.cairo_operator_t(this) } // void cairo_set_operator (cairo_t *cr, // cairo_operator_t op); func (this *Context) SetOperator(op Operator) { C.cairo_set_operator(this.c(), op.c()) } // cairo_operator_t cairo_get_operator (cairo_t *cr); func (this *Context) GetOperator() Operator { return Operator(C.cairo_get_operator(this.c())) } // void cairo_set_tolerance (cairo_t *cr, // double tolerance); func (this *Context) SetTolerance(tolerance float64) { C.cairo_set_tolerance(this.c(), C.double(tolerance)) } // double cairo_get_tolerance (cairo_t *cr); func (this *Context) GetTolerance() float64 { return float64(C.cairo_get_tolerance(this.c())) } // void cairo_clip (cairo_t *cr); func (this *Context) Clip() { C.cairo_clip(this.c()) } // void cairo_clip_preserve (cairo_t *cr); func (this *Context) ClipPreserve() { C.cairo_clip_preserve(this.c()) } // void cairo_clip_extents (cairo_t *cr, // double *x1, // double *y1, // double *x2, // double *y2); func (this *Context) ClipExtents() (x1, y1, x2, y2 float64) { C.cairo_clip_extents(this.c(), (*C.double)(unsafe.Pointer(&x1)), (*C.double)(unsafe.Pointer(&y1)), (*C.double)(unsafe.Pointer(&x2)), (*C.double)(unsafe.Pointer(&y2))) return } // cairo_bool_t cairo_in_clip (cairo_t *cr, // double x, // double y); func (this *Context) InClip(x, y float64) bool { return C.cairo_in_clip(this.c(), C.double(x), C.double(y)) != 0 } // void cairo_reset_clip (cairo_t *cr); func (this *Context) ResetClip() { C.cairo_reset_clip(this.c()) } // cairo_rectangle_t; type Rectangle struct { X, Y, Width, Height float64 } // cairo_rectangle_list_t; // void cairo_rectangle_list_destroy (cairo_rectangle_list_t *rectangle_list); // cairo_rectangle_list_t * cairo_copy_clip_rectangle_list (cairo_t *cr); func (this *Context) CopyClipRectangleList() ([]Rectangle, Status) { var slice []Rectangle var status Status rl := C.cairo_copy_clip_rectangle_list(this.c()) if rl.num_rectangles > 0 { var slice_header reflect.SliceHeader slice_header.Data = uintptr(unsafe.Pointer(rl.rectangles)) slice_header.Len = int(rl.num_rectangles) slice_header.Cap = int(rl.num_rectangles) slice_src := *(*[]Rectangle)(unsafe.Pointer(&slice_header)) slice = make([]Rectangle, rl.num_rectangles) copy(slice, slice_src) } status = Status(rl.status) C.cairo_rectangle_list_destroy(rl) return slice, status } // void cairo_fill (cairo_t *cr); func (this *Context) Fill() { C.cairo_fill(this.c()) } // void cairo_fill_preserve (cairo_t *cr); func (this *Context) FillPreserve() { C.cairo_fill_preserve(this.c()) } // void cairo_fill_extents (cairo_t *cr, // double *x1, // double *y1, // double *x2, // double *y2); func (this *Context) FillExtents() (x1, y1, x2, y2 float64) { C.cairo_fill_extents(this.c(), (*C.double)(unsafe.Pointer(&x1)), (*C.double)(unsafe.Pointer(&y1)), (*C.double)(unsafe.Pointer(&x2)), (*C.double)(unsafe.Pointer(&y2))) return } // cairo_bool_t cairo_in_fill (cairo_t *cr, // double x, // double y); func (this *Context) InFill(x, y float64) bool { return C.cairo_in_fill(this.c(), C.double(x), C.double(y)) != 0 } // void cairo_mask (cairo_t *cr, // cairo_pattern_t *pattern); func (this *Context) Mask(pattern PatternLike) { C.cairo_mask(this.c(), pattern.InheritedFromCairoPattern().c()) } // void cairo_mask_surface (cairo_t *cr, // cairo_surface_t *surface, // double surface_x, // double surface_y); func (this *Context) MaskSurface(surface SurfaceLike, surface_x, surface_y float64) { C.cairo_mask_surface(this.c(), surface.InheritedFromCairoSurface().c(), C.double(surface_x), C.double(surface_y)) } // void cairo_paint (cairo_t *cr); func (this *Context) Paint() { C.cairo_paint(this.c()) } // void cairo_paint_with_alpha (cairo_t *cr, // double alpha); func (this *Context) PaintWithAlpha(alpha float64) { C.cairo_paint_with_alpha(this.c(), C.double(alpha)) } // void cairo_stroke (cairo_t *cr); func (this *Context) Stroke() { C.cairo_stroke(this.c()) } // void cairo_stroke_preserve (cairo_t *cr); func (this *Context) StrokePreserve() { C.cairo_stroke_preserve(this.c()) } // void cairo_stroke_extents (cairo_t *cr, // double *x1, // double *y1, // double *x2, // double *y2); func (this *Context) StrokeExtents() (x1, y1, x2, y2 float64) { C.cairo_stroke_extents(this.c(), (*C.double)(unsafe.Pointer(&x1)), (*C.double)(unsafe.Pointer(&y1)), (*C.double)(unsafe.Pointer(&x2)), (*C.double)(unsafe.Pointer(&y2))) return } // cairo_bool_t cairo_in_stroke (cairo_t *cr, // double x, // double y); func (this *Context) InStroke(x, y float64) bool { return C.cairo_in_stroke(this.c(), C.double(x), C.double(y)) != 0 } // void cairo_copy_page (cairo_t *cr); func (this *Context) CopyPage() { C.cairo_copy_page(this.c()) } // void cairo_show_page (cairo_t *cr); func (this *Context) ShowPage() { C.cairo_show_page(this.c()) } // unsigned int cairo_get_reference_count (cairo_t *cr); // cairo_status_t cairo_set_user_data (cairo_t *cr, // const cairo_user_data_key_t *key, // void *user_data, // cairo_destroy_func_t destroy); // void * cairo_get_user_data (cairo_t *cr, // const cairo_user_data_key_t *key); //---------------------------------------------------------------------------- // Paths //---------------------------------------------------------------------------- // cairo_path_t; type Path struct { C unsafe.Pointer } func (this *Path) c() *C.cairo_path_t { return (*C.cairo_path_t)(this.C) } func path_finalizer(this *Path) { if gobject.FQueue.Push(unsafe.Pointer(this), path_finalizer2) { return } C.cairo_path_destroy(this.c()) } func path_finalizer2(this_un unsafe.Pointer) { this := (*Path)(this_un) C.cairo_path_destroy(this.c()) } func PathWrap(c_un unsafe.Pointer) unsafe.Pointer { if c_un == nil { return nil } c := (*C.cairo_path_t)(c_un) path := &Path{unsafe.Pointer(c)} runtime.SetFinalizer(path, path_finalizer) return unsafe.Pointer(path) } // TODO: Implement? // union cairo_path_data_t; // enum cairo_path_data_type_t; type PathDataType int const ( PathMoveTo PathDataType = C.CAIRO_PATH_MOVE_TO PathLineTo PathDataType = C.CAIRO_PATH_LINE_TO PathCurveTo PathDataType = C.CAIRO_PATH_CURVE_TO PathClosePath PathDataType = C.CAIRO_PATH_CLOSE_PATH ) // cairo_path_t * cairo_copy_path (cairo_t *cr); func (this *Context) CopyPath() *Path { return (*Path)(PathWrap(unsafe.Pointer(C.cairo_copy_path(this.c())))) } // cairo_path_t * cairo_copy_path_flat (cairo_t *cr); func (this *Context) CopyPathFlat() *Path { return (*Path)(PathWrap(unsafe.Pointer(C.cairo_copy_path_flat(this.c())))) } // void cairo_path_destroy (cairo_path_t *path); func (this *Path) Unref() { runtime.SetFinalizer(this, nil) C.cairo_path_destroy(this.c()) this.C = nil } // void cairo_append_path (cairo_t *cr, // const cairo_path_t *path); func (this *Context) AppendPath(path *Path) { C.cairo_append_path(this.c(), path.c()) } // cairo_bool_t cairo_has_current_point (cairo_t *cr); func (this *Context) HasCurrentPoint() bool { return C.cairo_has_current_point(this.c()) != 0 } // void cairo_get_current_point (cairo_t *cr, // double *x, // double *y); func (this *Context) GetCurrentPoint() (x, y float64) { C.cairo_get_current_point(this.c(), (*C.double)(unsafe.Pointer(&x)), (*C.double)(unsafe.Pointer(&y))) return } // void cairo_new_path (cairo_t *cr); func (this *Context) NewPath() { C.cairo_new_path(this.c()) } // void cairo_new_sub_path (cairo_t *cr); func (this *Context) NewSubPath() { C.cairo_new_sub_path(this.c()) } // void cairo_close_path (cairo_t *cr); func (this *Context) ClosePath() { C.cairo_close_path(this.c()) } // void cairo_arc (cairo_t *cr, // double xc, // double yc, // double radius, // double angle1, // double angle2); func (this *Context) Arc(xc, yc, radius, angle1, angle2 float64) { C.cairo_arc(this.c(), C.double(xc), C.double(yc), C.double(radius), C.double(angle1), C.double(angle2)) } // void cairo_arc_negative (cairo_t *cr, // double xc, // double yc, // double radius, // double angle1, // double angle2); func (this *Context) ArcNegative(xc, yc, radius, angle1, angle2 float64) { C.cairo_arc_negative(this.c(), C.double(xc), C.double(yc), C.double(radius), C.double(angle1), C.double(angle2)) } // void cairo_curve_to (cairo_t *cr, // double x1, // double y1, // double x2, // double y2, // double x3, // double y3); func (this *Context) CurveTo(x1, y1, x2, y2, x3, y3 float64) { C.cairo_curve_to(this.c(), C.double(x1), C.double(y1), C.double(x2), C.double(y2), C.double(x3), C.double(y3)) } // void cairo_line_to (cairo_t *cr, // double x, // double y); func (this *Context) LineTo(x, y float64) { C.cairo_line_to(this.c(), C.double(x), C.double(y)) } // void cairo_move_to (cairo_t *cr, // double x, // double y); func (this *Context) MoveTo(x, y float64) { C.cairo_move_to(this.c(), C.double(x), C.double(y)) } // void cairo_rectangle (cairo_t *cr, // double x, // double y, // double width, // double height); func (this *Context) Rectangle(x, y, width, height float64) { C.cairo_rectangle(this.c(), C.double(x), C.double(y), C.double(width), C.double(height)) } // void cairo_glyph_path (cairo_t *cr, // const cairo_glyph_t *glyphs, // int num_glyphs); func (this *Context) GlyphPath(glyphs []Glyph) { var first *C.cairo_glyph_t var n = C.int(len(glyphs)) if n > 0 { first = glyphs[0].c() } C.cairo_glyph_path(this.c(), first, n) } // void cairo_text_path (cairo_t *cr, // const char *utf8); func (this *Context) TextPath(utf8 string) { utf8c := C.CString(utf8) C.cairo_text_path(this.c(), utf8c) C.free(unsafe.Pointer(utf8c)) } // void cairo_rel_curve_to (cairo_t *cr, // double dx1, // double dy1, // double dx2, // double dy2, // double dx3, // double dy3); func (this *Context) RelCurveTo(dx1, dy1, dx2, dy2, dx3, dy3 float64) { C.cairo_rel_curve_to(this.c(), C.double(dx1), C.double(dy1), C.double(dx2), C.double(dy2), C.double(dx3), C.double(dy3)) } // void cairo_rel_line_to (cairo_t *cr, // double dx, // double dy); func (this *Context) RelLineTo(dx, dy float64) { C.cairo_rel_line_to(this.c(), C.double(dx), C.double(dy)) } // void cairo_rel_move_to (cairo_t *cr, // double dx, // double dy); func (this *Context) RelMoveTo(dx, dy float64) { C.cairo_rel_move_to(this.c(), C.double(dx), C.double(dy)) } // void cairo_path_extents (cairo_t *cr, // double *x1, // double *y1, // double *x2, // double *y2); func (this *Context) PathExtents() (x1, y1, x2, y2 float64) { C.cairo_path_extents(this.c(), (*C.double)(unsafe.Pointer(&x1)), (*C.double)(unsafe.Pointer(&y1)), (*C.double)(unsafe.Pointer(&x2)), (*C.double)(unsafe.Pointer(&y2))) return } //---------------------------------------------------------------------------- // Pattern // SolidPattern // SurfacePattern // Gradient // LinearGradient // RadialGradient //---------------------------------------------------------------------------- // typedef cairo_pattern_t; type PatternLike interface { InheritedFromCairoPattern() *Pattern } type Pattern struct{ C unsafe.Pointer } type SolidPattern struct{ Pattern } type SurfacePattern struct{ Pattern } type Gradient struct{ Pattern } type LinearGradient struct{ Gradient } type RadialGradient struct{ Gradient } func (this *Pattern) c() *C.cairo_pattern_t { return (*C.cairo_pattern_t)(this.C) } func pattern_finalizer(this *Pattern) { if gobject.FQueue.Push(unsafe.Pointer(this), pattern_finalizer2) { return } C.cairo_pattern_set_user_data(this.c(), &go_repr_cookie, nil, nil) C.cairo_pattern_destroy(this.c()) } func pattern_finalizer2(this_un unsafe.Pointer) { this := (*Pattern)(this_un) C.cairo_pattern_set_user_data(this.c(), &go_repr_cookie, nil, nil) C.cairo_pattern_destroy(this.c()) } func PatternWrap(c_un unsafe.Pointer, grab bool) unsafe.Pointer { if c_un == nil { return nil } c := (*C.cairo_pattern_t)(c_un) go_repr := C.cairo_pattern_get_user_data(c, &go_repr_cookie) if go_repr != nil { return unsafe.Pointer(go_repr) } pattern := &Pattern{unsafe.Pointer(c)} if grab { C.cairo_pattern_reference(c) } runtime.SetFinalizer(pattern, pattern_finalizer) status := C.cairo_pattern_set_user_data(c, &go_repr_cookie, unsafe.Pointer(pattern), nil) if status != C.CAIRO_STATUS_SUCCESS { panic("failed to set user data, out of memory?") } return unsafe.Pointer(pattern) } func ensure_pattern_type(c *C.cairo_pattern_t, types ...PatternType) { for _, t := range types { if C.cairo_pattern_get_type(c) == t.c() { return } } panic("unexpected pattern type") } func ToPattern(like PatternLike) *Pattern { return (*Pattern)(PatternWrap(unsafe.Pointer(like.InheritedFromCairoPattern().c()), true)) } func ToSolidPattern(like PatternLike) *SolidPattern { c := like.InheritedFromCairoPattern().c() ensure_pattern_type(c, PatternTypeSolid) return (*SolidPattern)(PatternWrap(unsafe.Pointer(c), true)) } func ToSurfacePattern(like PatternLike) *SurfacePattern { c := like.InheritedFromCairoPattern().c() ensure_pattern_type(c, PatternTypeSurface) return (*SurfacePattern)(PatternWrap(unsafe.Pointer(c), true)) } func ToGradient(like PatternLike) *Gradient { c := like.InheritedFromCairoPattern().c() ensure_pattern_type(c, PatternTypeLinear, PatternTypeRadial) return (*Gradient)(PatternWrap(unsafe.Pointer(c), true)) } func ToLinearGradient(like PatternLike) *LinearGradient { c := like.InheritedFromCairoPattern().c() ensure_pattern_type(c, PatternTypeLinear) return (*LinearGradient)(PatternWrap(unsafe.Pointer(c), true)) } func ToRadialGradient(like PatternLike) *RadialGradient { c := like.InheritedFromCairoPattern().c() ensure_pattern_type(c, PatternTypeRadial) return (*RadialGradient)(PatternWrap(unsafe.Pointer(c), true)) } func (this *Pattern) InheritedFromCairoPattern() *Pattern { return this } // void cairo_pattern_add_color_stop_rgb (cairo_pattern_t *pattern, // double offset, // double red, // double green, // double blue); func (this *Gradient) AddColorStopRGB(offset, red, green, blue float64) { C.cairo_pattern_add_color_stop_rgb(this.c(), C.double(offset), C.double(red), C.double(green), C.double(blue)) } // void cairo_pattern_add_color_stop_rgba (cairo_pattern_t *pattern, // double offset, // double red, // double green, // double blue, // double alpha); func (this *Gradient) AddColorStopRGBA(offset, red, green, blue, alpha float64) { C.cairo_pattern_add_color_stop_rgba(this.c(), C.double(offset), C.double(red), C.double(green), C.double(blue), C.double(alpha)) } // cairo_status_t cairo_pattern_get_color_stop_count (cairo_pattern_t *pattern, // int *count); func (this *Gradient) GetColorStopCount() (count int) { C.cairo_pattern_get_color_stop_count(this.c(), (*C.int)(unsafe.Pointer(&count))) return } // cairo_status_t cairo_pattern_get_color_stop_rgba (cairo_pattern_t *pattern, // int index, // double *offset, // double *red, // double *green, // double *blue, // double *alpha); func (this *Gradient) GetColorStopRGBA(index int) (offset, red, green, blue, alpha float64) { C.cairo_pattern_get_color_stop_rgba(this.c(), C.int(index), (*C.double)(unsafe.Pointer(&offset)), (*C.double)(unsafe.Pointer(&red)), (*C.double)(unsafe.Pointer(&green)), (*C.double)(unsafe.Pointer(&blue)), (*C.double)(unsafe.Pointer(&alpha))) return } // cairo_pattern_t * cairo_pattern_create_rgb (double red, // double green, // double blue); func NewSolidPatternRGB(red, green, blue float64) *SolidPattern { return (*SolidPattern)(PatternWrap(unsafe.Pointer(C.cairo_pattern_create_rgb(C.double(red), C.double(green), C.double(blue))), false)) } // cairo_pattern_t * cairo_pattern_create_rgba (double red, // double green, // double blue, // double alpha); func NewSolidPatternRGBA(red, green, blue, alpha float64) *SolidPattern { return (*SolidPattern)(PatternWrap(unsafe.Pointer(C.cairo_pattern_create_rgba(C.double(red), C.double(green), C.double(blue), C.double(alpha))), false)) } // cairo_status_t cairo_pattern_get_rgba (cairo_pattern_t *pattern, // double *red, // double *green, // double *blue, // double *alpha); func (this *SolidPattern) GetRGBA() (red, green, blue, alpha float64) { C.cairo_pattern_get_rgba(this.c(), (*C.double)(unsafe.Pointer(&red)), (*C.double)(unsafe.Pointer(&green)), (*C.double)(unsafe.Pointer(&blue)), (*C.double)(unsafe.Pointer(&alpha))) return } // cairo_pattern_t * cairo_pattern_create_for_surface (cairo_surface_t *surface); func NewSurfacePattern(surface SurfaceLike) *SurfacePattern { return (*SurfacePattern)(PatternWrap(unsafe.Pointer(C.cairo_pattern_create_for_surface(surface.InheritedFromCairoSurface().c())), false)) } // cairo_status_t cairo_pattern_get_surface (cairo_pattern_t *pattern, // cairo_surface_t **surface); func (this *SurfacePattern) GetSurface() *Surface { var surfacec *C.cairo_surface_t C.cairo_pattern_get_surface(this.c(), &surfacec) surface := (*Surface)(SurfaceWrap(unsafe.Pointer(surfacec), true)) return surface } // cairo_pattern_t * cairo_pattern_create_linear (double x0, // double y0, // double x1, // double y1); func NewLinearGradient(x0, y0, x1, y1 float64) *LinearGradient { return (*LinearGradient)(PatternWrap(unsafe.Pointer(C.cairo_pattern_create_linear( C.double(x0), C.double(y0), C.double(x1), C.double(y1))), false)) } // cairo_status_t cairo_pattern_get_linear_points (cairo_pattern_t *pattern, // double *x0, // double *y0, // double *x1, // double *y1); func (this *LinearGradient) GetLinearPoints() (x0, y0, x1, y1 float64) { C.cairo_pattern_get_linear_points(this.c(), (*C.double)(unsafe.Pointer(&x0)), (*C.double)(unsafe.Pointer(&y0)), (*C.double)(unsafe.Pointer(&x1)), (*C.double)(unsafe.Pointer(&y1))) return } // cairo_pattern_t * cairo_pattern_create_radial (double cx0, // double cy0, // double radius0, // double cx1, // double cy1, // double radius1); func NewRadialGradient(cx0, cy0, radius0, cx1, cy1, radius1 float64) *RadialGradient { return (*RadialGradient)(PatternWrap(unsafe.Pointer(C.cairo_pattern_create_radial( C.double(cx0), C.double(cy0), C.double(radius0), C.double(cx1), C.double(cy1), C.double(radius1))), false)) } // cairo_status_t cairo_pattern_get_radial_circles (cairo_pattern_t *pattern, // double *x0, // double *y0, // double *r0, // double *x1, // double *y1, // double *r1); func (this *RadialGradient) GetRadialCircles() (x0, y0, r0, x1, y1, r1 float64) { C.cairo_pattern_get_radial_circles(this.c(), (*C.double)(unsafe.Pointer(&x0)), (*C.double)(unsafe.Pointer(&y0)), (*C.double)(unsafe.Pointer(&r0)), (*C.double)(unsafe.Pointer(&x1)), (*C.double)(unsafe.Pointer(&y1)), (*C.double)(unsafe.Pointer(&r1))) return } // cairo_pattern_t * cairo_pattern_reference (cairo_pattern_t *pattern); // void cairo_pattern_destroy (cairo_pattern_t *pattern); func (this *Pattern) Unref() { runtime.SetFinalizer(this, nil) C.cairo_pattern_set_user_data(this.c(), &go_repr_cookie, nil, nil) C.cairo_pattern_destroy(this.c()) this.C = nil } // cairo_status_t cairo_pattern_status (cairo_pattern_t *pattern); func (this *Pattern) Status() Status { return Status(C.cairo_pattern_status(this.c())) } // enum cairo_extend_t; type Extend int const ( ExtendNone Extend = C.CAIRO_EXTEND_NONE ExtendRepeat Extend = C.CAIRO_EXTEND_REPEAT ExtendReflect Extend = C.CAIRO_EXTEND_REFLECT ExtendPad Extend = C.CAIRO_EXTEND_PAD ) func (this Extend) c() C.cairo_extend_t { return C.cairo_extend_t(this) } // void cairo_pattern_set_extend (cairo_pattern_t *pattern, // cairo_extend_t extend); func (this *SurfacePattern) SetExtend(extend Extend) { C.cairo_pattern_set_extend(this.c(), extend.c()) } // cairo_extend_t cairo_pattern_get_extend (cairo_pattern_t *pattern); func (this *SurfacePattern) GetExtend() Extend { return Extend(C.cairo_pattern_get_extend(this.c())) } // enum cairo_filter_t; type Filter int const ( FilterFast Filter = C.CAIRO_FILTER_FAST FilterGood Filter = C.CAIRO_FILTER_GOOD FilterBest Filter = C.CAIRO_FILTER_BEST FilterNearest Filter = C.CAIRO_FILTER_NEAREST FilterBilinear Filter = C.CAIRO_FILTER_BILINEAR FilterGaussian Filter = C.CAIRO_FILTER_GAUSSIAN ) func (this Filter) c() C.cairo_filter_t { return C.cairo_filter_t(this) } // void cairo_pattern_set_filter (cairo_pattern_t *pattern, // cairo_filter_t filter); func (this *SurfacePattern) SetFilter(filter Filter) { C.cairo_pattern_set_filter(this.c(), filter.c()) } // cairo_filter_t cairo_pattern_get_filter (cairo_pattern_t *pattern); func (this *SurfacePattern) GetFilter() Filter { return Filter(C.cairo_pattern_get_filter(this.c())) } // void cairo_pattern_set_matrix (cairo_pattern_t *pattern, // const cairo_matrix_t *matrix); func (this *Pattern) SetMatrix(matrix *Matrix) { C.cairo_pattern_set_matrix(this.c(), matrix.c()) } // void cairo_pattern_get_matrix (cairo_pattern_t *pattern, // cairo_matrix_t *matrix); func (this *Pattern) GetMatrix() Matrix { var matrix C.cairo_matrix_t C.cairo_pattern_get_matrix(this.c(), &matrix) return *(*Matrix)(unsafe.Pointer(&matrix)) } // enum cairo_pattern_type_t; type PatternType int const ( PatternTypeSolid PatternType = C.CAIRO_PATTERN_TYPE_SOLID PatternTypeSurface PatternType = C.CAIRO_PATTERN_TYPE_SURFACE PatternTypeLinear PatternType = C.CAIRO_PATTERN_TYPE_LINEAR PatternTypeRadial PatternType = C.CAIRO_PATTERN_TYPE_RADIAL ) func (this PatternType) c() C.cairo_pattern_type_t { return C.cairo_pattern_type_t(this) } // cairo_pattern_type_t cairo_pattern_get_type (cairo_pattern_t *pattern); func (this *Pattern) GetType() PatternType { return PatternType(C.cairo_pattern_get_type(this.c())) } // TODO: Implement these // unsigned int cairo_pattern_get_reference_count (cairo_pattern_t *pattern); // cairo_status_t cairo_pattern_set_user_data (cairo_pattern_t *pattern, // const cairo_user_data_key_t *key, // void *user_data, // cairo_destroy_func_t destroy); // void * cairo_pattern_get_user_data (cairo_pattern_t *pattern, // const cairo_user_data_key_t *key); //---------------------------------------------------------------------------- // Regions //---------------------------------------------------------------------------- // typedef cairo_region_t; type Region struct { C unsafe.Pointer } func (this *Region) c() *C.cairo_region_t { return (*C.cairo_region_t)(this.C) } func region_finalizer(this *Region) { if gobject.FQueue.Push(unsafe.Pointer(this), region_finalizer2) { return } C.cairo_region_destroy(this.c()) } func region_finalizer2(this_un unsafe.Pointer) { this := (*Region)(this_un) C.cairo_region_destroy(this.c()) } func RegionWrap(c_un unsafe.Pointer, grab bool) unsafe.Pointer { if c_un == nil { return nil } c := (*C.cairo_region_t)(c_un) if grab { C.cairo_region_reference(c) } region := &Region{unsafe.Pointer(c)} runtime.SetFinalizer(region, region_finalizer) return unsafe.Pointer(region) } // cairo_region_t * cairo_region_create (void); func NewRegion() *Region { return (*Region)(RegionWrap(unsafe.Pointer(C.cairo_region_create()), false)) } // cairo_region_t * cairo_region_create_rectangle (const cairo_rectangle_int_t *rectangle); func NewRegionRectangle(rectangle *RectangleInt) *Region { return (*Region)(RegionWrap(unsafe.Pointer(C.cairo_region_create_rectangle(rectangle.c())), false)) } // cairo_region_t * cairo_region_create_rectangles (const cairo_rectangle_int_t *rects, // int count); func NewRegionRectangles(rects []RectangleInt) *Region { var first *C.cairo_rectangle_int_t count := C.int(len(rects)) if count > 0 { first = rects[0].c() } return (*Region)(RegionWrap(unsafe.Pointer(C.cairo_region_create_rectangles(first, count)), false)) } // cairo_region_t * cairo_region_copy (const cairo_region_t *original); func (this *Region) Copy() *Region { return (*Region)(RegionWrap(unsafe.Pointer(C.cairo_region_copy(this.c())), false)) } // cairo_region_t * cairo_region_reference (cairo_region_t *region); // void cairo_region_destroy (cairo_region_t *region); func (this *Region) Unref() { runtime.SetFinalizer(this, nil) C.cairo_region_destroy(this.c()) this.C = nil } // cairo_status_t cairo_region_status (const cairo_region_t *region); func (this *Region) Status() Status { return Status(C.cairo_region_status(this.c())) } // void cairo_region_get_extents (const cairo_region_t *region, // cairo_rectangle_int_t *extents); func (this *Region) GetExtents() (extents RectangleInt) { C.cairo_region_get_extents(this.c(), extents.c()) return } // int cairo_region_num_rectangles (const cairo_region_t *region); func (this *Region) NumRectangles() int { return int(C.cairo_region_num_rectangles(this.c())) } // void cairo_region_get_rectangle (const cairo_region_t *region, // int nth, // cairo_rectangle_int_t *rectangle); func (this *Region) GetRectangle(nth int) (rectangle RectangleInt) { C.cairo_region_get_rectangle(this.c(), C.int(nth), rectangle.c()) return } // cairo_bool_t cairo_region_is_empty (const cairo_region_t *region); func (this *Region) IsEmpty() bool { return C.cairo_region_is_empty(this.c()) != 0 } // cairo_bool_t cairo_region_contains_point (const cairo_region_t *region, // int x, // int y); func (this *Region) ContainsPoint(x, y int) bool { return C.cairo_region_contains_point(this.c(), C.int(x), C.int(y)) != 0 } // enum cairo_region_overlap_t; type RegionOverlap int const ( RegionOverlapIn RegionOverlap = C.CAIRO_REGION_OVERLAP_IN /* completely inside region */ RegionOverlapOut RegionOverlap = C.CAIRO_REGION_OVERLAP_OUT /* completely outside region */ RegionOverlapPart RegionOverlap = C.CAIRO_REGION_OVERLAP_PART /* partly inside region */ ) // cairo_region_overlap_t cairo_region_contains_rectangle (const cairo_region_t *region, // const cairo_rectangle_int_t *rectangle); func (this *Region) ContainsRectangle(rectangle *RectangleInt) RegionOverlap { return RegionOverlap(C.cairo_region_contains_rectangle(this.c(), rectangle.c())) } // cairo_bool_t cairo_region_equal (const cairo_region_t *a, // const cairo_region_t *b); func (this *Region) Equal(b *Region) bool { return C.cairo_region_equal(this.c(), b.c()) != 0 } // void cairo_region_translate (cairo_region_t *region, // int dx, // int dy); func (this *Region) Translate(dx, dy int) { C.cairo_region_translate(this.c(), C.int(dx), C.int(dy)) } // cairo_status_t cairo_region_intersect (cairo_region_t *dst, // const cairo_region_t *other); func (this *Region) Intersect(other *Region) Status { return Status(C.cairo_region_intersect(this.c(), other.c())) } // cairo_status_t cairo_region_intersect_rectangle (cairo_region_t *dst, // const cairo_rectangle_int_t *rectangle); func (this *Region) IntersectRectangle(rectangle *RectangleInt) Status { return Status(C.cairo_region_intersect_rectangle(this.c(), rectangle.c())) } // cairo_status_t cairo_region_subtract (cairo_region_t *dst, // const cairo_region_t *other); func (this *Region) Subtract(other *Region) Status { return Status(C.cairo_region_subtract(this.c(), other.c())) } // cairo_status_t cairo_region_subtract_rectangle (cairo_region_t *dst, // const cairo_rectangle_int_t *rectangle); func (this *Region) SubtractRectangle(rectangle *RectangleInt) Status { return Status(C.cairo_region_subtract_rectangle(this.c(), rectangle.c())) } // cairo_status_t cairo_region_union (cairo_region_t *dst, // const cairo_region_t *other); func (this *Region) Union(other *Region) Status { return Status(C.cairo_region_union(this.c(), other.c())) } // cairo_status_t cairo_region_union_rectangle (cairo_region_t *dst, // const cairo_rectangle_int_t *rectangle); func (this *Region) UnionRectangle(rectangle *RectangleInt) Status { return Status(C.cairo_region_union_rectangle(this.c(), rectangle.c())) } // cairo_status_t cairo_region_xor (cairo_region_t *dst, // const cairo_region_t *other); func (this *Region) Xor(other *Region) Status { return Status(C.cairo_region_xor(this.c(), other.c())) } // cairo_status_t cairo_region_xor_rectangle (cairo_region_t *dst, // const cairo_rectangle_int_t *rectangle); func (this *Region) XorRectangle(rectangle *RectangleInt) Status { return Status(C.cairo_region_xor_rectangle(this.c(), rectangle.c())) } //---------------------------------------------------------------------------- // Transformations //---------------------------------------------------------------------------- // void cairo_translate (cairo_t *cr, // double tx, // double ty); func (this *Context) Translate(tx, ty float64) { C.cairo_translate(this.c(), C.double(tx), C.double(ty)) } // void cairo_scale (cairo_t *cr, // double sx, // double sy); func (this *Context) Scale(sx, sy float64) { C.cairo_scale(this.c(), C.double(sx), C.double(sy)) } // void cairo_rotate (cairo_t *cr, // double angle); func (this *Context) Rotate(angle float64) { C.cairo_rotate(this.c(), C.double(angle)) } // void cairo_transform (cairo_t *cr, // const cairo_matrix_t *matrix); func (this *Context) Transform(matrix *Matrix) { C.cairo_transform(this.c(), matrix.c()) } // void cairo_set_matrix (cairo_t *cr, // const cairo_matrix_t *matrix); func (this *Context) SetMatrix(matrix *Matrix) { C.cairo_set_matrix(this.c(), matrix.c()) } // void cairo_get_matrix (cairo_t *cr, // cairo_matrix_t *matrix); func (this *Context) GetMatrix() Matrix { var matrix C.cairo_matrix_t C.cairo_get_matrix(this.c(), &matrix) return *(*Matrix)(unsafe.Pointer(&matrix)) } // void cairo_identity_matrix (cairo_t *cr); func (this *Context) IdentityMatrix() { C.cairo_identity_matrix(this.c()) } // void cairo_user_to_device (cairo_t *cr, // double *x, // double *y); func (this *Context) UserToDevice(x, y float64) (float64, float64) { C.cairo_user_to_device(this.c(), (*C.double)(unsafe.Pointer(&x)), (*C.double)(unsafe.Pointer(&y))) return x, y } // void cairo_user_to_device_distance (cairo_t *cr, // double *dx, // double *dy); func (this *Context) UserToDeviceDistance(dx, dy float64) (float64, float64) { C.cairo_user_to_device_distance(this.c(), (*C.double)(unsafe.Pointer(&dx)), (*C.double)(unsafe.Pointer(&dy))) return dx, dy } // void cairo_device_to_user (cairo_t *cr, // double *x, // double *y); func (this *Context) DeviceToUser(x, y float64) (float64, float64) { C.cairo_device_to_user(this.c(), (*C.double)(unsafe.Pointer(&x)), (*C.double)(unsafe.Pointer(&y))) return x, y } // void cairo_device_to_user_distance (cairo_t *cr, // double *dx, // double *dy); func (this *Context) DeviceToUserDistance(dx, dy float64) (float64, float64) { C.cairo_device_to_user_distance(this.c(), (*C.double)(unsafe.Pointer(&dx)), (*C.double)(unsafe.Pointer(&dy))) return dx, dy } //---------------------------------------------------------------------------- // Text //---------------------------------------------------------------------------- // cairo_glyph_t; // type Glyph (see types_$GOARCH.go) func (this *Glyph) c() *C.cairo_glyph_t { return (*C.cairo_glyph_t)(unsafe.Pointer(this)) } // enum cairo_font_slant_t; type FontSlant int const ( FontSlantNormal FontSlant = C.CAIRO_FONT_SLANT_NORMAL FontSlantItalic FontSlant = C.CAIRO_FONT_SLANT_ITALIC FontSlantOblique FontSlant = C.CAIRO_FONT_SLANT_OBLIQUE ) func (this FontSlant) c() C.cairo_font_slant_t { return C.cairo_font_slant_t(this) } // enum cairo_font_weight_t; type FontWeight int const ( FontWeightNormal FontWeight = C.CAIRO_FONT_WEIGHT_NORMAL FontWeightBold FontWeight = C.CAIRO_FONT_WEIGHT_BOLD ) func (this FontWeight) c() C.cairo_font_weight_t { return C.cairo_font_weight_t(this) } // cairo_text_cluster_t; type TextCluster struct { NumBytes int32 NumGlyphs int32 } // enum cairo_text_cluster_flags_t; type TextClusterFlags int const ( TextClusterFlagBackward TextClusterFlags = C.CAIRO_TEXT_CLUSTER_FLAG_BACKWARD ) // void cairo_select_font_face (cairo_t *cr, // const char *family, // cairo_font_slant_t slant, // cairo_font_weight_t weight); func (this *Context) SelectFontFace(family string, slant FontSlant, weight FontWeight) { cfamily := C.CString(family) C.cairo_select_font_face(this.c(), cfamily, slant.c(), weight.c()) C.free(unsafe.Pointer(cfamily)) } // void cairo_set_font_size (cairo_t *cr, // double size); func (this *Context) SetFontSize(size float64) { C.cairo_set_font_size(this.c(), C.double(size)) } // void cairo_set_font_matrix (cairo_t *cr, // const cairo_matrix_t *matrix); func (this *Context) SetFontMatrix(matrix *Matrix) { C.cairo_set_font_matrix(this.c(), matrix.c()) } // void cairo_get_font_matrix (cairo_t *cr, // cairo_matrix_t *matrix); func (this *Context) GetFontMatrix() Matrix { var matrix Matrix C.cairo_get_font_matrix(this.c(), matrix.c()) return matrix } // TODO: Implement these // void cairo_set_font_options (cairo_t *cr, // const cairo_font_options_t *options); // void cairo_get_font_options (cairo_t *cr, // cairo_font_options_t *options); // void cairo_set_font_face (cairo_t *cr, // cairo_font_face_t *font_face); // cairo_font_face_t * cairo_get_font_face (cairo_t *cr); // void cairo_set_scaled_font (cairo_t *cr, // const cairo_scaled_font_t *scaled_font); // cairo_scaled_font_t * cairo_get_scaled_font (cairo_t *cr); // void cairo_show_text (cairo_t *cr, // const char *utf8); func (this *Context) ShowText(utf8 string) { cutf8 := C.CString(utf8) C.cairo_show_text(this.c(), cutf8) C.free(unsafe.Pointer(cutf8)) } // void cairo_show_glyphs (cairo_t *cr, // const cairo_glyph_t *glyphs, // int num_glyphs); func (this *Context) ShowGlyphs(glyphs []Glyph) { var first *C.cairo_glyph_t var n = C.int(len(glyphs)) if n > 0 { first = glyphs[0].c() } C.cairo_show_glyphs(this.c(), first, n) } // TODO: Implement these // void cairo_show_text_glyphs (cairo_t *cr, // const char *utf8, // int utf8_len, // const cairo_glyph_t *glyphs, // int num_glyphs, // const cairo_text_cluster_t *clusters, // int num_clusters, // cairo_text_cluster_flags_t cluster_flags); // void cairo_font_extents (cairo_t *cr, // cairo_font_extents_t *extents); // void cairo_text_extents (cairo_t *cr, // const char *utf8, // cairo_text_extents_t *extents); // void cairo_glyph_extents (cairo_t *cr, // const cairo_glyph_t *glyphs, // int num_glyphs, // cairo_text_extents_t *extents); // cairo_font_face_t * cairo_toy_font_face_create (const char *family, // cairo_font_slant_t slant, // cairo_font_weight_t weight); // const char * cairo_toy_font_face_get_family (cairo_font_face_t *font_face); // cairo_font_slant_t cairo_toy_font_face_get_slant (cairo_font_face_t *font_face); // cairo_font_weight_t cairo_toy_font_face_get_weight (cairo_font_face_t *font_face); // cairo_glyph_t * cairo_glyph_allocate (int num_glyphs); // void cairo_glyph_free (cairo_glyph_t *glyphs); // cairo_text_cluster_t * cairo_text_cluster_allocate (int num_clusters); // void cairo_text_cluster_free (cairo_text_cluster_t *clusters); //---------------------------------------------------------------------------- // FontFace //---------------------------------------------------------------------------- // typedef cairo_font_face_t; type FontFace struct { C unsafe.Pointer } func (this *FontFace) c() *C.cairo_font_face_t { return (*C.cairo_font_face_t)(this.C) } func font_face_finalizer(this *FontFace) { if gobject.FQueue.Push(unsafe.Pointer(this), font_face_finalizer2) { return } C.cairo_font_face_destroy(this.c()) } func font_face_finalizer2(this_un unsafe.Pointer) { this := (*FontFace)(this_un) C.cairo_font_face_destroy(this.c()) } func FontFaceWrap(c_un unsafe.Pointer, grab bool) unsafe.Pointer { if c_un == nil { return nil } c := (*C.cairo_font_face_t)(c_un) go_repr := C.cairo_font_face_get_user_data(c, &go_repr_cookie) if go_repr != nil { return unsafe.Pointer(go_repr) } font_face := &FontFace{unsafe.Pointer(c)} if grab { C.cairo_font_face_reference(c) } runtime.SetFinalizer(font_face, font_face_finalizer) status := C.cairo_font_face_set_user_data(c, &go_repr_cookie, unsafe.Pointer(font_face), nil) if status != C.CAIRO_STATUS_SUCCESS { panic("failed to set user data, out of memory?") } return unsafe.Pointer(font_face) } // cairo_font_face_t * cairo_font_face_reference (cairo_font_face_t *font_face); // void cairo_font_face_destroy (cairo_font_face_t *font_face); func (this *FontFace) Unref() { runtime.SetFinalizer(this, nil) C.cairo_font_face_destroy(this.c()) this.C = nil } // cairo_status_t cairo_font_face_status (cairo_font_face_t *font_face); func (this *FontFace) Status() Status { return Status(C.cairo_font_face_status(this.c())) } // enum cairo_font_type_t; type FontType int const ( FontTypeToy FontType = C.CAIRO_FONT_TYPE_TOY FontTypeFT FontType = C.CAIRO_FONT_TYPE_FT FontTypeWin32 FontType = C.CAIRO_FONT_TYPE_WIN32 FontTypeQuartz FontType = C.CAIRO_FONT_TYPE_QUARTZ FontTypeUser FontType = C.CAIRO_FONT_TYPE_USER ) // cairo_font_type_t cairo_font_face_get_type (cairo_font_face_t *font_face); func (this *FontFace) GetType() FontType { return FontType(C.cairo_font_face_get_type(this.c())) } // unsigned int cairo_font_face_get_reference_count (cairo_font_face_t *font_face); // cairo_status_t cairo_font_face_set_user_data (cairo_font_face_t *font_face, // const cairo_user_data_key_t *key, // void *user_data, // cairo_destroy_func_t destroy); // void * cairo_font_face_get_user_data (cairo_font_face_t *font_face, // const cairo_user_data_key_t *key); //---------------------------------------------------------------------------- // ScaledFont //---------------------------------------------------------------------------- // typedef cairo_scaled_font_t; type ScaledFont struct { C unsafe.Pointer } func (this *ScaledFont) c() *C.cairo_scaled_font_t { return (*C.cairo_scaled_font_t)(this.C) } func scaled_font_finalizer(this *ScaledFont) { if gobject.FQueue.Push(unsafe.Pointer(this), scaled_font_finalizer2) { return } C.cairo_scaled_font_destroy(this.c()) } func scaled_font_finalizer2(this_un unsafe.Pointer) { this := (*ScaledFont)(this_un) C.cairo_scaled_font_destroy(this.c()) } func ScaledFontWrap(c_un unsafe.Pointer, grab bool) unsafe.Pointer { if c_un == nil { return nil } c := (*C.cairo_scaled_font_t)(c_un) go_repr := C.cairo_scaled_font_get_user_data(c, &go_repr_cookie) if go_repr != nil { return unsafe.Pointer(go_repr) } scaled_font := &ScaledFont{unsafe.Pointer(c)} if grab { C.cairo_scaled_font_reference(c) } runtime.SetFinalizer(scaled_font, scaled_font_finalizer) status := C.cairo_scaled_font_set_user_data(c, &go_repr_cookie, unsafe.Pointer(scaled_font), nil) if status != C.CAIRO_STATUS_SUCCESS { panic("failed to set user data, out of memory?") } return unsafe.Pointer(scaled_font) } // cairo_scaled_font_t * cairo_scaled_font_create (cairo_font_face_t *font_face, // const cairo_matrix_t *font_matrix, // const cairo_matrix_t *ctm, // const cairo_font_options_t *options); func NewScaledFont(font_face *FontFace, font_matrix, ctm *Matrix, options *FontOptions) *ScaledFont { return (*ScaledFont)(ScaledFontWrap(unsafe.Pointer(C.cairo_scaled_font_create( font_face.c(), font_matrix.c(), ctm.c(), options.c())), false)) } // cairo_scaled_font_t * cairo_scaled_font_reference (cairo_scaled_font_t *scaled_font); // void cairo_scaled_font_destroy (cairo_scaled_font_t *scaled_font); func (this *ScaledFont) Unref() { runtime.SetFinalizer(this, nil) C.cairo_scaled_font_destroy(this.c()) this.C = nil } // cairo_status_t cairo_scaled_font_status (cairo_scaled_font_t *scaled_font); func (this *ScaledFont) Status() Status { return Status(C.cairo_scaled_font_status(this.c())) } // cairo_font_extents_t; type FontExtents struct { Ascent float64 Descent float64 Height float64 MaxXAdvance float64 MaxYAdvance float64 } func (this *FontExtents) c() *C.cairo_font_extents_t { return (*C.cairo_font_extents_t)(unsafe.Pointer(this)) } // void cairo_scaled_font_extents (cairo_scaled_font_t *scaled_font, // cairo_font_extents_t *extents); func (this *ScaledFont) Extents() (out FontExtents) { C.cairo_scaled_font_extents(this.c(), out.c()) return } // cairo_text_extents_t; type TextExtents struct { XBearing float64 YBearing float64 Width float64 Height float64 XAdvance float64 YAdvance float64 } func (this *TextExtents) c() *C.cairo_text_extents_t { return (*C.cairo_text_extents_t)(unsafe.Pointer(this)) } // void cairo_scaled_font_text_extents (cairo_scaled_font_t *scaled_font, // const char *utf8, // cairo_text_extents_t *extents); func (this *ScaledFont) TextExtents(utf8 string) (out TextExtents) { utf8c := C.CString(utf8) C.cairo_scaled_font_text_extents(this.c(), utf8c, out.c()) C.free(unsafe.Pointer(utf8c)) return } // void cairo_scaled_font_glyph_extents (cairo_scaled_font_t *scaled_font, // const cairo_glyph_t *glyphs, // int num_glyphs, // cairo_text_extents_t *extents); func (this *ScaledFont) GlyphExtents(glyphs []Glyph) (out TextExtents) { var first *C.cairo_glyph_t var n = C.int(len(glyphs)) if n > 0 { first = glyphs[0].c() } C.cairo_scaled_font_glyph_extents(this.c(), first, n, out.c()) return } // TODO // cairo_status_t cairo_scaled_font_text_to_glyphs (cairo_scaled_font_t *scaled_font, // double x, // double y, // const char *utf8, // int utf8_len, // cairo_glyph_t **glyphs, // int *num_glyphs, // cairo_text_cluster_t **clusters, // int *num_clusters, // cairo_text_cluster_flags_t *cluster_flags); // cairo_font_face_t * cairo_scaled_font_get_font_face (cairo_scaled_font_t *scaled_font); func (this *ScaledFont) GetFontFace() *FontFace { return (*FontFace)(FontFaceWrap(unsafe.Pointer(C.cairo_scaled_font_get_font_face(this.c())), true)) } // void cairo_scaled_font_get_font_options (cairo_scaled_font_t *scaled_font, // cairo_font_options_t *options); func (this *ScaledFont) GetFontOptions() *FontOptions { fo := NewFontOptions() C.cairo_scaled_font_get_font_options(this.c(), fo.c()) return fo } // void cairo_scaled_font_get_font_matrix (cairo_scaled_font_t *scaled_font, // cairo_matrix_t *font_matrix); func (this *ScaledFont) GetFontMatrix() (out Matrix) { C.cairo_scaled_font_get_font_matrix(this.c(), out.c()) return } // void cairo_scaled_font_get_ctm (cairo_scaled_font_t *scaled_font, // cairo_matrix_t *ctm); func (this *ScaledFont) GetCTM() (out Matrix) { C.cairo_scaled_font_get_ctm(this.c(), out.c()) return } // void cairo_scaled_font_get_scale_matrix (cairo_scaled_font_t *scaled_font, // cairo_matrix_t *scale_matrix); func (this *ScaledFont) GetScaleMatrix() (out Matrix) { C.cairo_scaled_font_get_scale_matrix(this.c(), out.c()) return } // cairo_font_type_t cairo_scaled_font_get_type (cairo_scaled_font_t *scaled_font); func (this *ScaledFont) GetType() FontType { return FontType(C.cairo_scaled_font_get_type(this.c())) } // unsigned int cairo_scaled_font_get_reference_count // (cairo_scaled_font_t *scaled_font); // cairo_status_t cairo_scaled_font_set_user_data (cairo_scaled_font_t *scaled_font, // const cairo_user_data_key_t *key, // void *user_data, // cairo_destroy_func_t destroy); // void * cairo_scaled_font_get_user_data (cairo_scaled_font_t *scaled_font, // const cairo_user_data_key_t *key); //---------------------------------------------------------------------------- // Font Options //---------------------------------------------------------------------------- // typedef cairo_font_options_t; type FontOptions struct { C unsafe.Pointer } func (this *FontOptions) c() *C.cairo_font_options_t { return (*C.cairo_font_options_t)(this.C) } func font_options_finalizer(this *FontOptions) { if gobject.FQueue.Push(unsafe.Pointer(this), font_options_finalizer2) { return } C.cairo_font_options_destroy(this.c()) } func font_options_finalizer2(this_un unsafe.Pointer) { this := (*FontOptions)(this_un) C.cairo_font_options_destroy(this.c()) } func FontOptionsWrap(c_un unsafe.Pointer) unsafe.Pointer { if c_un == nil { return nil } c := (*C.cairo_font_options_t)(c_un) font_options := &FontOptions{unsafe.Pointer(c)} runtime.SetFinalizer(font_options, font_options_finalizer) return unsafe.Pointer(font_options) } // cairo_font_options_t * cairo_font_options_create (void); func NewFontOptions() *FontOptions { return (*FontOptions)(FontOptionsWrap(unsafe.Pointer(C.cairo_font_options_create()))) } // cairo_font_options_t * cairo_font_options_copy (const cairo_font_options_t *original); func (this *FontOptions) Copy() *FontOptions { return (*FontOptions)(FontOptionsWrap(unsafe.Pointer(C.cairo_font_options_copy(this.c())))) } // void cairo_font_options_destroy (cairo_font_options_t *options); func (this *FontOptions) Unref() { runtime.SetFinalizer(this, nil) C.cairo_font_options_destroy(this.c()) this.C = nil } // cairo_status_t cairo_font_options_status (cairo_font_options_t *options); func (this *FontOptions) Status() Status { return Status(C.cairo_font_options_status(this.c())) } // void cairo_font_options_merge (cairo_font_options_t *options, // const cairo_font_options_t *other); func (this *FontOptions) Merge(other *FontOptions) { C.cairo_font_options_merge(this.c(), other.c()) } // unsigned long cairo_font_options_hash (const cairo_font_options_t *options); func (this *FontOptions) Hash() uint64 { return uint64(C.cairo_font_options_hash(this.c())) } // cairo_bool_t cairo_font_options_equal (const cairo_font_options_t *options, // const cairo_font_options_t *other); func (this *FontOptions) Equal(other *FontOptions) bool { return C.cairo_font_options_equal(this.c(), other.c()) != 0 } // void cairo_font_options_set_antialias (cairo_font_options_t *options, // cairo_antialias_t antialias); func (this *FontOptions) SetAntialias(antialias Antialias) { C.cairo_font_options_set_antialias(this.c(), antialias.c()) } // cairo_antialias_t cairo_font_options_get_antialias (const cairo_font_options_t *options); func (this *FontOptions) GetAntialias() Antialias { return Antialias(C.cairo_font_options_get_antialias(this.c())) } // enum cairo_subpixel_order_t; type SubpixelOrder int const ( SubpixelOrderDefault SubpixelOrder = C.CAIRO_SUBPIXEL_ORDER_DEFAULT SubpixelOrderRGB SubpixelOrder = C.CAIRO_SUBPIXEL_ORDER_RGB SubpixelOrderBGR SubpixelOrder = C.CAIRO_SUBPIXEL_ORDER_BGR SubpixelOrderVRGB SubpixelOrder = C.CAIRO_SUBPIXEL_ORDER_VRGB SubpixelOrderVBGR SubpixelOrder = C.CAIRO_SUBPIXEL_ORDER_VBGR ) func (this SubpixelOrder) c() C.cairo_subpixel_order_t { return C.cairo_subpixel_order_t(this) } // void cairo_font_options_set_subpixel_order // (cairo_font_options_t *options, // cairo_subpixel_order_t subpixel_order); func (this *FontOptions) SetSubpixelOrder(subpixel_order SubpixelOrder) { C.cairo_font_options_set_subpixel_order(this.c(), subpixel_order.c()) } // cairo_subpixel_order_t cairo_font_options_get_subpixel_order // (const cairo_font_options_t *options); func (this *FontOptions) GetSubpixelOrder() SubpixelOrder { return SubpixelOrder(C.cairo_font_options_get_subpixel_order(this.c())) } // enum cairo_hint_style_t; type HintStyle int const ( HintStyleDefault HintStyle = C.CAIRO_HINT_STYLE_DEFAULT HintStyleNone HintStyle = C.CAIRO_HINT_STYLE_NONE HintStyleSlight HintStyle = C.CAIRO_HINT_STYLE_SLIGHT HintStyleMedium HintStyle = C.CAIRO_HINT_STYLE_MEDIUM HintStyleFull HintStyle = C.CAIRO_HINT_STYLE_FULL ) func (this HintStyle) c() C.cairo_hint_style_t { return C.cairo_hint_style_t(this) } // void cairo_font_options_set_hint_style (cairo_font_options_t *options, // cairo_hint_style_t hint_style); func (this *FontOptions) SetHintStyle(hint_style HintStyle) { C.cairo_font_options_set_hint_style(this.c(), hint_style.c()) } // cairo_hint_style_t cairo_font_options_get_hint_style (const cairo_font_options_t *options); func (this *FontOptions) GetHintStyle() HintStyle { return HintStyle(C.cairo_font_options_get_hint_style(this.c())) } // enum cairo_hint_metrics_t; type HintMetrics int const ( HintMetricsDefault HintMetrics = C.CAIRO_HINT_METRICS_DEFAULT HintMetricsOff HintMetrics = C.CAIRO_HINT_METRICS_OFF HintMetricsOn HintMetrics = C.CAIRO_HINT_METRICS_ON ) func (this HintMetrics) c() C.cairo_hint_metrics_t { return C.cairo_hint_metrics_t(this) } // void cairo_font_options_set_hint_metrics (cairo_font_options_t *options, // cairo_hint_metrics_t hint_metrics); func (this *FontOptions) SetHintMetrics(hint_metrics HintMetrics) { C.cairo_font_options_set_hint_metrics(this.c(), hint_metrics.c()) } // cairo_hint_metrics_t cairo_font_options_get_hint_metrics // (const cairo_font_options_t *options); func (this *FontOptions) GetHintMetrics() HintMetrics { return HintMetrics(C.cairo_font_options_get_hint_metrics(this.c())) } //---------------------------------------------------------------------------- // Device (TODO) //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Surface // ImageSurface // PDFSurface // ... etc //---------------------------------------------------------------------------- // #define CAIRO_MIME_TYPE_JP2 // #define CAIRO_MIME_TYPE_JPEG // #define CAIRO_MIME_TYPE_PNG // #define CAIRO_MIME_TYPE_URI const ( MimeTypeJp2 = "image/jp2" MimeTypeJpeg = "image/jpeg" MimeTypePng = "image/png" MimeTypeUri = "text/x-uri" ) // typedef cairo_surface_t; type SurfaceLike interface { InheritedFromCairoSurface() *Surface } type Surface struct{ C unsafe.Pointer } type ImageSurface struct{ Surface } type PDFSurface struct{ Surface } func (this *Surface) c() *C.cairo_surface_t { return (*C.cairo_surface_t)(this.C) } func surface_finalizer(this *Surface) { if gobject.FQueue.Push(unsafe.Pointer(this), surface_finalizer2) { return } C.cairo_surface_set_user_data(this.c(), &go_repr_cookie, nil, nil) C.cairo_surface_destroy(this.c()) } func surface_finalizer2(this_un unsafe.Pointer) { this := (*Surface)(this_un) C.cairo_surface_set_user_data(this.c(), &go_repr_cookie, nil, nil) C.cairo_surface_destroy(this.c()) } func SurfaceWrap(c_un unsafe.Pointer, grab bool) unsafe.Pointer { if c_un == nil { return nil } c := (*C.cairo_surface_t)(c_un) go_repr := C.cairo_surface_get_user_data(c, &go_repr_cookie) if go_repr != nil { return unsafe.Pointer(go_repr) } surface := &Surface{unsafe.Pointer(c)} if grab { C.cairo_pattern_reference(c) } runtime.SetFinalizer(surface, surface_finalizer) status := C.cairo_surface_set_user_data(c, &go_repr_cookie, unsafe.Pointer(surface), nil) if status != C.CAIRO_STATUS_SUCCESS { panic("failed to set user data, out of memory?") } return unsafe.Pointer(surface) } func ensure_surface_type(c *C.cairo_surface_t, types ...SurfaceType) { for _, t := range types { if C.cairo_surface_get_type(c) == t.c() { return } } panic("unexpected surface type") } func ToSurface(like SurfaceLike) *Surface { return (*Surface)(SurfaceWrap(unsafe.Pointer(like.InheritedFromCairoSurface().c()), true)) } func ToImageSurface(like SurfaceLike) *ImageSurface { c := like.InheritedFromCairoSurface().c() ensure_surface_type(c, SurfaceTypeImage) return (*ImageSurface)(SurfaceWrap(unsafe.Pointer(c), true)) } func ToPDFSurface(like SurfaceLike) *PDFSurface { c := like.InheritedFromCairoSurface().c() ensure_surface_type(c, SurfaceTypePDF) return (*PDFSurface)(SurfaceWrap(unsafe.Pointer(c), true)) } func (this *Surface) InheritedFromCairoSurface() *Surface { return this } // enum cairo_content_t; type Content int const ( ContentColor Content = C.CAIRO_CONTENT_COLOR ContentAlpha Content = C.CAIRO_CONTENT_ALPHA ContentColorAlpha Content = C.CAIRO_CONTENT_COLOR_ALPHA ) func (this Content) c() C.cairo_content_t { return C.cairo_content_t(this) } // cairo_surface_t * cairo_surface_create_similar (cairo_surface_t *other, // cairo_content_t content, // int width, // int height); func (this *Surface) CreateSimilar(content Content, width, height int) *Surface { return (*Surface)(SurfaceWrap(unsafe.Pointer(C.cairo_surface_create_similar(this.c(), content.c(), C.int(width), C.int(height))), false)) } // cairo_surface_t * cairo_surface_create_for_rectangle (cairo_surface_t *target, // double x, // double y, // double width, // double height); func (this *Surface) CreateForRectangle(x, y, width, height float64) *Surface { return (*Surface)(SurfaceWrap(unsafe.Pointer(C.cairo_surface_create_for_rectangle(this.c(), C.double(x), C.double(y), C.double(width), C.double(height))), false)) } // cairo_surface_t * cairo_surface_reference (cairo_surface_t *surface); // void cairo_surface_destroy (cairo_surface_t *surface); func (this *Surface) Unref() { runtime.SetFinalizer(this, nil) C.cairo_surface_set_user_data(this.c(), &go_repr_cookie, nil, nil) C.cairo_surface_destroy(this.c()) this.C = nil } // cairo_status_t cairo_surface_status (cairo_surface_t *surface); func (this *Surface) Status() Status { return Status(C.cairo_surface_status(this.c())) } // void cairo_surface_finish (cairo_surface_t *surface); func (this *Surface) Finish() { C.cairo_surface_finish(this.c()) } // void cairo_surface_flush (cairo_surface_t *surface); func (this *Surface) Flush() { C.cairo_surface_flush(this.c()) } // TODO: Implement these // cairo_device_t * cairo_surface_get_device (cairo_surface_t *surface); // void cairo_surface_get_font_options (cairo_surface_t *surface, // cairo_font_options_t *options); // cairo_content_t cairo_surface_get_content (cairo_surface_t *surface); func (this *Surface) GetContent() Content { return Content(C.cairo_surface_get_content(this.c())) } // void cairo_surface_mark_dirty (cairo_surface_t *surface); func (this *Surface) MarkDirty() { C.cairo_surface_mark_dirty(this.c()) } // void cairo_surface_mark_dirty_rectangle (cairo_surface_t *surface, // int x, // int y, // int width, // int height); func (this *Surface) MarkDirtyRectangle(x, y, width, height int) { C.cairo_surface_mark_dirty_rectangle(this.c(), C.int(x), C.int(y), C.int(width), C.int(height)) } // void cairo_surface_set_device_offset (cairo_surface_t *surface, // double x_offset, // double y_offset); func (this *Surface) SetDeviceOffset(x_offset, y_offset float64) { C.cairo_surface_set_device_offset(this.c(), C.double(x_offset), C.double(y_offset)) } // void cairo_surface_get_device_offset (cairo_surface_t *surface, // double *x_offset, // double *y_offset); func (this *Surface) GetDeviceOffset() (x_offset, y_offset float64) { C.cairo_surface_get_device_offset(this.c(), (*C.double)(unsafe.Pointer(&x_offset)), (*C.double)(unsafe.Pointer(&y_offset))) return } // void cairo_surface_set_fallback_resolution // (cairo_surface_t *surface, // double x_pixels_per_inch, // double y_pixels_per_inch); func (this *Surface) SetFallbackResolution(x_pixels_per_inch, y_pixels_per_inch float64) { C.cairo_surface_set_fallback_resolution(this.c(), C.double(x_pixels_per_inch), C.double(y_pixels_per_inch)) } // void cairo_surface_get_fallback_resolution // (cairo_surface_t *surface, // double *x_pixels_per_inch, // double *y_pixels_per_inch); func (this *Surface) GetFallbackResolution() (x_pixels_per_inch, y_pixels_per_inch float64) { C.cairo_surface_get_fallback_resolution(this.c(), (*C.double)(unsafe.Pointer(&x_pixels_per_inch)), (*C.double)(unsafe.Pointer(&y_pixels_per_inch))) return } // enum cairo_surface_type_t; type SurfaceType int const ( SurfaceTypeImage SurfaceType = C.CAIRO_SURFACE_TYPE_IMAGE SurfaceTypePDF SurfaceType = C.CAIRO_SURFACE_TYPE_PDF SurfaceTypePS SurfaceType = C.CAIRO_SURFACE_TYPE_PS SurfaceTypeXLib SurfaceType = C.CAIRO_SURFACE_TYPE_XLIB SurfaceTypeXCB SurfaceType = C.CAIRO_SURFACE_TYPE_XCB SurfaceTypeGlitz SurfaceType = C.CAIRO_SURFACE_TYPE_GLITZ SurfaceTypeQuartz SurfaceType = C.CAIRO_SURFACE_TYPE_QUARTZ SurfaceTypeWin32 SurfaceType = C.CAIRO_SURFACE_TYPE_WIN32 SurfaceTypeBeOS SurfaceType = C.CAIRO_SURFACE_TYPE_BEOS SurfaceTypeDirectFB SurfaceType = C.CAIRO_SURFACE_TYPE_DIRECTFB SurfaceTypeSVG SurfaceType = C.CAIRO_SURFACE_TYPE_SVG SurfaceTypeOs2 SurfaceType = C.CAIRO_SURFACE_TYPE_OS2 SurfaceTypeWin32Printing SurfaceType = C.CAIRO_SURFACE_TYPE_WIN32_PRINTING SurfaceTypeQuartzImage SurfaceType = C.CAIRO_SURFACE_TYPE_QUARTZ_IMAGE SurfaceTypeScript SurfaceType = C.CAIRO_SURFACE_TYPE_SCRIPT SurfaceTypeQt SurfaceType = C.CAIRO_SURFACE_TYPE_QT SurfaceTypeRecording SurfaceType = C.CAIRO_SURFACE_TYPE_RECORDING SurfaceTypeVg SurfaceType = C.CAIRO_SURFACE_TYPE_VG SurfaceTypeGL SurfaceType = C.CAIRO_SURFACE_TYPE_GL SurfaceTypeDRM SurfaceType = C.CAIRO_SURFACE_TYPE_DRM SurfaceTypeTee SurfaceType = C.CAIRO_SURFACE_TYPE_TEE SurfaceTypeXML SurfaceType = C.CAIRO_SURFACE_TYPE_XML SurfaceTypeSkia SurfaceType = C.CAIRO_SURFACE_TYPE_SKIA SurfaceTypeSubsurface SurfaceType = C.CAIRO_SURFACE_TYPE_SUBSURFACE ) func (this SurfaceType) c() C.cairo_surface_type_t { return C.cairo_surface_type_t(this) } // cairo_surface_type_t cairo_surface_get_type (cairo_surface_t *surface); func (this *Surface) GetType() SurfaceType { return SurfaceType(C.cairo_surface_get_type(this.c())) } // TODO: Implement these // unsigned int cairo_surface_get_reference_count (cairo_surface_t *surface); // cairo_status_t cairo_surface_set_user_data (cairo_surface_t *surface, // const cairo_user_data_key_t *key, // void *user_data, // cairo_destroy_func_t destroy); // void * cairo_surface_get_user_data (cairo_surface_t *surface, // const cairo_user_data_key_t *key); // void cairo_surface_copy_page (cairo_surface_t *surface); func (this *Surface) CopyPage() { C.cairo_surface_copy_page(this.c()) } // void cairo_surface_show_page (cairo_surface_t *surface); func (this *Surface) ShowPage() { C.cairo_surface_show_page(this.c()) } // cairo_bool_t cairo_surface_has_show_text_glyphs (cairo_surface_t *surface); func (this *Surface) HasShowTextGlyphs() bool { return C.cairo_surface_has_show_text_glyphs(this.c()) != 0 } // TODO: Implement these // cairo_status_t cairo_surface_set_mime_data (cairo_surface_t *surface, // const char *mime_type, // unsigned char *data, // unsigned long length, // cairo_destroy_func_t destroy, // void *closure); // void cairo_surface_get_mime_data (cairo_surface_t *surface, // const char *mime_type, // unsigned char **data, // unsigned long *length); //---------------------------------------------------------------------------- // Image Surfaces //---------------------------------------------------------------------------- // enum cairo_format_t; type Format int const ( FormatInvalid Format = C.CAIRO_FORMAT_INVALID FormatARGB32 Format = C.CAIRO_FORMAT_ARGB32 FormatRGB24 Format = C.CAIRO_FORMAT_RGB24 FormatA8 Format = C.CAIRO_FORMAT_A8 FormatA1 Format = C.CAIRO_FORMAT_A1 FormatRGB16_565 Format = C.CAIRO_FORMAT_RGB16_565 ) func (this Format) c() C.cairo_format_t { return C.cairo_format_t(this) } // int cairo_format_stride_for_width (cairo_format_t format, // int width); func (this Format) StrideForWidth(width int) int { return int(C.cairo_format_stride_for_width(this.c(), C.int(width))) } // cairo_surface_t * cairo_image_surface_create (cairo_format_t format, // int width, // int height); func NewImageSurface(format Format, width, height int) *ImageSurface { return (*ImageSurface)(SurfaceWrap(unsafe.Pointer(C.cairo_image_surface_create(format.c(), C.int(width), C.int(height))), false)) } // TODO: Implement this (need a way to keep GC from freeing the 'data') // cairo_surface_t * cairo_image_surface_create_for_data (unsigned char *data, // cairo_format_t format, // int width, // int height, // int stride); // TODO: Implement this (think about wrapping it into slice.. how?) // unsigned char * cairo_image_surface_get_data (cairo_surface_t *surface); // cairo_format_t cairo_image_surface_get_format (cairo_surface_t *surface); func (this *ImageSurface) GetFormat() Format { return Format(C.cairo_image_surface_get_format(this.c())) } // int cairo_image_surface_get_width (cairo_surface_t *surface); func (this *ImageSurface) GetWidth() int { return int(C.cairo_image_surface_get_width(this.c())) } // int cairo_image_surface_get_height (cairo_surface_t *surface); func (this *ImageSurface) GetHeight() int { return int(C.cairo_image_surface_get_height(this.c())) } // int cairo_image_surface_get_stride (cairo_surface_t *surface); func (this *ImageSurface) GetStride() int { return int(C.cairo_image_surface_get_stride(this.c())) } //---------------------------------------------------------------------------- // PNG Support //---------------------------------------------------------------------------- // cairo_surface_t * cairo_image_surface_create_from_png (const char *filename); func NewImageSurfaceFromPNG(filename string) *ImageSurface { cfilename := C.CString(filename) surface := (*ImageSurface)(SurfaceWrap(unsafe.Pointer(C.cairo_image_surface_create_from_png(cfilename)), false)) C.free(unsafe.Pointer(cfilename)) return surface } // cairo_status_t (*cairo_read_func_t) (void *closure, // unsigned char *data, // unsigned int length); //export io_reader_wrapper func io_reader_wrapper(reader_up unsafe.Pointer, data_uc *C.uchar, length uint32) uint32 { var reader io.Reader var data []byte var data_header reflect.SliceHeader reader = *(*io.Reader)(reader_up) data_header.Data = uintptr(unsafe.Pointer(data_uc)) data_header.Len = int(length) data_header.Cap = int(length) data = *(*[]byte)(unsafe.Pointer(&data_header)) _, err := reader.Read(data) if err != nil { return uint32(StatusReadError) } return uint32(StatusSuccess) } // cairo_surface_t * cairo_image_surface_create_from_png_stream // (cairo_read_func_t read_func, // void *closure); func NewImageSurfaceFromPNGStream(r io.Reader) *ImageSurface { return (*ImageSurface)(SurfaceWrap(unsafe.Pointer(C._cairo_image_surface_create_from_png_stream(unsafe.Pointer(&r))), false)) } // cairo_status_t cairo_surface_write_to_png (cairo_surface_t *surface, // const char *filename); func (this *ImageSurface) WriteToPNG(filename string) Status { cfilename := C.CString(filename) status := C.cairo_surface_write_to_png(this.c(), cfilename) C.free(unsafe.Pointer(cfilename)) return Status(status) } // cairo_status_t (*cairo_write_func_t) (void *closure, // unsigned char *data, // unsigned int length); //export io_writer_wrapper func io_writer_wrapper(writer_up unsafe.Pointer, data_uc *C.uchar, length uint32) uint32 { var writer io.Writer var data []byte var data_header reflect.SliceHeader writer = *(*io.Writer)(writer_up) data_header.Data = uintptr(unsafe.Pointer(data_uc)) data_header.Len = int(length) data_header.Cap = int(length) data = *(*[]byte)(unsafe.Pointer(&data_header)) _, err := writer.Write(data) if err != nil { return uint32(StatusWriteError) } return uint32(StatusSuccess) } // cairo_status_t cairo_surface_write_to_png_stream (cairo_surface_t *surface, // cairo_write_func_t write_func, // void *closure); func (this *ImageSurface) WriteToPNGStream(w io.Writer) Status { return Status(C._cairo_surface_write_to_png_stream(this.c(), unsafe.Pointer(&w))) } //---------------------------------------------------------------------------- // PDF Surfaces //---------------------------------------------------------------------------- // #define CAIRO_HAS_PDF_SURFACE // cairo_surface_t * cairo_pdf_surface_create (const char *filename, // double width_in_points, // double height_in_points); func NewPDFSurface(filename string, width_in_points, height_in_points float64) *PDFSurface { cfilename := C.CString(filename) surface := (*PDFSurface)(SurfaceWrap(unsafe.Pointer(C.cairo_pdf_surface_create(cfilename, C.double(width_in_points), C.double(height_in_points))), false)) C.free(unsafe.Pointer(cfilename)) return surface } // cairo_surface_t * cairo_pdf_surface_create_for_stream (cairo_write_func_t write_func, // void *closure, // double width_in_points, // double height_in_points); func NewPDFSurfaceForStream(w io.Writer, width_in_points, height_in_points float64) *PDFSurface { surface := (*PDFSurface)(SurfaceWrap(unsafe.Pointer(C._cairo_pdf_surface_create_for_stream(unsafe.Pointer(&w), C.double(width_in_points), C.double(height_in_points))), false)) return surface } // void cairo_pdf_surface_restrict_to_version // (cairo_surface_t *surface, // cairo_pdf_version_t version); func (this *PDFSurface) RestrictToVersion(version PDFVersion) { C.cairo_pdf_surface_restrict_to_version(this.c(), version.c()) } // enum cairo_pdf_version_t; type PDFVersion int const ( PDFVersion_1_4 PDFVersion = C.CAIRO_PDF_VERSION_1_4 PDFVersion_1_5 PDFVersion = C.CAIRO_PDF_VERSION_1_5 ) func (this PDFVersion) c() C.cairo_pdf_version_t { return C.cairo_pdf_version_t(this) } // void cairo_pdf_get_versions (cairo_pdf_version_t const **versions, // int *num_versions); func PDFGetVersions() []PDFVersion { var versions *C.cairo_pdf_version_t var num_versions C.int C.cairo_pdf_get_versions(&versions, &num_versions) var out []PDFVersion if num_versions > 0 { out = make([]PDFVersion, num_versions) for i := range out { out[i] = (*(*[999999]PDFVersion)(unsafe.Pointer(&versions)))[i] } } return out } // const char * cairo_pdf_version_to_string (cairo_pdf_version_t version); func (this PDFVersion) String() string { return C.GoString(C.cairo_pdf_version_to_string(this.c())) } // void cairo_pdf_surface_set_size (cairo_surface_t *surface, // double width_in_points, // double height_in_points); func (this *PDFSurface) SetSize(width_in_points, height_in_points float64) { C.cairo_pdf_surface_set_size(this.c(), C.double(width_in_points), C.double(height_in_points)) } //---------------------------------------------------------------------------- // Matrix //---------------------------------------------------------------------------- // cairo_matrix_t; type Matrix struct { xx, yx, xy, yy, x0, y0 float64 } func (this *Matrix) c() *C.cairo_matrix_t { return (*C.cairo_matrix_t)(unsafe.Pointer(this)) } // void cairo_matrix_init (cairo_matrix_t *matrix, // double xx, // double yx, // double xy, // double yy, // double x0, // double y0); func (this *Matrix) Init(xx, yx, xy, yy, x0, y0 float64) { C.cairo_matrix_init(this.c(), C.double(xx), C.double(yx), C.double(xy), C.double(yy), C.double(x0), C.double(y0)) } // void cairo_matrix_init_identity (cairo_matrix_t *matrix); func (this *Matrix) InitIdentity() { C.cairo_matrix_init_identity(this.c()) } // void cairo_matrix_init_translate (cairo_matrix_t *matrix, // double tx, // double ty); func (this *Matrix) InitTranslate(tx, ty float64) { C.cairo_matrix_init_translate(this.c(), C.double(tx), C.double(ty)) } // void cairo_matrix_init_scale (cairo_matrix_t *matrix, // double sx, // double sy); func (this *Matrix) InitScale(sx, sy float64) { C.cairo_matrix_init_scale(this.c(), C.double(sx), C.double(sy)) } // void cairo_matrix_init_rotate (cairo_matrix_t *matrix, // double radians); func (this *Matrix) InitRotate(radians float64) { C.cairo_matrix_init_rotate(this.c(), C.double(radians)) } // void cairo_matrix_translate (cairo_matrix_t *matrix, // double tx, // double ty); func (this *Matrix) Translate(tx, ty float64) { C.cairo_matrix_translate(this.c(), C.double(tx), C.double(ty)) } // void cairo_matrix_scale (cairo_matrix_t *matrix, // double sx, // double sy); func (this *Matrix) Scale(sx, sy float64) { C.cairo_matrix_scale(this.c(), C.double(sx), C.double(sy)) } // void cairo_matrix_rotate (cairo_matrix_t *matrix, // double radians); func (this *Matrix) Rotate(radians float64) { C.cairo_matrix_rotate(this.c(), C.double(radians)) } // cairo_status_t cairo_matrix_invert (cairo_matrix_t *matrix); func (this *Matrix) Invert() Status { return Status(C.cairo_matrix_invert(this.c())) } // void cairo_matrix_multiply (cairo_matrix_t *result, // const cairo_matrix_t *a, // const cairo_matrix_t *b); func (this *Matrix) Multiply(b *Matrix) Matrix { var result C.cairo_matrix_t C.cairo_matrix_multiply(&result, this.c(), b.c()) return *(*Matrix)(unsafe.Pointer(&result)) } // void cairo_matrix_transform_distance (const cairo_matrix_t *matrix, // double *dx, // double *dy); func (this *Matrix) TransformDistance(dx, dy float64) (float64, float64) { C.cairo_matrix_transform_distance(this.c(), (*C.double)(unsafe.Pointer(&dx)), (*C.double)(unsafe.Pointer(&dy))) return dx, dy } // void cairo_matrix_transform_point (const cairo_matrix_t *matrix, // double *x, // double *y); func (this *Matrix) TransformPoint(x, y float64) (float64, float64) { C.cairo_matrix_transform_point(this.c(), (*C.double)(unsafe.Pointer(&x)), (*C.double)(unsafe.Pointer(&y))) return x, y } go-gir-generator-master/lib.in/cairo-1.0/demos/000077500000000000000000000000001414263242200213725ustar00rootroot00000000000000go-gir-generator-master/lib.in/cairo-1.0/demos/fill.go000066400000000000000000000005651414263242200226550ustar00rootroot00000000000000package main import "gobject/cairo-1.0" func main() { surface := cairo.NewImageSurface(cairo.FormatARGB32, 120, 120) cr := cairo.NewContext(surface) // Examples are in 1.0 x 1.0 coordinate space cr.Scale(120, 120) // Drawing code goes here cr.SetSourceRGB(0, 0, 0) cr.Rectangle(0.25, 0.25, 0.5, 0.5) cr.Fill() // Write output surface.WriteToPNG("fill.png") }go-gir-generator-master/lib.in/cairo-1.0/demos/fill.png000066400000000000000000000004241414263242200230260ustar00rootroot00000000000000PNG  IHDRxx9d6bKGDIDATxс @w-,9\g0^8N88N88N88N88N88N88N88N88N88N88N88N88N88N8Hy+LxIENDB`go-gir-generator-master/lib.in/cairo-1.0/demos/go-int1.go000066400000000000000000000012561414263242200232030ustar00rootroot00000000000000package main import "gobject/cairo-1.0" import "os" func main() { // read r, err := os.Open("tux.png") if err != nil { panic(err) } defer r.Close() surface := cairo.NewImageSurfaceFromPNGStream(r) if surface.Status() != cairo.StatusSuccess { panic(surface.Status().String()) } // modify cr := cairo.NewContext(surface) cr.Scale(float64(surface.GetWidth()), float64(surface.GetHeight())) cr.SetSourceRGBA(0.2, 0, 0, 0.5) cr.Rectangle(0.05, 0.05, 0.9, 0.9) cr.Fill() // write w, err := os.Create("tux-2.png") if err != nil { panic(err) } defer w.Close() status := surface.WriteToPNGStream(w) if status != cairo.StatusSuccess { panic(status.String()) } }go-gir-generator-master/lib.in/cairo-1.0/demos/go-int2.go000066400000000000000000000003531414263242200232010ustar00rootroot00000000000000package main import "gobject/cairo-1.0" func main() { surface := cairo.NewImageSurface(cairo.FormatARGB32, 128, 128) cr := cairo.NewContext(surface) x := cr.GetTarget() y := cr.GetTarget() z := cr.GetTarget() println(x, y, z) }go-gir-generator-master/lib.in/cairo-1.0/demos/mask.go000066400000000000000000000011511414263242200226520ustar00rootroot00000000000000package main import "gobject/cairo-1.0" func main() { surface := cairo.NewImageSurface(cairo.FormatARGB32, 120, 120) cr := cairo.NewContext(surface) // Examples are in 1.0 x 1.0 coordinate space cr.Scale(120, 120) // Drawing code goes here linpat := cairo.NewLinearGradient(0, 0, 1, 1) linpat.AddColorStopRGB(0, 0, 0.3, 0.8) linpat.AddColorStopRGB(1, 0, 0.8, 0.3) radpat := cairo.NewRadialGradient(0.5, 0.5, 0.25, 0.5, 0.5, 0.75) radpat.AddColorStopRGBA(0, 0, 0, 0, 1) radpat.AddColorStopRGBA(0.5, 0, 0, 0, 0) cr.SetSource(linpat) cr.Mask(radpat) // Write output surface.WriteToPNG("mask.png") }go-gir-generator-master/lib.in/cairo-1.0/demos/paint.go000066400000000000000000000005371414263242200230410ustar00rootroot00000000000000package main import "gobject/cairo-1.0" func main() { surface := cairo.NewImageSurface(cairo.FormatARGB32, 120, 120) cr := cairo.NewContext(surface) // Examples are in 1.0 x 1.0 coordinate space cr.Scale(120, 120) // Drawing code goes here cr.SetSourceRGB(0, 0, 0) cr.PaintWithAlpha(0.5) // Write output surface.WriteToPNG("paint.png") }go-gir-generator-master/lib.in/cairo-1.0/demos/path-close.go000066400000000000000000000011241414263242200237560ustar00rootroot00000000000000package main import "gobject/cairo-1.0" import "math" func main() { surface := cairo.NewImageSurface(cairo.FormatARGB32, 120, 120) cr := cairo.NewContext(surface) // Examples are in 1.0 x 1.0 coordinate space cr.Scale(120, 120) // Drawing code goes here cr.SetLineWidth(0.1) cr.SetSourceRGB(0, 0, 0) cr.MoveTo(0.25, 0.25) cr.LineTo(0.5, 0.375) cr.RelLineTo(0.25, -0.125) cr.Arc(0.5, 0.5, 0.25 * math.Sqrt2, -0.25 * math.Pi, 0.25 * math.Pi) cr.RelCurveTo(-0.25, -0.125, -0.25, 0.125, -0.5, 0) cr.ClosePath() cr.Stroke() // Write output surface.WriteToPNG("path-close.png") }go-gir-generator-master/lib.in/cairo-1.0/demos/pdf.go000066400000000000000000000010761414263242200224760ustar00rootroot00000000000000package main import "gobject/cairo-1.0" import "math" func main() { surface := cairo.NewPDFSurface("pdf.pdf", 256, 256) cr := cairo.NewContext(surface) lin := cairo.NewLinearGradient(0,0,0,256) lin.AddColorStopRGBA(1, 0, 0, 0, 1) lin.AddColorStopRGBA(0, 1, 1, 1, 1) cr.Rectangle(0, 0, 256, 256) cr.SetSource(lin) cr.Fill() rad := cairo.NewRadialGradient(115.2, 102.4, 25.6, 102.4, 102.4, 128.0) rad.AddColorStopRGBA(0, 1, 1, 1, 1) rad.AddColorStopRGBA(1, 0, 0, 0, 1) cr.SetSource(rad) cr.Arc(128, 128, 76.8, 0, 2 * math.Pi) cr.Fill() surface.Finish() }go-gir-generator-master/lib.in/cairo-1.0/demos/setsourcegradient.go000066400000000000000000000017461414263242200254630ustar00rootroot00000000000000package main import "gobject/cairo-1.0" func main() { surface := cairo.NewImageSurface(cairo.FormatARGB32, 120, 120) cr := cairo.NewContext(surface) // Examples are in 1.0 x 1.0 coordinate space cr.Scale(120, 120) // Drawing code goes here radpat := cairo.NewRadialGradient(0.25, 0.25, 0.1, 0.5, 0.5, 0.5) radpat.AddColorStopRGB(0, 1.0, 0.8, 0.8) radpat.AddColorStopRGB(1, 0.9, 0.0, 0.0) for i := 1; i < 10; i++ { fi := float64(i) for j := 1; j < 10; j++ { fj := float64(j) cr.Rectangle(fi/10.0 - 0.04, fj/10.0 - 0.04, 0.08, 0.08) } } cr.SetSource(radpat) cr.Fill() linpat := cairo.NewLinearGradient(0.25, 0.35, 0.75, 0.65) linpat.AddColorStopRGBA(0.00, 1, 1, 1, 0) linpat.AddColorStopRGBA(0.25, 0, 1, 0, 0.5) linpat.AddColorStopRGBA(0.50, 1, 1, 1, 0) linpat.AddColorStopRGBA(0.75, 0, 0, 1, 0.5) linpat.AddColorStopRGBA(1.00, 1, 1, 1, 0) cr.Rectangle(0, 0, 1, 1) cr.SetSource(linpat) cr.Fill() // Write output surface.WriteToPNG("setsourcegradient.png") }go-gir-generator-master/lib.in/cairo-1.0/demos/setsourcergba.go000066400000000000000000000012301414263242200245650ustar00rootroot00000000000000package main import "gobject/cairo-1.0" func main() { surface := cairo.NewImageSurface(cairo.FormatARGB32, 120, 120) cr := cairo.NewContext(surface) // Examples are in 1.0 x 1.0 coordinate space cr.Scale(120, 120) // Drawing code goes here cr.SetSourceRGB(0, 0, 0) cr.MoveTo(0, 0) cr.LineTo(1, 1) cr.MoveTo(1, 0) cr.LineTo(0, 1) cr.SetLineWidth(0.2) cr.Stroke() cr.Rectangle(0, 0, 0.5, 0.5) cr.SetSourceRGBA(1, 0, 0, 0.8) cr.Fill() cr.Rectangle(0, 0.5, 0.5, 0.5) cr.SetSourceRGBA(0, 1, 0, 0.6) cr.Fill() cr.Rectangle(0.5, 0, 0.5, 0.5) cr.SetSourceRGBA(0, 0, 1, 0.4) cr.Fill() // Write output surface.WriteToPNG("setsourcergba.png") }go-gir-generator-master/lib.in/cairo-1.0/demos/stroke.go000066400000000000000000000006171414263242200232340ustar00rootroot00000000000000package main import "gobject/cairo-1.0" func main() { surface := cairo.NewImageSurface(cairo.FormatARGB32, 120, 120) cr := cairo.NewContext(surface) // Examples are in 1.0 x 1.0 coordinate space cr.Scale(120, 120) // Drawing code goes here cr.SetLineWidth(0.1) cr.SetSourceRGB(0, 0, 0) cr.Rectangle(0.25, 0.25, 0.5, 0.5) cr.Stroke() // Write output surface.WriteToPNG("stroke.png") }go-gir-generator-master/lib.in/cairo-1.0/demos/tux.png000066400000000000000000001204241414263242200227230ustar00rootroot00000000000000PNG  IHDR~uIDATx^kLUᗛG^ XQ -{ްThuTZR>hqLɌu*aF(שʴ֌SXeqQkyN߬'N9$<$Z{0M",6#{᮱3VnJo{D$ }8ca-'(5<5gs"!8\]roosD4@Dl%f,+egX9s"D4@DCuީ}JU/D4@DV&iab̅b:pet`o1]_>VD4@D?zp8 0mmmhnn6iVʘ 4VfB D\\1b:dz޽{2\|wA' "FGqcbb0~xL0 b𧆆3HիW؈8a⦻h|tw|ȑ2e )))G09NTVVpd'0HDD$0|g7M>CVV`g. eee8z(Μ9ϽW}h|d;w.f͚e6{gϞԩS8v\?hd̉>D4@D>fX̙39993f *?~'OÇa <+]sRjʕ6mBy}vsB޾ ],^rss͊#22G[x,O 5z+vD7""X`9E)bǎx%,-aA/! "saHOOիjl۶ H-6' "RֿUҥKdsW:>o>ݻ׬L,J^cو^,,,Drr2?q6ol>b? 6" "aA8VZe吮CRTTdl~NCD4@DVv}fd8r,rZd"X4YlϟC90D4@D< G^^f̘ˈ$ʮ]FeC{l ዁Άĉ愖\lۍ X8<̞=<ٳgN>  "žb߂I&Y7ůot,pMd"&+jM 6;N̕7n꫾{S]4@DJi^PPT\v|ĢM$ ssj…<9pJKKa +H,e <yds*(h|kj ED+fxXx1tb>~X^DDf 2uׯ_oiiiM̯Eh=+Z܋/"N6E@DrNff>+H8& D$հ9]ֆ'[l1,{  "k{0vXsHqq1jjj`!'{]@avpM_ 6VpVľ\hdډl+DD5t ::ڦDbbb'ٟ}P @~9@ğ$umh `S;G*}jhCx=6(6 6<< ,U" ÞY;68p BV F~gD4@Dҽ]6S~ɓ'I=z4G߿c?a" <%o  . G"""`ֆǏE8sƒB),^.t5 !nBYY;_p@Db͛7͗_mCWx,sH }#yR'MMMf#fw#,^"%%'{̆MI>HpJVTWW#DV @Dࣤ$7#ׯ_7{RA @D;inn6( @DvaÐrG`fKwVɈGH]]ه wAMt; :;hРc|6.D+ 4DFF¿ɒ ad4@DXzSYaaa8Na#:") СCw}a3l+BLv 2d-Z۷e^6! BBv,[֚V6uGHYvB="ZypxmK Bț{wuuL:C6 *B[ ? u[]b=VkmVumk+mݪH( k.eLf|~{sLH,r|Nd$ +}ũ[]gyK9l b!`׮]y\5͝;g}Vn] W_}Ul-(x!K\Dx#Pvίk)j~ߊA]3G[ , r)*pK/cÆ \tE܂o~ |;ߑa%dR( ya;rDO>)xkf#  )*@Չ.f_#DMDuz \6AٳiӦET("-#lԩS 7ŨQD7:"Hc5 nڴ1cp?9n/0!KGnVyc=&FOqD"WC}HbR(AE~"(N}}=~%LH"{eO[Y@3C E6:ؾK/%k!vꮻ s=0Mv1d((`'.Zp-9Z2o$~yJF  ;?CZZ^{-LN-((2H#X&PT(*@.Ѡl͛7/wy߿5kֈ^pBd)BYGQ1Lr EdQLEG}T|weرb`~a1_3n"T EH oVi@zdeƌ駟&''gl۶M"B7}Xtˣ'N䩧 yUrUWEo(*@ 3g iK2@Ĉv٬;3e˖#rƍyW?L2qea֕We„ Q EH ˋVX~#N:$y)77W⋩$82dy{lዲn[?+p{7ESӑ=#PBє)%%K9T ("}]K+@Pd7wkk+}':?"<㲾qe\ "yf1%Xlɟ5PguVq8`DDM DQ{Mz@nXD{#]탾mq v XVY,h9_ cV ҉D(o%aܸq]oСC:\#KQɭt .В#G>ASSSCbq5W(*@QIIoP6UWWYW^yV!b(syHl6^e?~CCJ)CQ y j;Mv"@|!$_2tD* s1 ,F7A+OE+ Ema b z}DfvAzB E 9ש¹|u1w\?CȿO4D0! v=(rIƽm, CtY浾r+>V^ 􅘸j7.+@@"  1@DY^GbL ,0ui0a5QTD4 w^? tq(R$8M%OUɚՖ0 QT(Pa@"()˃9b* 6,>ޝ5Dkwinnph EDn!5! F,VɁ?D1Q!Yz5@v?3C Xu?o2@}bEQ%gDi">/j!N\UϐOrʹ:;i QյxL3Ʋpq\4{6"jQT/|s?Sz n{V##@" ־[RČDLX-F F|tIÃCytx{L`~zxB 񱱱l_`Pƹ+J)P/{;Q%ƽM Dt]rUЭ#wW9^b7[8_14yIxȋX@,\8酢DWT D7,whЈ9=}5<4 RˬgD^5c0it `J!&*eLQ#ϩ'% A7&?=/myM֣wz腼=ƎK0C$QuQ]&E_dmF(4`TnCfMn2R[HMj/N{thiܒH-N}1%sRrg]99 ?Pn;5kkx@> ZړO>8qs8~|hIve54oH瘯uMI-d.bdLG? yTV5l1X5SOwDIN 0Lo&sBrRLhNAN|4fBM17A@ y=m*҈qȏ57xHFҨN2r4WG* ƒ%KXbAǨ|A" 0\p~k%gֵߟMg`u1nd9cБw'C Ey8[ne„ [>ɉL(.Ӊ `p=;yl뵲ý.eIHwY#H."ChI駟fٲeDGPT(*@$ľ =xF|RۘX\}&U1'!Ϲ䷠w`MDjcERI8SpAx!G ,$DĔ^9fv#<d73v5b`ս ͟5㎑!ܐ@׏-?dUrbp[gQ(o/G!{v;^lFTv0phJ'$ZiOGd}l^PہrT(ʿ至'r)̯nCED~`h w}ϺPD[S7Kщ82Q7 ܱܻLc=4.pqA{7s;ϓkY1Q7 Ʌ b4_x0a|)Vkk`H!j>΁ 4tb&wُa&;RT( ` A(ΎG`14 HoY@ /okeգ6afHQ(3/\5ѣ+ɱ)!a\W>{a _žU/Ok0w儦NQtc͹£\[߫xНV pFHքp{@苢DQriLf'+ºc]`JЃXU!ZhxA h4%Pw$E(ƝVN[cnT9'@ DOb1`Ss(c<|+=t8& Da+5ӺUvP-K+20  C.I жˡ=zCu xq2z`ʱU&vo<b1n   d'+gp5!60ߖ"\/xtpUaex; TOȞL:=`BYÛDrV[S>ى`Q(GɀOn-7Zw-t0z2#A [1\7JGWfrFHh, &l."> E@Fec0$$uj} F`Lc bAg_#SZnۆ!nr[+M6&b541ZdH7 EmaDx[*cJc v𶇳GCnWޞCՁ4ʈi$vRD"`$pAQ-,Gv㞎uНqx0d\-| -umʧܣ1bj5iy~} ]ӫDQ;54[H#h1- z'n=HZ^_eQ/]ɵ䎱Z}mfpGE<QT48xI&y^JZAwn40oC>&'@ <_6uefg)-*y(otLEM3ɊhKHAV ̉ҁN4`ߏW(ۑEn[K1&/#O"{TcǙԗ]'e w9Q #J xn/&,M^b OH T ZY*51VPŌϺveC#@4^E? @?n(&5>hd5RX\Kl;keͧ|W&;3UçU;6`ѴeDpR(@=rV&:fJÚ# $B 9~쫬6Ϊ .5`V--<~h$\ K@B%33I5 Y\c=A͂ݱrm X%?@BmÑdʶgخ[uESk6mG7&S5[]MDNQ+E l%7efeƷ3ʥ' BbF-s[1Z d1}"5&bUүuMNwɇv3v# Mq~4 RrZLF4m`VD#_S+ +o`xkطo/Ql1' p !YK·M=ZEvQ#3)ݙ%V}&Ot]|WG^7a0,MIi#SgV_eP*k=[F sGᒋ"Jmf:'  wbB秷G>Guh&O9rP#Tt&W=i$X~diYw[U6RJ2 {Lcyӳ$ x EY#Dw..\qy}OZ '#V GR/OB͝!N74,)Nߤn*?[iG'ZL!9ɭx%$J9i^N*@e+0=0idi*û1hgܬr2 Ap(Ȏ63<"dDf+?wy 1:x!gQ'0ǵ lf"c{Ҋ@ !Pݳk*Oem:z*@ !DソTzh>߁ `M^ľ= Zt)ZG{opD;j*@%h4B'b4^}+x<(PSE&Ah']=p咋.p:. E)>^F6ѰI|đ)=,80zɧP2]wIӖR^YE{pz 8T(|`%!2L|:z3,7l4M&>Û)]ա#n`g{H8ʏTz %\LUe%Qn Ex+LQaInxM`R]?7%wUg >i=Ҳr쭭׮_Is3D p!2 [4< 1ikdTɟX!GDccv~ѧ11''멬jGnf˖~ TMTQ("Mtg 4+^=ˁOnUiz4@dch:@W9 o24@;>\?8UW^Ngg'Q^ EF?lÇ`-Oz\)[.ƟDx*d`hݤMOdc`IIm0o(N{CT(J,gԄd"핻9p6`ه1y#nGdRYY^aas*])++P577K\D< r:)d5b5,Wc%_|DxM!wbZdD}\@WcNgË́CEEFB$s'BMn" E=eNG ^ֲ/*)1gV`:[ir[G6gv;ee02컷yüש!D(ZZ9yżf" Ey XD?}cÇ'TEgwtmrnZc04miTnCWqY>q@^y)97ND$Eu@:~&OD?ɺH;9cnDyS0{&GsEnS5%Gw\q[hf :W-GUN{ Q&;+?d֬Yv+|l>BN(W$qCh n$EΜk Grt'_>Q_NQT( b':J^4->t"k#iX~s &v4q4Re4QxLFdϾa9N%eA7666rEt8D&`*PJPT(F % {y.]@;DWhto'1wbx0tG"4j1:[,-f$ SI(&#.s$[Ss3U5?<^+яOoDEr/G?nn_iok!! iD#Gkkhϣǯ m`!arϽu;i+ق_?p(SJE$.#Nf ҹ]n =߈~x3W %(ʕL?y:CG~U{EՉ! <|9ל/WhF0`y8}@WUe޼䥒PzQA4%4AUQD:m D E@ (:*,!!{e(.ه o;&2u*}zZ_}^8Y{~QhLp37骴#Gš";l4@@oLPN֯ GCy<`Xs=E$ҁ끽Fif3H>ٲ*U`/vb=qǟ $U *)iw|5׎ XNi'qK.[u~y}y b;JqnL}u= QQ>ciӖҥKhoUotLQ\m۴ů.?pz̞53z   s&oors7KdocZL6ejup?⫱cFƍګ4@T`'PތŋЬysC9" }M9 h dSdJD*3&G^wms%Oޞ8q_eeeѹc?o Ƚ %\mj1I=)H8Z`) OL԰a#ʕ+Ovv.WΥ+q M sI ~Cj`cf*PD 8>m{QL M}6 @C1b0Q %<YvHJo,.xxbLDMa ;GDtS4oт_\^\l#,u+sKSrX\.FyXzc妮]}~=C@TU`GY J\ry48olvĴ:,[;;u&?.hA=AFFV|m@ *̷*<"""ܱYYل_5R10 r뀶XS<;Hb4@vͭ=oZ[ " j$0ٓː[nw<9N>:&wCmVv͚50233 u;R^ٳءaÆ^b: 0* |TBիWge4###̒އ>XO_]B D}Ś5opiↅ\Ts3m~V j40:5Zlj uz9{L_9նM+=J1 x ZgAMF7PRᄄXDy62 C2QuS$IT( 5lH[o'S >-[(KC@ :6Ay񒑙!oizQ@S  DH.# ?Q?_H++t_EwxE~9A-E-q!\W.'5(n l'NM7uOH]<z=x'NsNrQ/c4@즞ŏVbŊ 1 "Iħdy*h|b ҥKM8!Ab]pI6TP ?j߾LJ. #B`ނw8) HojXMMFàA$L"8%K3a8Pj4@س̡ifZ6))<أrE1ͪ *^\ J)5DC_kM*Wf͚T23!|(4@̤:uŗ^,J=zT־8pJ*`%6Mt3,׭b& WB w$%%1-Jq&M2g<צԩWٔWc̚93gnhRTTw81cR? PT j֬EUt܅ D=:#^~+){nnQظq 3+ X`)+VVSꉿ=ŋRÆ gC%Ny3gH=X&sZ(umСΕ:u r:rhMH*C),l IM%11 (5g7wIM1k6aaaWF η~CHj 0qCnJtLɓ'1C]yɄtֈؼys4ԟ#V#XvS%J`0hdd;&St)ʖ)CbbY%%R\9*T(O\"U*WX_s}~pǓ܏n=bիV1ϴצʔH Q+KQN\əorΝ$4#" w}|[];gϞ%#3lUO*$-- <8lX@|{31b$SI2eH]|Zsp7K`υE@җIFfg38!,z7e LO஻d4,x5@.zoc_O>\d82ITd+$ !˙3g9}挜՟ 1 qV_|] '' pw> BVo^}'ۧ>WI>\!IXDEEނTOP9^,fΘ/`07ޘA~z4vi(׀!O/fl߾_=3uߏbc N<%IiӺYYY)::~|kZ5&vҁ WUUch[DD1Q(#= uʉ'9y4٨#XzfKHH`ȑ#uNBr @veD;ng׮/ҭ[w;$0bc(Az N<\>ah8wޛطoEqY7@pfe j֪Ų)d4bKP"&ôz<"ǏDW0:w{b>=5 |';hwgeՀߋ_@,xeT:uD=oWѱcG,$RbKHXJ׉'8~`YLe C͛O&M.Xg-~7KVGܹ3kצ)<-}!7˔.eSxpʔ.-?*=]^dU<0Dѣ@ūQT,HʊUF{Ռhݦ!ST%H)cGeK`=z+W` O"@={̩Sp * ʊO3gͦeV,_1UyoHT| (]VL;z'Oh>3mPǢ%JE.K?a55oUYsҹ{}o2,|1)UTLT#r$~˅Vpa cǎae8`~p |c]+3-G)[oc8n|ɒ@rc3;wyi3rm!@Z\.:u7xD0wq'2/GÆJF{'k=zL.%:ݱchڤ'U'[:0a< XZ߷xo.YG+>shGU2e'((~aW#O?J1C. 䦮v7d:8Dhg˨S>pJ/Ẻu)ل[*!WEyrr8|,pt|Sְ[cN:5.4__n݊4> Q-MX{㏟yhX|աC2_HS_%Kɽ0j eՀl޲S9G1d8VT(Q@bR#F<nڴiE 1|$ K*KR%dc[&qk{3))ׯ?h׾=III8H}pDẂX5+WdϞ=K׮Ԯ]UIe%<v忻Dz;$c%6ٳN^])+qxڥ?PF +:*Ax9r(O!n7uj+Vk:qp:D5>MdYv+V0j|$&UJK?.~7cϓˌ2Yok$}\{u>^{"0 AHM!ȈnDdQ39-\>=(V1sڵC{C8yZ}4hPiN-R3t )3pzQRŒ~jҤ)vXjjp믿vZ3 ]0X*M<_y]/_PQ\Rr'RJUY<6mI8L)Mի>nv~#ٰq#eʖܴ|RrПYcF>֤媚5۹۝z tCwtbbb.XYQUXQnTL:ɥw,Y.J)yu4َ`aȠ%TcfXn L a@,лODx԰p=^H0<顔;Ҏ`U)aVھsN>MTThѲqn@撾 ,x]|$!C&4,TC|DL ۛ.W(WתŮ]ܸm۶\+[lJ  q %HKKcMLTTdA87R2i3ԑ_Xpʡq WɪV 0 [r侇R2wpkmHrzuG0mp< Gϵ-å#9^zA#2fR!!2d?ˠ&ԭWωRj8SpGo߯|{i.o722ҲP**23g6Uv걸oQrePn=(h ,q@%ݺ [_UTm%o /QJ?aWTPQ>pYmT\%W/gi\-ZtR(ʈ>\K\R ;ckUT'@uasoAE²@w,УgpQ=}IT]ʕ+ {Tuz@I@?\rA)9#ذ~g7r3%Kd#,,TQ0 )WZj8 hq@Nrr]n-޽{I8^(6T vn.VjUTYsy'`pY6oc#M4K,LP*\La~23" E``ҥвeK m;>GK:|)%Vadfea '_~9fjժPWkYannu9i;Ur>#UHa#ii\L2t@V  o ܹ#mڶ%?/tѢbcc arΉ7Z_{ ŠU؍.z`.qőWh(RZ||< 8T-@;擝UJIC5q访)FN+ErIV&}  4+9PW(x'h;+ B&zCHW]uRW RJ>x9@KDZT & -#abXt0:Z+|$gQB\364hX`) 1RD.:TV Uo|̐KC%7)}аaC KU NR*1vHfF&TVT^+ԅŔN^~]ř >3LHr y&}7ePd珱 K(''{֭ر3g` wH Jqxذ~}N rmlW^s+DIoK\"L4iGeqxG ;@4@V^C\Kb$I]HO  iڴ)ݻ7+Wz00LyGvO9}f1b8%K5kYVHig̙ >ŋ f&*z5 ~u мys< 8u[n #S~.l;aEhkڴi4nܘ Ⱦ"mkT~8'BYu|4hЀo>e}=@Ulԯ_&=<?8v(kl!hR,_νby Z8p/rA=}-Ciq }>Rl իWORwaQ0 تeV}wl n?Mok?5[naƌ 7xq㞠xx lذ7hdffbF4@̛?.]?Dt2K@ L4PGϞ=7~<ʕ =grLddTX{^)))̝3G֣ Ni`8~ NCD.Ǒ!dd@YM4iB~=+y/iߕVZԬYSo:u,;w\,Y™ӧB?U ɍ-Zhb0 C{"gKoҥkWLJllE[p>ojnݺiۖmѨQ#w$==]l޼O4vG=8#GD=DBbJNo_Ĝ9s-(+K,Gc<ܙI@BI ( ,k/`C\WwUQWE.((XAR2df~焙Ԑ {2g[~{_|Kdɇwy.^z9sS]~-.\]]C SۤIs]w1|҆Rlg쉏zGLwkr$ VN}-jU!::>F~S'uyj+\r.KΘ1gJKKg4r] {)wj $Sy:呓# W~"M+˽ȑ#SɤI8;e7ڵD @€swiyp9Ј/O${}*H)kV5(]%&6^(+\f-oؿ>)S  G .ȝSO=СCE '$!B+L:{";9vӀ8HVF P*~jS8}G6wnUp`rO_7.[]WRsp#cjp`ID'1:IqWK4q&9Β$w[|ZTr'A7|S&Qhwo7n$5W_} u< /7U(2v2/gR r.9MDG8 ׽Hz$$ Ȣe[8駟q<]v=;: [SͥEF%rM7‹/ ??ӇAGiut =@lHηQ +,<4_Ҳv[*%ED$CExa ^awOk.yaix!Cd#06r#A} t)A RIu7,5&Y,f|a„ &%%Dty+WPEEc*RjN`a7h1a1(=HMY iP=~: (sxwάYߧmy9+V6ihOiutf ح6@qxľOQ8Gjm؜|ugȜ v6;L\r'Fs۝B}M$!uOʩuV^+pc=&m}5i3fu=i@.֕ }jN2'p{֗]8}㻬j|@d GƁ.]J(ݼAeиC$7;K ҉U&OEե%W.sJWde3\II&#`3|A[J.~׉͝p`TP{4}19aDG8ڬdλJt:,|gAP;wv*y|U6n+" F6oޱÄ{v=VE k|JL rt{}=ZLti U{q0d|Kkvmow݋\pc!˹퐡VwGrB vnV_K 5׽}cb:w63C(wq{C̽` 4@뽊&sp]C UOKh># f3qB.V'@|g9K!EF.w?!~zv܉'??+Nvok2Q9aYi fRP" <;YN`"ZcQZgfI7ѱ8v^e  gCdwh8 Y`-pOӛ@$~"WQ'x zw$ 'eHY"+@!/ `˄xtIg ih&O˯"EDG6gD θxQVWq:BTo\A;P쿦^zPIjx-9}gቾYxK>pI$[Hc NH\1GJ"?cPJC,Am|ϓH2Bq*YSeÿl-ttJ.W2j>7ч=<>mP}OÂe;Ǐ/QH82ٴi@onrS Sj1QS፩Xj"p"IZHl2o5RWƾ" | 8}g{EO*~}"S|?W^5*v S vD͐OpL_mZ[IC 0~؜!SaOƉOIY \ˈ ܦ"]Pu]1 aM!4 iNV_C b.@zz :aS^ǀw/@SO=,:|O[ ?饡@={Pv8'&jTHqϨ+rtY"ؠ~|ycy?}pI=S%D3 IMMDm}T~#Щ[ESI$_ݟ sʐ0}ȉjqh]kaPhn{}i@5@& <ߒ)Dh`6F* Q`Ձi8x"n*"@䜈&)*4:: %dyNI\R}S1x# ?d2*)kɉO?vfY$+7LE/, 8p<]I$_HpFR-=Lbz]+!N{d, /fA`7oTjS^Y>8ӦӢ.tt*|Aފq˟u)(1|JDO~C.`f.~ "qRф!5iɉ HMLb75 $pysl!](n>ue(+ ]0 _C#d&ɐr{ R.^oV_͋(z1 pܔQF\8.kM&$DUrbH<6 R7.A@&0!y rG2ד3AZY8G3E`^6 In"7w`@j W%ʕ+ٳwꫣcPr4Pr*BF"2{JKiɮ`rhi*]7׉i9@PUxCH9z E~?+?,v̭҇P(SķU)  xW+hitt%"#Neͺ~kӥ#JQ)WnM0*K$!v4yE!'@$J b~FrAB<n)JU%uv xFĿAٟGJqXGLra 2{m.'xB!DG02ToPq8f/fQ""./LL' @KyJ`?-_40. ?цM/wLB|8wYA޹I+Z 6! Z8Lh%-`.6ߋ 1( v(;XvHu #4۸iAz7صk/6Nc.c'M ʢ| A ó/,pO.\$ʃY2&[ۀ@$ eF~U%7 W- 2jQUi>P-n%X/W*ylU_W $A|Irssil?+::%[rtDZqH],S\Z+[+) ﺌONLt$B?z @H$ ~]Nȅa. IM>%3"{DNo#`9U(ƃ)_1[NHq/b[J!Hv*Jc[j`@lM=V"A`C|qiY"|9d,wy1c ^rŻm*e|D7x7|V`Psxo7pڀ˭1ų{U&z- 1@+dQSL!r\"VHa//jWy/Qr8 0sj?Y|l6)ݻWN; VmNZ'5q;y ]&[`lٺOSZVFG.?&CzI~ @ʢ?8 $+ρ "58h XP b8D )!Ƞ\W@`-t+>gh`]LlJVTi8.M"ROYḅ>*#P_@bb""bpB6`-3)Q!1> fyqp (vdj"|YyםSݫ3zһGgzk?{j?#"|{U*"9t +#VΘ/ԓ2d?9T0xO7y@ࡋD쁲gPt0m1N@E!]{쑖ߒ`ѢeeLqFNOTL#(2Ƥ<[@ Y!}>*ZB8G  s}a 0vwW_p] AP!@P! n)ƒ<U:Jy͛:tDn.Is=#̙3G9"?N^}"@l'#\TPVGYvZ PdJIĹ`쁠C^" ޣī~'+zߘ#44(wgD/++$5h /p! PWW)S駟 uV4جB >#obCzBMRZ@Pa%2hQ=\Rz<!aD`?֕)v%#* ^٥ BƍQ C=$m0{R\;oEUq@pV1tPF&?_ ?q@{`e DP$< n=SRXj{+zD BZ2'SU MS@%K|ً Vgu›Dnz˛Ҥ"3֮]'`)MSX`vFY {z5-A\3 u$#p-_ ,P*g߿;i$>\"Qe"] E޳W@,PWD}կ{Ե:Q>M!]vIrȨU9m鱨V !z>1e'g%P?`r~?eBqbZ9FOߋ)=<#O.orGAJ!g{ghYҙU\|"/Ic=L4b ErN]+J˽xf+dZqf@TUaWE"/PM"Mae31J.=lA @4dHJ(N<c:mf5*-xAƗh%WLL 3gΔCG-ǽ&M_N?t~[#bD nk *X[rk#oBc6((Ab2IGs,YE΀SRf"$^%ρjuQ?+kz 1f^Ѕf ,m{sQ Ut~ꫯ's%ADmp#IV^GVSX@ֺ7x߿]EnOMq "q6m/HqPUUɕW^|#I~cV1@OglN\z^B޶8x x<R]Xv3`>#?I=D L^)x9?Nly/<.<"f퓺CqM>] UUU88pz+˖-`0prcl"w)RPm(APB]{ô&݆Q(ݙ8Xv-͞7Nv$ItP`-S AGJ^[L@pa.;f18/M"YD~ 7_DWODU_Aw+ (Ob- yFHeɬrP=LB6Q䒃or`X>^֭[w#5Հj.e~!4BK"p}jz. {s*tkI>,"K  l`hjG AK>1#Gh,p+v5-+Kg2#zH&24Ls*6?991D6_QE =ޖ4C˒W)40x94D DdT+F BcD~~<4QCxE 0*6Hb:O)rݨ7 ndIjj,rB1]%bT|~b(~MZv1V>G$8dD5kUX&M ~r Џ2 X G6@Xc``ٝrzOQ爋 J"gy) $UU'^u!UeI0`b-y`6G|z]OzH &M"oH*XFºBz( ҏ.#qnW0*<2+w,rPMڕ,u0udD Nr믘\ ~b5@l?r!C?#K"`+u~M.K`gE"N{fإ Xƀ"CH%"DBv6HA^D>{›{79n2َT/y?ĭH vݪGŇZ4GM""zXxPP$ J(O-ty_ρ,PXQ<+ "]Ybw+CdmSDH':}wq F; bWCߺ6@[`-d]jNþuݰZp5]dM"--1S]$D" !(!$)U<;*C ɑL?/9z:"U<(*(@ͣ#(mH:\G.Lr_q=kz8o36M"3@]2fn%R t0T @B>{˟Fˋ(z 햰(;@YAPߘYCMrB]QFXV#'kIkr7Hc@D4\-W<[&_([惠pwmw bMr&iZ4"k}@]X7BU-_Q RG y@f1,_QWӹ坃Tm$"ф&_$"+rsrrDt31t2xJYhцLC.w{hcN_{gY맪7un˶,KV',laIBlda@f%a``b ː dBx_by.k_ZO9}TJVzΩ}*:>'O NE2 &TJ< .!cW9]X>O$=/NKI%`j-_t/M_Yn=l'@rel̆%%%mXS#h7r4a$I"MȲ,Of5_kettx#PX%)BgB?HBYn[_Jt iQE1;b;A /ٵߓȿ' pmQ+b/@8;ޫg$L)# Dr+Ν;vB, Z$7'x+ <LJF^P$YcY}m`{`=U/a⽺Df@ 2mK?Z٧JoVx{6Ddw BrpF ᅴHdt +2WCJfĠP'Iw }G s`KsZ śE ˼Ub#N%9:0]^ae?my Ď~rřgߏDm6> yIJJ/Kb$@潑nFm KB#{ ?w9ɡ(~3J5x v|FPoQ/Oq?]B>8opx!`anAc4.כ0gD K,6?5/C#Cqu趆It/kxH&*m| O# ; d34)9b%RYsN;k%&Ud|b1\ټy3[nٞce@MwP."H7 c376 3.]"ߴ`Y55,x.vRC|/ٚ]+pe/l,qm/jX[΋ߧȖ`0Eqz~\zU7%Ϫh)z{8'8}je7_% IA,%`(7-%ڜ@f/_3LIqU/!F~QP?5lXt)'Ď~A/d&|믿$@\~ZDv$?8'f/:'C?f{l˵39,qV@Rc3JMмv5RԿs-qxE0e_ fM۸9%/86(b]ZF_Q(䀭><>o^F^L! U8y=,o^K,ӽO>UdVVy3G'" !B gci)ؘ + c~WPrxRje-'ȑ#X`4cxWW*w RWfyKvKXNKNEgqkXgzqy ZR;LВ1mbpK/}a $|Mqw ۼX " ;d߀o7r2Er(RUxXÑ {o Xx8O}J서/J<4L XvV`ٗN ?=qT{v*̻0P<)B :Q!zmɎ M I#7Bp{Ȟ]qoca[~wr Z?sSMhIH)}8t0"Gf3> #HV |/9 #/{Iތf-'Ka謒|m*ֿ܏㬲!~k_#Ja"+'ד0 w&yL"Sy:F:2p R #œ@i&<lG%xh6tV)XW s2ϣ9r}F-e,6t͕A#|`Æ vm<7Rr;$s\r48R#;Gey: @+d/#_ikxֈH3 kYY@{Yq ^ e+~KbַW(dj,piݾDNYP{ 4 *}}I*ưN%Z&C |Ur9*Wi6ubV]CoOYz^>^Twxg?k18+?RP@SmFI V\&}_i3DE%TFS\jD/zf8':鞷O*)˚Nqp=<)*(Bnpسg>VO1_ M5J7еGZJXq WápG^i at5`@TQ>*4u&p nru* pL7Zn[z!l zz8 d}A:}F,1[8Lܤˣ3(31BUG&C@{ͥ0:f%YIhZ+*ʕ+ۿ[9bV/o^{8 //GpѴ0|R޹16?andW J黉|g] DLXH1tnwuqDAQ'9 % J ewm+WS|T #R轐jVfB @e6n(d_uY"TVV.37[o%yzzz8]X?i} "K^M}%Vxʴ^}1a_ t٥vZ' Rb xnd[K#9'J~`bւU\)4qKKYr?62~FO%B$˖-K_PRR"LO% ƄhT- '3!>9MÃ^҄p)]fonXExdzO2ؠ"$z'(z* AE(`ĺ@;  3vʤ{RY ~jR)Y<~yU;C4ew%gD(H07K!9S(MuX8, xHtqhF/+e{ 0٨Qv+J sZ`nT+ZW;@GgP^a ġW^o;iy+Autl7 KcyB X1ۓ-o#d棔*/ɕ85X< 焅D(_;"|V .i*h_C<0 ~!zg`5Da=9 !J@qL4TnI hYIPϮD*ńP`bjAT~Vf E7p2U*Le"XIMq-8i*!9f䝡M~,"H"@J.޽vPT8k+ iV`yX2:f_ZGGK5InAMA  oII2npgv0%C@%Q1/04ʵe@u+I҄@CdP| "!6Vc'ѝ D#$x/@Zd$B- H^peYn3 2hjV"KJrhai4~obٗq%ei*q|O=]*X[p2>]=H|Z >L fY{l|4.YA^:4LPQ`^}eN45'ҤLuYgOx9}^&g CF_VlIq )Ce-{cehZ \B+$E`l`jQ†(?#U} `lzYʘjfܪ$fIDؘ]Iɟc_8ŁÏ?*˗XkD`(~L{b=FЛ 2šJebs"C1,rk+J+) gr6X, 5ٞIdf:+%,EI U NDINT ԐUܗ@G<&A nEq"9s@=f*DžPO1.˚|$dd1IlfF2#-t,nDlXuʲQs c_$nDT vq"F@N]"o\d*wX.$bʺ|/fN?E-pY;1P< yȒ L>T|ͅhnzϙTJz;ʙ#'uyLPHid-X9^W Xq]YFP)?ėNq'!+[ WP d%}$ >&"Ȩ/q1 O f(; \ \a oR(}J",D݇V2){b}o[Łó.ajÃf(AĕT$BRZv-=4I盍@ʐ\*XKQ D(?bkھ{7_ sK8ɸƀq@Y ϸ j+4-fIMY:-.I'~IܪˣPʀK58_3#,BP8*r8(5hK@7%> 0j!25?Lj`=S@f64,o"ȓt_Y~ǁ73ǿ |AG G Bo6kpeX IP"ǓtE=WɑIw#'.h0J|"|\]fA@ 2qk*Ļ,)3c#~i w9%v$`#ktJ걆`UcT"\ӓXb9t2<,QG=4d1>7nrUbvpHyNusd*oG 6(B&j,dq!"X:$-4 8f$O^ł`+G8Mrg>pV%cll>ao`AR#Ͽ8$4<f#dRQ )Y4wJ!3w ,4`Ӑ|=X?I*g!,*>yyw 65| IyN! D\ЮFdol^ Ha"Iܐ~UDp)yN s-mKk8MFcJR+.Z: 0m|&\ED.ۆr(M@KV~^F,&>f=u#'F!*H E|N]lƁ<[($K2.~ +ORY:jB Ѣy/_uޥ|-IN`BN'dR (JI~rWN)2eʐdPM *ɔLjxQ g22<[I9.ZH*8:>qr{?AC)\NL-.wB 9 qÁ+gA E#S3r M'UU#0XҺc|ѣhpR 2%]4TO_p@?}>vX)f.@QjjW,AkF"%iYI_+n`?nbđȳ(=0}))txNٳI/@8#L6.&v0orF$vn&2`4-- '\ Q8 $@Hf̓D4Вw&.lb<#YđIMLUU4s_s<7^]/1G ^,j2 W"Z rNUػs%#~2a]*6qAG3BVQW;P,vcw 'DCxHp$䂍ou[)O43tϊHC82 H' (h\KU0K}x%q@% HXprZ 0-RQ}e}{W06'oHp.(y#'j&i\rI 4 $Czغw p7p$ؔnH!.DRa<"cLy11<|JIq%E82_.:O{o:4#@>< `Z[e=V2>%~+v[817_"A-&hñl߱cK+f{x&1/[3!]pؒY:U+~_+A|}M<<&|xs*il&tivmn$|B4DTUj&1|Tc@.3\qPJ`@iCcK/=}0q#8LKř!.$ UtuW>ˣ"3~pp%fdID&kYL<9)P5 3H ;Q2W PĠ ?|o1%hG LBH>%P;)D_! !͸TUC"]̎m8v25Ι!_ܓ{{Q.U/fPWY9qd.3''_#3Hd% ia#ʰqg,iv! 0CS % q4#&`=\ O[]G$z <@(07JqJQDrNb'15y 28C3 |MG?88qmge@qZ@@W1Rqh/:8"> 4% dUU` .1G L C4I xxz5j#1Հ^7;N;?3yIENDB`go-gir-generator-master/lib.in/cairo-1.0/types_386.go000066400000000000000000000002121414263242200223510ustar00rootroot00000000000000// Created by cgo -godefs - DO NOT EDIT // cgo -godefs types.go package cairo type Glyph struct { Index uint32 X float64 Y float64 } go-gir-generator-master/lib.in/cairo-1.0/types_amd64.go000066400000000000000000000002121414263242200227440ustar00rootroot00000000000000// Created by cgo -godefs - DO NOT EDIT // cgo -godefs types.go package cairo type Glyph struct { Index uint64 X float64 Y float64 } go-gir-generator-master/lib.in/config.json000066400000000000000000000020041414263242200210260ustar00rootroot00000000000000{ "disguised-types": [ "gdk.Atom" ], "word-subst": { "hadjustment" : "HAdjustment", "vadjustment" : "VAdjustment", "hborder" : "HBorder", "vborder" : "VBorder", "hscroll" : "HScroll", "vscroll" : "VScroll", "halign" : "HAlign", "valign" : "VAlign", "hline" : "HLine", "vline" : "VLine", "hexpand" : "HExpand", "vexpand" : "VExpand", "uri" : "URI", // Uniform Resource Identifier "uris" : "URIs", "id" : "ID", // Identity Document "ids" : "IDs", "gicon" : "GIcon", // gio.Icon "fd" : "FD", // File Descriptor "im" : "IM", // Input Method "mime" : "MIME", // Multipurpose Internet Mail Extensions "rgba" : "RGBA", "rgb" : "RGB", "hsv" : "HSV", "ppd" : "PPD", // PostScript Printer Description "dpi" : "DPI", // Dots Per Inch "lpi" : "LPI", // Lines Per Inch "xy" : "XY", "yrange" : "YRange", "ui" : "UI", // User Interface "wmclass" : "WMClass", // Window Manager Class "qclass" : "QClass", "qname" : "QName", "qregion" : "QRegion" } }go-gir-generator-master/lib.in/gdk-2.0/000077500000000000000000000000001414263242200177345ustar00rootroot00000000000000go-gir-generator-master/lib.in/gdk-2.0/config.json000066400000000000000000000036251414263242200221020ustar00rootroot00000000000000{ "namespace": "Gdk", "version": "2.0", "blacklist": { "objects": [ "AppLaunchContext" ], "functions": [ "add_option_entries_libgtk_only", "color_alloc", "color_black", "color_change", "color_parse", "color_white", "event_get", "event_get_graphics_expose", "event_handler_set", "event_peek", "event_request_motions", "event_send_client_message_for_display", "font_from_description", "font_from_description_for_display", "font_load", "font_load_for_display", "keyboard_grab_info_libgtk_only", "input_add_full", "threads_add_idle_full", "threads_add_timeout_full", "threads_add_timeout_seconds_full", "colors_alloc", "colors_free", "drag_get_protocol", "drag_get_protocol_for_display", "draw_gray_image", "draw_indexed_image", "draw_rgb_32_image", "draw_rgb_32_image_dithalign", "draw_rgb_image", "draw_rgb_image_dithalign", "draw_text_wc", "free_compound_text", "mbstowcs", "pointer_grab_info_libgtk_only", "property_change", "property_get", "query_visual_types", "selection_property_get", "string_extents", "string_to_compound_text", "string_to_compound_text_for_display", "text_extents", "text_extents_wc", "text_property_to_text_list", "text_property_to_text_list_for_display", "text_property_to_utf8_list", "text_property_to_utf8_list_for_display", "text_width_wc", "utf8_to_compound_text", "utf8_to_compound_text_for_display", "wcstombs" ] }, "method-blacklist": { "Colormap": [ "alloc_colors" ], "Device": [ "get_axis", "get_key", "get_state" ], "Drawable": [ "set_data" ], "KeyboardGrabInfo": [ "libgtk_only" ], "Keymap": [ "add_virtual_modifiers", "get_entries_for_keycode", "map_virtual_modifiers" ], "Region": [ "get_rectangles" ], "Window": [ "get_decorations", "get_deskrelative_origin" ] } } go-gir-generator-master/lib.in/gdk-2.0/gdk.go.in000066400000000000000000000004211414263242200214320ustar00rootroot00000000000000package gdk /* #include "gdk.gen.h" [<.g_object_ref_unref>] [<.g_error_free>] [<.g_free>] */ import "C" import "unsafe" import "errors" import ( "gobject/gobject-2.0" "gobject/cairo-1.0" "gobject/gdkpixbuf-2.0" "gobject/pango-1.0" ) [<.go_utils>] [<.go_bindings>] go-gir-generator-master/lib.in/gdk-3.0/000077500000000000000000000000001414263242200177355ustar00rootroot00000000000000go-gir-generator-master/lib.in/gdk-3.0/config.json000066400000000000000000000011031414263242200220700ustar00rootroot00000000000000{ "namespace": "Gdk", "version": "3.0", "blacklist": { "objects": [ "AppLaunchContext" ], "functions": [ "add_option_entries_libgtk_only", "threads_add_idle", "threads_add_timeout", "threads_add_timeout_seconds", "pango_context_get", "pango_context_get_for_screen", "event_handler_set", "atom_intern", "atom_intern_static_string", "color_parse", "event_get", "event_peek", "event_request_motions" ] }, "method-blacklist": { "Keymap": [ "get_entries_for_keycode" ], "Display": [ "get_app_launch_context" ] } } go-gir-generator-master/lib.in/gdk-3.0/gdk.go.in000066400000000000000000000003571414263242200214430ustar00rootroot00000000000000package gdk /* #include "gdk.gen.h" [<.g_object_ref_unref>] [<.g_free>] */ import "C" import "unsafe" import ( "gobject/gobject-2.0" "gobject/cairo-1.0" "gobject/gdkpixbuf-2.0" "gobject/pango-1.0" ) [<.go_utils>] [<.go_bindings>] go-gir-generator-master/lib.in/gdkpixbuf-2.0/000077500000000000000000000000001414263242200211525ustar00rootroot00000000000000go-gir-generator-master/lib.in/gdkpixbuf-2.0/config.json000066400000000000000000000014131414263242200233110ustar00rootroot00000000000000{ "namespace": "GdkPixbuf", "version": "2.0", "whitelist": { "callbacks": [] }, "blacklist": { "objects": [ "PixbufSimpleAnimIter" ], "functions": [ "pixbuf_new_from_stream_async", "pixbuf_new_from_stream_at_scale_async" ] }, "method-blacklist": { "Pixbuf": [ "gettext", "new_from_data", "new_from_stream", "new_from_stream_at_scale", "new_from_stream_async", "new_from_stream_at_scale_async", "new_from_stream_finish", "save_to_stream_finish", "new_from_inline", "get_file_info", "get_pixels", "save_to_bufferv", "save_to_callbackv", "savev" ], "PixbufAnimation": [ "get_iter" ], "PixbufAnimationIter": [ "advance" ], "Pixdata": [ "serialize", "deserialize", "to_csource" ] } } go-gir-generator-master/lib.in/gdkpixbuf-2.0/gdkpixbuf.go.in000066400000000000000000000023041414263242200240700ustar00rootroot00000000000000package gdkpixbuf /* #include "gdkpixbuf.gen.h" [<.g_object_ref_unref>] [<.g_error_free>] [<.g_free>] #cgo pkg-config: gdk-pixbuf-2.0 */ import "C" import "unsafe" import "errors" // package dependencies import ( "gobject/gobject-2.0" "gobject/gio-2.0" ) [<.go_utils>] [<.go_bindings>] func (this *Pixbuf) Save(filename0, type0 string, args ...string) error { if len(args) & 1 != 0 { panic("the number of arguments should be even (key/value pairs)") } nkeyvalues := len(args) / 2 + 1 keys := make([]*C.char, 0, nkeyvalues) values := make([]*C.char, 0, nkeyvalues) for i := range args { cstr := C.CString(args[i]) defer C.free(unsafe.Pointer(cstr)) if i & 1 == 0 { keys = append(keys, cstr) } else { values = append(values, cstr) } } keys = append(keys, nil) values = append(values, nil) filename1 := C.CString(filename0) defer C.free(unsafe.Pointer(filename1)) type1 := C.CString(type0) defer C.free(unsafe.Pointer(type1)) var err1 *C.GError C.gdk_pixbuf_savev(this.InheritedFromGdkPixbuf(), filename1, type1, &keys[0], &values[0], &err1) var err2 error if err1 != nil { err2 = ((*_GError)(unsafe.Pointer(err1))).ToGError() C.g_error_free(err1) } return err2 } go-gir-generator-master/lib.in/gio-2.0/000077500000000000000000000000001414263242200177455ustar00rootroot00000000000000go-gir-generator-master/lib.in/gio-2.0/.gitignore000066400000000000000000000000341414263242200217320ustar00rootroot00000000000000gio.gen.c gio.gen.h gio.go go-gir-generator-master/lib.in/gio-2.0/config.json000066400000000000000000000120331414263242200221040ustar00rootroot00000000000000{ "namespace": "Gio", "version": "2.0", "whitelist": { "callbacks": [ "FileProgressCallback", "DesktopAppLaunchCallback", "AsyncReadyCallback" ], "functions": [ "app_info_get_all", "app_info_get_all_for_type", "app_info_get_default_for_type", "app_info_get_default_for_uri_scheme", "app_info_get_fallback_for_type", "app_info_get_recommended_for_type", "app_info_launch_default_for_uri", "app_info_reset_type_associations", "file_new_for_commandline_arg", "file_new_for_commandline_arg_and_cwd", "file_new_for_path", "file_new_for_uri", "file_new_tmp", "file_parse_name" ], "objects": [ "Cancellable", "Icon", "Permission", "MountOperation", "MenuModel", "MenuAttributeIter", "MenuLinkIter", "EmblemedIcon", "AppLaunchContext", "Emblem", "Settings", "FileMonitor", "FileInfo", "InputStream", "FileOutputStream", "FileInputStream", "OutputStream", "IOStream", "FileIOStream", "FileEnumerator", "DesktopAppInfo", "VolumeMonitor" ], "structs": [ "FileAttributeInfo", "FileAttributeInfoList", "FileAttributeMatcher", "ActionEntry", "SettingsBackend", "SettingsSchema", "SettingsSchemaKey", "SettingsSchemaSource", "MountIface", "OutputVector" ], "interfaces": [ "Seekable", "Drive", "Mount", "Volume", "Icon", "File", "AppInfo", "Action", "ActionGroup", "AsyncResult", "ActionMap" ] }, "method-whitelist": { "File": [ "copy", "move", "delete", "get_uri", "monitor", "append_to", "append_to_async", "append_to_finish", "copy_attributes", "copy_finish", "create", "create_async", "create_finish", "create_readwrite", "create_readwrite_async", "create_readwrite_finish", "delete_async", "delete_finish", "dup", "eject_mountable", "eject_mountable_finish", "eject_mountable_with_operation", "eject_mountable_with_operation_finish", "enumerate_children", "enumerate_children_async", "enumerate_children_finish", "equal", "find_enclosing_mount", "find_enclosing_mount_async", "find_enclosing_mount_finish", "get_basename", "get_child", "get_child_for_display_name", "get_parent", "get_parse_name", "get_path", "get_relative_path", "get_uri_scheme", "has_parent ", "has_prefix", "has_uri_scheme", "hash", "is_native", "load_contents", "load_contents_async", "load_contents_finish", "load_partial_contents_finish", "make_directory", "make_directory_async", "make_directory_finish", "make_directory_with_parents", "make_symbolic_link", "measure_disk_usage_finish", "has_parent", "monitor_directory", "monitor_file", "mount_enclosing_volume", "mount_enclosing_volume_finish", "mount_mountable", "mount_mountable_finish", "open_readwrite", "open_readwrite_async", "open_readwrite_finish", "poll_mountable", "poll_mountable_finish", "query_default_handler", "query_exists", "query_file_type", "query_filesystem_info", "query_filesystem_info_async", "query_filesystem_info_finish", "query_info", "query_info_async", "query_info_finish", "query_settable_attributes", "query_writable_namespaces", "read", "read_async", "read_finish", "replace", "replace_async", "replace_contents", "replace_contents_async", "replace_contents_finish", "replace_finish", "replace_readwrite", "replace_readwrite_async", "replace_readwrite_finish", "resolve_relative_path", "set_attribute", "set_attribute_byte_string", "set_attribute_int32", "set_attribute_int64", "set_attribute_string", "set_attribute_uint32", "set_attribute_uint64", "set_attributes_async", "set_attributes_finish", "set_attributes_from_info", "set_display_name", "set_display_name_async", "set_display_name_finish", "start_mountable", "start_mountable_finish", "stop_mountable", "stop_mountable_finish", "supports_thread_contexts", "trash", "trash_async", "trash_finish", "unmount_mountable", "unmount_mountable_finish", "unmount_mountable_with_operation", "unmount_mountable_with_operation_finish" ], "AppInfo": [ "launch", "create_from_commandline", "add_supports_type", "can_delete", "can_remove_supports_type", "delete", "dup", "equal", "get_commandline", "get_description", "get_display_name", "get_executable", "get_icon", "get_id", "get_name", "get_supported_types", "launch_uris", "remove_supports_type", "set_as_default_for_extension", "set_as_default_for_type", "set_as_last_used_for_type", "should_show", "supports_files", "supports_uris" ] }, "method-blacklist": { "DesktopAppInfo":[ "launch_uris_as_manager", "launch_uris_as_manager_with_fds" ], "Cancellable": [ "connect", "source_new" ], "Application": [ "get_dbus_connection" ], "Settings": [ "get_mapped", "new_full", "new_with_backend", "new_with_backend_and_path" ] } } go-gir-generator-master/lib.in/gio-2.0/gdk_workaround.go000066400000000000000000000024361414263242200233210ustar00rootroot00000000000000package gio // #include // #include // void free(void*); // #cgo pkg-config: gdk-3.0 import "C" import "unsafe" import "pkg.deepin.io/gir/gobject-2.0" type GdkAppLaunchContext struct { AppLaunchContext } func (this0 *GdkAppLaunchContext) GetStaticType() gobject.Type { return gobject.Type(C.gdk_app_launch_context_get_type()) } func (this0 *GdkAppLaunchContext) SetTimestamp(t uint32) *GdkAppLaunchContext { var this1 *C.GdkAppLaunchContext if this0 != nil { this1 = (*C.GdkAppLaunchContext)(this0.InheritedFromGAppLaunchContext()) } variable0 := C.guint32(t) C.gdk_app_launch_context_set_timestamp(this1, variable0) return this0 } func (this0 *GdkAppLaunchContext) SetIconName(iconName string) *GdkAppLaunchContext { var this1 *C.GdkAppLaunchContext var value0 *C.char if this0 != nil { this1 = (*C.GdkAppLaunchContext)(this0.InheritedFromGAppLaunchContext()) } value0 = _GoStringToGString(iconName) defer C.free(unsafe.Pointer(value0)) C.gdk_app_launch_context_set_icon_name(this1, value0) return this0 } func GetGdkAppLaunchContext() *GdkAppLaunchContext { ret1 := C.gdk_display_get_app_launch_context(C.gdk_display_get_default()) var ret2 *GdkAppLaunchContext ret2 = (*GdkAppLaunchContext)(gobject.ObjectWrap(unsafe.Pointer(ret1), false)) return ret2 } go-gir-generator-master/lib.in/gio-2.0/gio.go.in000066400000000000000000000006441414263242200214630ustar00rootroot00000000000000package gio /* #include "gio.gen.h" [<.g_list_funcs>] [<.g_object_ref_unref>] [<.g_error_free>] [<.g_free>] #cgo pkg-config: gio-2.0 */ import "C" import "unsafe" import ( "pkg.deepin.io/gir/gobject-2.0" "pkg.deepin.io/gir/glib-2.0" ) [<.go_utils>] [<.go_bindings>] func (gs *Settings) GetSchema() *SettingsSchema { var gsSchema *SettingsSchema gs.GetProperty("settings-schema", &gsSchema) return gsSchema } go-gir-generator-master/lib.in/gio-2.0/gio_test.go000066400000000000000000000002441414263242200221110ustar00rootroot00000000000000package gio import "testing" func TestAppInfo(t *testing.T) { apps := AppInfoGetAll() for _, app := range apps { app.GetSupportedTypes() app.GetIcon() } } go-gir-generator-master/lib.in/glib-2.0/000077500000000000000000000000001414263242200201045ustar00rootroot00000000000000go-gir-generator-master/lib.in/glib-2.0/.gitignore000066400000000000000000000000361414263242200220730ustar00rootroot00000000000000glib.gen.c glib.gen.h glib.go go-gir-generator-master/lib.in/glib-2.0/config.json000066400000000000000000000022671414263242200222530ustar00rootroot00000000000000{ "namespace": "GLib", "version": "2.0", "whitelist": { "objects": [], "structs": [ "Bytes", "TimeVal", "DateTime", "TimeZone", "KeyFile", "Variant", "VariantType", "PollFD" ], "functions": [ "get_user_cache_dir", "get_user_config_dir", "get_user_data_dir", "get_user_runtime_dir", "get_user_special_dir", "get_system_data_dirs", "get_system_config_dirs", "get_current_dir", "get_home_dir", "get_tmp_dir" ], "callbacks": [ // callbacks depend on gobject-2.0, glib shouldn't depened on gobject-2.0 // "DestroyNotify" ] }, "blacklist": { "constants": [ // two constants, automatic renaming facility fails to deal with them // (produces redeclaration) "CSET_A_2_Z", "CSET_a_2_z" ] }, "method-blacklist": { "Bytes": [ "unref_to_array" ], "Variant": [ // hasn't implement error to GError converting "parse_error_print_context", "new_bytestring", "new_from_bytes", "get_data_as_bytes", // cannot use notify1 (type unsafe.Pointer) as type _Ctype_GDestroyNotify in function argument "new_from_data" ] } } go-gir-generator-master/lib.in/glib-2.0/fixwarning.go000066400000000000000000000002001414263242200225770ustar00rootroot00000000000000package glib import "C" import "unsafe" //export _GLib_go_callback_cleanup func _GLib_go_callback_cleanup(unsafe.Pointer) { } go-gir-generator-master/lib.in/glib-2.0/glib.go.in000066400000000000000000000004751414263242200217630ustar00rootroot00000000000000package glib /* #include "glib.gen.h" extern void g_key_file_free(GKeyFile*); #cgo pkg-config: glib-2.0 */ import "C" import "unsafe" [<.go_utils_no_cb>] [<.go_bindings>] //workaround func (this0 *KeyFile) Free() { var this1 *C.GKeyFile this1 = (*C.GKeyFile)(unsafe.Pointer(this0)) C.g_key_file_free(this1) } go-gir-generator-master/lib.in/glib-2.0/keyfile_test.go000066400000000000000000000056341414263242200231320ustar00rootroot00000000000000package glib import ( C "gopkg.in/check.v1" "os" "strings" "testing" ) type glib struct{} func Test(t *testing.T) { C.TestingT(t) } func init() { C.Suite(&glib{}) } var desktop_file = ` [Desktop Entry] Categories=GNOME;GTK;Utility;System;TerminalEmulator; Comment=Use the command line Comment[am]=የ ትእዛዝ መስመር ይጠቀሙ Comment[ar]=إستعمال سطر الأوامر Comment[zh_CN]=使用命令行 Keywords=shell;prompt;command;commandline; Keywords[an]=enterprite ;indicador;comando;linia de comandos; Keywords[ar]=طرفية;صدفة;سطر;أوامر; Keywords[as]=শ্বেল;প্ৰমপ্ট;কমান্ড;কমান্ডশাৰী; Keywords[zh_CN]=shell;prompt;command;commandline;命令;提示符;命令行; Name=Deepin Terminal Name[es_AR]=Terminal Deepin Name[ja]=ターミナル StartupNotify=true TryExec=deepin-terminal Type=Application [NewQuake Shortcut Group] Exec=deepin-terminal --quake-mode Name=New Quake Window [NewWindow Shortcut Group] Exec=deepin-terminal Name=New Window Name[vi]=Cửa sổ Mới Name[zh_CN]=新建窗口 Name[zh_TW]=開啟新視窗 ` func checkDesktopFile(f *KeyFile, c *C.C) { { r, err := f.GetBoolean("Desktop Entry", "StartupNotify") c.Check(err, C.Equals, nil) c.Check(r, C.Equals, true) } { r, err := f.GetString("Desktop Entry", "Type") c.Check(err, C.Equals, nil) c.Check(r, C.Equals, "Application") } { l, r, err := f.GetStringList("Desktop Entry", "Keywords") c.Check(err, C.Equals, nil) c.Check(uint64(l), C.Equals, uint64(4)) c.Check(strings.Join(r, ";"), C.Equals, "shell;prompt;command;commandline") } { r, err := f.GetLocaleString("NewWindow Shortcut Group", "Name", "zh_CN") c.Check(err, C.Equals, nil) c.Check(r, C.Equals, "新建窗口") os.Setenv("LANGUAGE", "zh_TW") r, err = f.GetLocaleString("NewWindow Shortcut Group", "Name", "\x00") c.Check(err, C.Equals, nil) c.Check(r, C.Equals, "開啟新視窗") } { l, r, err := f.GetLocaleStringList("Desktop Entry", "Keywords", "zh_CN") c.Check(err, C.Equals, nil) c.Check(uint64(l), C.Equals, uint64(7)) c.Check(strings.Join(r, ";"), C.Equals, "shell;prompt;command;commandline;命令;提示符;命令行") } { _, err := f.GetDouble("Can'tFind", "Name") c.Check(err, C.ErrorMatches, "Key file does not have group 'Can'tFind'") } } func (*glib) TestKeyFileFromFile(c *C.C) { f := NewKeyFile() ok, err := f.LoadFromFile("testdata/deepin-terminal.desktop", KeyFileFlagsKeepTranslations) if !ok || err != nil { c.Fatal(ok, err) } checkDesktopFile(f, c) } func (*glib) TestUserDirs(c *C.C) { dirs := []UserDirectory{ UserDirectoryDirectoryDesktop, UserDirectoryDirectoryDocuments, UserDirectoryDirectoryDownload, UserDirectoryDirectoryMusic, UserDirectoryDirectoryPictures, UserDirectoryDirectoryPublicShare, UserDirectoryDirectoryTemplates, UserDirectoryDirectoryVideos, } for _, d := range dirs { GetUserSpecialDir(d) } } go-gir-generator-master/lib.in/glib-2.0/misc.go000066400000000000000000000002501414263242200213630ustar00rootroot00000000000000package glib /* #include void _run() { g_main_loop_run(g_main_loop_new(0, FALSE)); } #cgo pkg-config: glib-2.0 */ import "C" func StartLoop() { C._run() } go-gir-generator-master/lib.in/glib-2.0/testdata/000077500000000000000000000000001414263242200217155ustar00rootroot00000000000000go-gir-generator-master/lib.in/glib-2.0/testdata/deepin-terminal.desktop000066400000000000000000000222621414263242200263710ustar00rootroot00000000000000[Desktop Entry] Categories=GNOME;GTK;Utility;System;TerminalEmulator; Comment=Use the command line Comment[am]=የ ትእዛዝ መስመር ይጠቀሙ Comment[ar]=إستعمال سطر الأوامر Comment[cs]=Používejte příkazový řádek Comment[da]=Brug kommandolinien Comment[de]=Kommandozeile benutzen Comment[de_DE]=Kommandozeile benutzen Comment[el_GR]=Χρησιμοποιήστε τη γραμμή εντολών Comment[en]=Use the command line Comment[es]=Uso de linea de comando Comment[es_419]=Usar la linea de comandos Comment[es_AR]=Usar linea de comandos Comment[es_CL]=Utilice la línea de comandos Comment[es_ES]=Usar linea de comandos Comment[es_PE]=Utilice la línea de comandos Comment[fi]=Käytä komentoriviä Comment[fr]=Utiliser la ligne de commande Comment[he]=השתמש בשורת פקודה Comment[hu]= A parancssor használata Comment[hy]=Օգտագործել հրամանների տողը Comment[id_ID]=Gunakan perintah text Comment[it]=Usa linea di comando Comment[ja]=コマンドラインを使用する Comment[ms]=gunakan garis perintah Comment[nl]=Opdrachtprompt gebruiken Comment[pl_PL]=Użyj wiersza poleceń Comment[pt_BR]=Usar a linha de comando Comment[pt_PT]=Utilizar o terminal Comment[ro]=Folosește linia de comandă Comment[ru]=Использование командной строки Comment[sk]=Používajte príkazový riadok Comment[sl]=Uporabi ukazno vrstico Comment[tr]=Komut satırı kullan Comment[zh_CN]=使用命令行 Comment[zh_HK]=使用命令列 Comment[zh_TW]=使用命令列介面 Exec=deepin-terminal Icon=deepin-terminal Keywords=shell;prompt;command;commandline; Keywords[an]=enterprite ;indicador;comando;linia de comandos; Keywords[ar]=طرفية;صدفة;سطر;أوامر; Keywords[as]=শ্বেল;প্ৰমপ্ট;কমান্ড;কমান্ডশাৰী; Keywords[be]=абалонка;загадны радок;загад; Keywords[ca@valencia]=intèrpret d'ordes;indicador;orde;línia d'ordes; Keywords[ca]=intèrpret d'ordres;indicador;ordre;línia d'ordres; Keywords[cs]=shell;prompt;výzva;příkaz;příkazový řádek;příkazová řádka; Keywords[da]=shell;skal;prompt;kommando;kommandolinje; Keywords[de]=Shell;Prompt;Befehl;Befehlszeile; Keywords[el]=κέλυφος;προτροπή;εντολή;γραμμή εντολών; Keywords[en_GB]=shell;prompt;command;commandline; Keywords[es]=shell;prompt;comando;línea de comandos; Keywords[et]=shell;kest;käsuviip;käsk;käsurida;terminal; Keywords[eu]=shell;gonbitea;komandoa;komando-lerroa; Keywords[fa]=پوسته;prompt;فرمان;خط‌فرمان; Keywords[fi]=shell;prompt;command;commandline;komento;kehote;cli; Keywords[fr]=shell;prompt;commande;ligne de commande; Keywords[gl]=shell;consola;orde;liña de ordes; Keywords[gu]=શેલ;પ્રોમ્પ્ટ;આદેશ;આદેશવાક્ય; Keywords[he]=מעטפת;פקודה;שורת פקודה;שורה;מסך שחור;חלון דוס; Keywords[hi]=शेल;प्रांप्ट;कमांड;कमांडलाइन; Keywords[hu]=parancsértelmező;prompt;parancs;parancssor; Keywords[id]=shell;prompt;perintah;baris perintah; Keywords[it]=shell;prompt;terminale;rigadicomando;comando; Keywords[kn]=ಶೆಲ್;ಪ್ರಾಂಪ್ಟ್‍;ಆದೇಶ;ಆದೇಶಸಾಲು; Keywords[ko]=shell;셸;쉘;prompt;프롬프트;command;명령;commandline;명령행;커맨드;라인; Keywords[lt]=apvalkalas;eilutė;komanda;komandų eilutė; Keywords[lv]=čaula;uzvedne;komanda;komandrinda; Keywords[ml]=shell;prompt;command;commandline; Keywords[mr]=शेल;प्रॉम्प्ट;कमांड;कमांडलाइन; Keywords[nb]=skall;kommando;kommandolinje; Keywords[nl]=shell;prompt;commando;opdrachtregel;cli;commandline;terminal; Keywords[or]=ସେଲ;ପ୍ରମ୍ପ୍ଟ;ନିର୍ଦ୍ଦେଶ;ନିର୍ଦ୍ଦେଶ ଧାରା; Keywords[pa]=ਸ਼ੈਲ;ਪਰੌਂਟ;ਕਮਾਂਡ;ਕਮਾਂਡ-ਲਾਈਨ;shell;prompt;command;commandline; Keywords[pl]=powłoka;shell;prompt;polecenie;komenda;wiersz poleceń;linia poleceń;wiersz komend;linia komend; Keywords[pt]=consola;linha;comando;terminal; Keywords[pt_BR]=shell;prompt;comando;comandos;linha de comando; Keywords[ru]=оболочка;строка;команда;командная строка; Keywords[sk]=shell;výzva;príkaz;príkazový riadok; Keywords[sl]=lupina;ukaz;ukazna vrstica;terminal; Keywords[sr@latin]=ljuska;školjka;upit;naredba;komanda; Keywords[sr]=љуска;шкољка;упит;наредба;команда; Keywords[ta]=ஷெல்;தூண்டி;கட்டளை;கட்டளை வரி; Keywords[te]=షెల్;ప్రామ్ట్;కమాండ్;కమాండ్‌లైన్; Keywords[th]=เชลล์;พรอมต์;คำสั่ง;บรรทัดคำสั่ง; Keywords[ug]=shell;prompt;command;commandline;shell;كۆرسەتمە;بۇيرۇق;بۇيرۇق قۇرى; Keywords[uk]=оболочка;комадний;рядок;команда; Keywords[zh_CN]=shell;prompt;command;commandline;命令;提示符;命令行; Keywords[zh_HK]=shell;prompt;command;commandline;提示;指令;命令列; Keywords[zh_TW]=shell;prompt;command;commandline;提示;指令;命令列; Name=Deepin Terminal Name[am]=ተርሚናል Name[ar]=طرفية دييبن Name[cs]=Terminál Name[da]=Deepin Terminal Name[de]=Deepin Terminal Name[de_DE]=Deepin Terminal Name[el_GR]=Τερματικό Deepin Name[en]=Deepin Terminal Name[es]=Terminal Deepin Name[es_419]=Terminal Deepin Name[es_AR]=Terminal Deepin Name[es_CL]=Terminal Deepin Name[es_ES]=Terminal Deepin Name[es_MX]=Terminal Deepin Name[es_PE]=Terminal Deepin Name[fi]=Deepin Terminaali Name[fr]=Terminal de Deepin Name[he]=מסוף Deepin Name[hu]=Deepin Terminál Name[hy]=Deepin Տերմինալ Name[id]=Deepin Terminal Name[id_ID]=Terminal Deepin Name[it]=Deepin Terminal Name[ja]=ターミナル Name[ms]=Terminal Deepin Name[nl]=Deepin Terminal Name[pl_PL]=Terminal Deepin Name[pt_BR]=Deepin Terminal Name[pt_PT]=Terminal Deepin Name[ro]=Terminalul Deepin Name[ru]=Терминал Deepin Name[sk]=Terminál Name[sl]=Terminal Deepin Name[sv_SE]=Deepin Terminal Name[tr]=Deepin Terminal Name[vi]=Deepin Terminal Name[zh_CN]=深度终端 Name[zh_HK]=深度終端機 Name[zh_TW]=深度終端機 StartupNotify=true TryExec=deepin-terminal Type=Application [NewQuake Shortcut Group] Exec=deepin-terminal --quake-mode Name=New Quake Window Name[am]=አዲስ የ Quake መስኮት Name[ar]=نافذة مهتزة جديدة Name[cs]=Nové okno Quake Name[da]=Nyt fremhævet vindue Name[de]=Neues Quake Fenster Name[de_DE]=Neues Quake Fenster Name[el_GR]=Νέο παράθυρο σε πλήρη οθόνη Name[en]=New Quake Window Name[es]=Nueva Ventana Quake Name[es_419]=Nueva ventana Quake Name[es_AR]=Nueva Ventana Quake Name[es_CL]=Nueva ventana Quake Name[es_ES]=Nueva Ventana Quake Name[es_PE]=Nueva ventana Name[fi]=Uusi Quake ikkuna Name[fr]=Nouvelle fenêtre spéciale Name[he]=חלון Quake jsa Name[hu]=Új teljes képernyős ablak Name[hy]=Նոր Quake Պատուհան Name[id_ID]=Halaman Layar Penuh Name[it]=Nuova finestra con root Name[ja]=新しい揺れウィンドウ Name[ms]=Tetingkap Baharu Quake Name[nl]=Nieuw Quake Venster Name[pl_PL]=Nowe okno Quake Name[pt_BR]=Nova Janela Sobreposta Name[pt_PT]=Nova Janela Quake Name[ro]=Fereastră nouă Quake Name[ru]=Новое quake-окно Name[sk]=Nové okno Quake Name[sl]=Novo okno Quake Name[tr]=Yeni Quake Pencere Name[zh_CN]=新建雷神窗口 Name[zh_TW]=新建雷神模式視窗 [NewWindow Shortcut Group] Exec=deepin-terminal Name=New Window Name[am]=አዲስ መስኮት Name[ar]=نافذة جديدة Name[bg]=Нов прозорец Name[bn]=নতুন উইন্ডো Name[ca]=Finestra nova Name[cs]=Nové okno Name[da]=Nyt vindue Name[de]=Neues Fenster Name[de_DE]=Neues Fenster Name[el]=Νέο Παράθυρο Name[el_GR]=Νέο Παράθυρο Name[en]=New Window Name[en_GB]=New Window Name[es]=Nueva Ventana Name[es_419]=Nueva ventana Name[es_AR]=Nueva Ventana Name[es_CL]=Nueva ventana Name[es_ES]=Nueva Ventana Name[es_PE]=Nueva ventana Name[et]=Uus aken Name[fa]=پنجره جدید Name[fi]=Uusi ikkuna Name[fil]=New Window Name[fr]=Nouvelle fenêtre Name[gu]=નવી વિંડો Name[he]=חלון חדש Name[hi]=नई विंडो Name[hr]=Novi prozor Name[hu]=Új ablak Name[hy]=Նոր Պատուհան Name[id]=Jendela Baru Name[id_ID]=Jendela baru Name[it]=Nuova finestra Name[ja]=新しいウィンドウ Name[kn]=ಹೊಸ ವಿಂಡೊ Name[ko]=새 창 Name[lt]=Naujas langas Name[lv]=Jauns logs Name[ml]=പുതിയ വിന്‍ഡോ Name[mr]=नवीन विंडो Name[ms]=Tetingkap Baharu Name[nl]=Nieuw Venster Name[no]=Nytt vindu Name[pl]=Nowe okno Name[pl_PL]=Nowe okno Name[pt]=Nova janela Name[pt_BR]=Nova Janela Name[pt_PT]=Nova Janela Name[ro]=Fereastră nouă Name[ru]=Новое окно Name[sk]=Nové okno Name[sl]=Novo okno Name[sr]=Нови прозор Name[sv]=Nytt fönster Name[sw]=Dirisha Jipya Name[ta]=புதிய சாளரம் Name[te]=క్రొత్త విండో Name[th]=หน้าต่างใหม่ Name[tr]=Yeni Pencere Name[uk]=Нове вікно Name[vi]=Cửa sổ Mới Name[zh_CN]=新建窗口 Name[zh_TW]=開啟新視窗 go-gir-generator-master/lib.in/gobject-2.0/000077500000000000000000000000001414263242200206045ustar00rootroot00000000000000go-gir-generator-master/lib.in/gobject-2.0/.gitignore000066400000000000000000000000471414263242200225750ustar00rootroot00000000000000gobject.gen.c gobject.gen.h gobject.go go-gir-generator-master/lib.in/gobject-2.0/config.json000066400000000000000000000006031414263242200227430ustar00rootroot00000000000000{ "namespace": "GObject", "version": "2.0", "whitelist": { "deps": [], "callbacks": [], "functions": [], "objects": [ "Binding", "Object", "InitiallyUnowned" ] }, "method-whitelist": { "Object": [], "InitiallyUnowned": [], "Value": [] }, "blacklist": { "structs": [ "ParamSpecPool" ] }, "method-blacklist": { "ValueArray": [ "sort" ] } } go-gir-generator-master/lib.in/gobject-2.0/fix_gobject.c000066400000000000000000000112151414263242200232330ustar00rootroot00000000000000#include #include #include #include "gobject.h" struct _GGoClosure { GClosure closure; GoInterfaceHolder func; GoInterfaceHolder recv; }; GType _g_param_spec_type(GParamSpec *pspec) { return G_PARAM_SPEC_TYPE(pspec); } GType _g_param_spec_value_type(GParamSpec *pspec) { return G_PARAM_SPEC_VALUE_TYPE(pspec); } GType _g_object_type(GObject *obj) { return G_OBJECT_TYPE(obj); } GType _g_value_type(GValue *val) { return G_VALUE_TYPE(val); } GType _g_type_interface() { return G_TYPE_INTERFACE; } GType _g_type_char() { return G_TYPE_CHAR; } GType _g_type_uchar() { return G_TYPE_UCHAR; } GType _g_type_boolean() { return G_TYPE_BOOLEAN; } GType _g_type_int() { return G_TYPE_INT; } GType _g_type_uint() { return G_TYPE_UINT; } GType _g_type_long() { return G_TYPE_LONG; } GType _g_type_ulong() { return G_TYPE_ULONG; } GType _g_type_int64() { return G_TYPE_INT64; } GType _g_type_uint64() { return G_TYPE_UINT64; } GType _g_type_enum() { return G_TYPE_ENUM; } GType _g_type_flags() { return G_TYPE_FLAGS; } GType _g_type_float() { return G_TYPE_FLOAT; } GType _g_type_double() { return G_TYPE_DOUBLE; } GType _g_type_string() { return G_TYPE_STRING; } GType _g_type_pointer() { return G_TYPE_POINTER; } GType _g_type_boxed() { return G_TYPE_BOXED; } GType _g_type_param() { return G_TYPE_PARAM; } GType _g_type_object() { return G_TYPE_OBJECT; } GType _g_type_gtype() { return G_TYPE_GTYPE; } GType _g_type_variant() { return G_TYPE_VARIANT; } GType _g_type_param_boolean() { return G_TYPE_PARAM_BOOLEAN; } GType _g_type_param_boxed() { return G_TYPE_PARAM_BOXED; } GType _g_type_param_char() { return G_TYPE_PARAM_CHAR; } GType _g_type_param_double() { return G_TYPE_PARAM_DOUBLE; } GType _g_type_param_enum() { return G_TYPE_PARAM_ENUM; } GType _g_type_param_flags() { return G_TYPE_PARAM_FLAGS; } GType _g_type_param_float() { return G_TYPE_PARAM_FLOAT; } GType _g_type_param_gtype() { return G_TYPE_PARAM_GTYPE; } GType _g_type_param_int() { return G_TYPE_PARAM_INT; } GType _g_type_param_int64() { return G_TYPE_PARAM_INT64; } GType _g_type_param_long() { return G_TYPE_PARAM_LONG; } GType _g_type_param_object() { return G_TYPE_PARAM_OBJECT; } GType _g_type_param_override() { return G_TYPE_PARAM_OVERRIDE; } GType _g_type_param_param() { return G_TYPE_PARAM_PARAM; } GType _g_type_param_pointer() { return G_TYPE_PARAM_POINTER; } GType _g_type_param_string() { return G_TYPE_PARAM_STRING; } GType _g_type_param_uchar() { return G_TYPE_PARAM_UCHAR; } GType _g_type_param_uint() { return G_TYPE_PARAM_UINT; } GType _g_type_param_uint64() { return G_TYPE_PARAM_UINT64; } GType _g_type_param_ulong() { return G_TYPE_PARAM_ULONG; } GType _g_type_param_unichar() { return G_TYPE_PARAM_UNICHAR; } GType _g_type_param_value_array() { return G_TYPE_PARAM_VALUE_ARRAY; } GType _g_type_param_variant() { return G_TYPE_PARAM_VARIANT; } GParamSpec *_g_object_find_property(GObject *object, const char *name) { GObjectClass *cls = G_OBJECT_GET_CLASS(object); return g_object_class_find_property(cls, name); } extern void *g_go_interface_copy_go(void *boxed); extern void g_go_interface_free_go(void *boxed); GType _g_type_go_interface() { static GType go_interface_type = G_TYPE_NONE; if (go_interface_type == G_TYPE_NONE) { go_interface_type = g_boxed_type_register_static("gointerface", g_go_interface_copy_go, g_go_interface_free_go); } return go_interface_type; } //----------------------------------------------------------------------------- extern void g_goclosure_marshal_go(GGoClosure*, GValue*, int32_t, GValue*); extern void g_goclosure_finalize_go(GGoClosure*); static void g_goclosure_finalize(void *notify_data, GClosure *closure) { GGoClosure *goclosure = (GGoClosure*)closure; g_goclosure_finalize_go(goclosure); } static void g_goclosure_marshal(GClosure *closure, GValue *return_value, uint32_t n_param_values, const GValue *param_values, void *invocation_hint, void *data) { g_goclosure_marshal_go((GGoClosure*)closure, return_value, n_param_values, (GValue*)param_values); } GGoClosure *g_goclosure_new(GoInterfaceHolder func, GoInterfaceHolder recv) { GClosure *closure; GGoClosure *goclosure; closure = g_closure_new_simple(sizeof(GGoClosure), 0); goclosure = (GGoClosure*)closure; goclosure->func = func; goclosure->recv = recv; g_closure_add_finalize_notifier(closure, 0, g_goclosure_finalize); g_closure_set_marshal(closure, g_goclosure_marshal); return goclosure; } GoInterfaceHolder g_goclosure_get_func(GGoClosure *clo) { return clo->func; } GoInterfaceHolder g_goclosure_get_recv(GGoClosure *clo) { return clo->recv; } go-gir-generator-master/lib.in/gobject-2.0/gobject.go.in000066400000000000000000000402501414263242200231560ustar00rootroot00000000000000package gobject /* #include "gobject.gen.h" #include [<.g_free>] #include "gobject.h" extern uint32_t g_quark_from_string(const char*); extern void g_object_set_qdata(GObject*, uint32_t, void*); extern void g_type_init(); #cgo pkg-config: gobject-2.0 */ import "C" import "unsafe" import "runtime" import "reflect" [<.go_utils>] [<.go_bindings>] //-------------------------------------------------------------- // NilString //-------------------------------------------------------------- // its value will stay the same forever, use the value directly if you like const NilString = "\x00" //-------------------------------------------------------------- // Quark // // TODO: probably it's a temporary place for this, quarks are // from glib //-------------------------------------------------------------- type Quark uint32 func NewQuarkFromString(s string) Quark { cs := C.CString(s) quark := C.g_quark_from_string(cs) C.free(unsafe.Pointer(cs)) return Quark(quark) } // we use this one to store Go's representation of the GObject // as user data in that GObject once it was allocated. For the // sake of avoiding allocations. var go_repr Quark func init() { go_repr = NewQuarkFromString("go-representation") } //-------------------------------------------------------------- // Object //-------------------------------------------------------------- func object_finalizer(obj *Object) { if FQueue.Push(unsafe.Pointer(obj), object_finalizer2) { return } C.g_object_set_qdata((*C.GObject)(obj.C), C.uint32_t(go_repr), nil) C.g_object_unref((*C.GObject)(obj.C)) } func object_finalizer2(obj_un unsafe.Pointer) { obj := (*Object)(obj_un) C.g_object_set_qdata((*C.GObject)(obj.C), C.uint32_t(go_repr), nil) C.g_object_unref((*C.GObject)(obj.C)) } func set_object_finalizer(obj *Object) { runtime.SetFinalizer(obj, object_finalizer) } func ObjectWrap(c unsafe.Pointer, grab bool) unsafe.Pointer { if c == nil { return nil } obj := (*Object)(C.g_object_get_qdata((*C.GObject)(c), C.uint32_t(go_repr))) if obj != nil { return unsafe.Pointer(obj) } obj = &Object{c} if grab { C.g_object_ref_sink((*C.GObject)(obj.C)) } set_object_finalizer(obj) C.g_object_set_qdata((*C.GObject)(obj.C), C.uint32_t(go_repr), unsafe.Pointer(obj)) return unsafe.Pointer(obj) } func ObjectGrabIfType(c unsafe.Pointer, t Type) unsafe.Pointer { if c == nil { return nil } hasrepr := true obj := (*Object)(C.g_object_get_qdata((*C.GObject)(c), C.uint32_t(go_repr))) if obj == nil { obj = &Object{c} hasrepr = false } if obj.GetType().IsA(t) { if !hasrepr { C.g_object_ref_sink((*C.GObject)(obj.C)) set_object_finalizer(obj) C.g_object_set_qdata((*C.GObject)(obj.C), C.uint32_t(go_repr), unsafe.Pointer(obj)) } return unsafe.Pointer(obj) } return nil } func (this *Object) GetType() Type { return Type(C._g_object_type((*C.GObject)(this.C))) } func (this *Object) Connect(signal string, clo interface{}) { csignal := C.CString(signal) Holder.Grab(clo) if clo == nil { panic("Connect with nil") } goclosure := C.g_goclosure_new(toGoInterfaceHolder(clo), toGoInterfaceHolder(nil)) C.g_signal_connect_closure((*C.GObject)(this.C), csignal, (*C.GClosure)(unsafe.Pointer(goclosure)), 0) C.free(unsafe.Pointer(csignal)) } func (this *Object) ConnectMethod(signal string, clo interface{}, recv interface{}) { csignal := C.CString(signal) Holder.Grab(clo) Holder.Grab(recv) goclosure := C.g_goclosure_new(toGoInterfaceHolder(clo), toGoInterfaceHolder(recv)) C.g_signal_connect_closure((*C.GObject)(this.C), csignal, (*C.GClosure)(unsafe.Pointer(goclosure)), 0) C.free(unsafe.Pointer(csignal)) } func (this *Object) FindProperty(name string) *ParamSpec { cname := C.CString(name) ret := C._g_object_find_property(this.InheritedFromGObject(), cname) C.free(unsafe.Pointer(cname)) return (*ParamSpec)(ParamSpecWrap(unsafe.Pointer(ret), true)) } func (this *Object) SetProperty(name string, value interface{}) { cname := C.CString(name) pspec := this.FindProperty(name) if pspec == nil { panic("Object has no property with that name: " + name) } var gvalue Value gvalue.Init(pspec.GetValueType()) gvalue.SetGoInterface(value) C.g_object_set_property(this.InheritedFromGObject(), cname, (*C.GValue)(unsafe.Pointer(&gvalue))) gvalue.Unset() C.free(unsafe.Pointer(cname)) } func (this *Object) GetProperty(name string, value interface{}) { cname := C.CString(name) pspec := this.FindProperty(name) if pspec == nil { panic("Object has no property with that name: " + name) } var gvalue Value gvalue.Init(pspec.GetValueType()) C.g_object_get_property(this.InheritedFromGObject(), cname, (*C.GValue)(unsafe.Pointer(&gvalue))) gvalue.GetGoInterface(value) gvalue.Unset() C.free(unsafe.Pointer(cname)) } func ObjectBindProperty(source ObjectLike, source_property string, target ObjectLike, target_property string, flags BindingFlags) *Binding { csource_property := C.CString(source_property) ctarget_property := C.CString(target_property) obj := C.g_object_bind_property( source.InheritedFromGObject(), csource_property, target.InheritedFromGObject(), ctarget_property, C.GBindingFlags(flags)) C.free(unsafe.Pointer(csource_property)) C.free(unsafe.Pointer(ctarget_property)) return (*Binding)(ObjectWrap(unsafe.Pointer(obj), true)) } func (this *Object) Unref() { runtime.SetFinalizer(this, nil) C.g_object_set_qdata((*C.GObject)(this.C), C.uint32_t(go_repr), nil) C.g_object_unref((*C.GObject)(this.C)) this.C = nil } //-------------------------------------------------------------- // Closures //-------------------------------------------------------------- //export g_goclosure_finalize_go func g_goclosure_finalize_go(goclosure_up unsafe.Pointer) { goclosure := (*C.GGoClosure)(goclosure_up) clo := fromGoInterfaceHolder(C.g_goclosure_get_func(goclosure)) recv := fromGoInterfaceHolder(C.g_goclosure_get_recv(goclosure)) Holder.Release(clo) Holder.Release(recv) } //export g_goclosure_marshal_go func g_goclosure_marshal_go(goclosure_up, ret_up unsafe.Pointer, nargs int32, args_up unsafe.Pointer) { var callargs [20]reflect.Value var recv reflect.Value goclosure := (*C.GGoClosure)(goclosure_up) ret := (*Value)(ret_up) args := (*(*[alot]Value)(args_up))[:nargs] f := reflect.ValueOf(fromGoInterfaceHolder(C.g_goclosure_get_func(goclosure))) ft := f.Type() callargsn := ft.NumIn() recvi := fromGoInterfaceHolder(C.g_goclosure_get_recv(goclosure)) if recvi != nil { recv = reflect.ValueOf(recvi) } if callargsn >= 20 { panic("too many arguments in a closure") } for i, n := 0, callargsn; i < n; i++ { idx := i if recvi != nil { idx-- if i == 0 { callargs[i] = recv continue } } in := ft.In(i) // use default value, if there is not enough args if len(args) <= idx { callargs[i] = reflect.New(in).Elem() continue } v := args[idx].GetGoValue(in) callargs[i] = v } // The running thread of f need be the owner of global // default main content. // And g_goclosure_marshal_go is called by main loop, // So we can simply make this by using runtime.LockOSThread runtime.LockOSThread() out := f.Call(callargs[:callargsn]) runtime.UnlockOSThread() if len(out) == 1 { ret.SetGoValue(out[0]) } } //-------------------------------------------------------------- // Go Interface boxed type //-------------------------------------------------------------- //export g_go_interface_copy_go func g_go_interface_copy_go(boxed unsafe.Pointer) unsafe.Pointer { Holder.Grab(*(*interface{})(boxed)) newboxed := C.malloc(C.size_t(unsafe.Sizeof([2]unsafe.Pointer{}))) C.memcpy(newboxed, boxed, C.size_t(unsafe.Sizeof([2]unsafe.Pointer{}))) return newboxed } //export g_go_interface_free_go func g_go_interface_free_go(boxed unsafe.Pointer) { Holder.Release(*(*interface{})(boxed)) C.free(boxed) } //-------------------------------------------------------------- // Type //-------------------------------------------------------------- type Type C.GType func (this Type) IsA(other Type) bool { return C.g_type_is_a(C.GType(this), C.GType(other)) != 0 } func (this Type) String() string { cname := C.g_type_name(C.GType(this)) if cname == nil { return "" } return C.GoString(cname) } func (this Type) asC() C.GType { return C.GType(this) } var ( Interface Type Char Type UChar Type Boolean Type Int Type UInt Type Long Type ULong Type Int64 Type UInt64 Type Enum Type Flags Type Float Type Double Type String Type Pointer Type Boxed Type Param Type GObject Type GType Type Variant Type GoInterface Type ) func init() { C.g_type_init() Interface = Type(C._g_type_interface()) Char = Type(C._g_type_char()) UChar = Type(C._g_type_uchar()) Boolean = Type(C._g_type_boolean()) Int = Type(C._g_type_int()) UInt = Type(C._g_type_uint()) Long = Type(C._g_type_long()) ULong = Type(C._g_type_ulong()) Int64 = Type(C._g_type_int64()) UInt64 = Type(C._g_type_uint64()) Enum = Type(C._g_type_enum()) Flags = Type(C._g_type_flags()) Float = Type(C._g_type_float()) Double = Type(C._g_type_double()) String = Type(C._g_type_string()) Pointer = Type(C._g_type_pointer()) Boxed = Type(C._g_type_boxed()) Param = Type(C._g_type_param()) GObject = Type(C._g_type_object()) GType = Type(C._g_type_gtype()) Variant = Type(C._g_type_variant()) GoInterface = Type(C._g_type_go_interface()) } // Every GObject generated by this generator implements this interface // and it must work even if the receiver is a nil value type StaticTyper interface { GetStaticType() Type } //-------------------------------------------------------------- // Value //-------------------------------------------------------------- func (this *Value) asC() *C.GValue { return (*C.GValue)(unsafe.Pointer(this)) } // g_value_init func (this *Value) Init(t Type) { C.g_value_init(this.asC(), t.asC()) } // g_value_copy func (this *Value) Set(src *Value) { C.g_value_copy(src.asC(), this.asC()) } // g_value_reset func (this *Value) Reset() { C.g_value_reset(this.asC()) } // g_value_unset func (this *Value) Unset() { C.g_value_unset(this.asC()) } // G_VALUE_TYPE func (this *Value) GetType() Type { return Type(C._g_value_type(this.asC())) } // g_value_type_compatible func ValueTypeCompatible(src, dst Type) bool { return C.g_value_type_compatible(src.asC(), dst.asC()) != 0 } // g_value_type_transformable func ValueTypeTransformable(src, dst Type) bool { return C.g_value_type_transformable(src.asC(), dst.asC()) != 0 } // g_value_transform func (this *Value) Transform(src *Value) bool { return C.g_value_transform(src.asC(), this.asC()) != 0 } // g_value_get_boolean func (this *Value) GetBool() bool { return C.g_value_get_boolean(this.asC()) != 0 } // g_value_set_boolean func (this *Value) SetBool(v bool) { C.g_value_set_boolean(this.asC(), _GoBoolToCBool(v)) } // g_value_get_int64 func (this *Value) GetInt() int64 { return int64(C.g_value_get_int64(this.asC())) } // g_value_set_int64 func (this *Value) SetInt(v int64) { C.g_value_set_int64(this.asC(), C.int64_t(v)) } // g_value_get_uint64 func (this *Value) GetUint() uint64 { return uint64(C.g_value_get_uint64(this.asC())) } // g_value_set_uint64 func (this *Value) SetUint(v uint64) { C.g_value_set_uint64(this.asC(), C.uint64_t(v)) } // g_value_get_double func (this *Value) GetFloat() float64 { return float64(C.g_value_get_double(this.asC())) } // g_value_set_double func (this *Value) SetFloat(v float64) { C.g_value_set_double(this.asC(), C.double(v)) } // g_value_get_string func (this *Value) GetString() string { return C.GoString(C.g_value_get_string(this.asC())) } // g_value_take_string func (this *Value) SetString(v string) { cstr := C.CString(v) C.g_value_take_string(this.asC(), cstr) // not freeing, because GValue takes the ownership } // g_value_get_object func (this *Value) GetObject() unsafe.Pointer { return unsafe.Pointer(C.g_value_get_object(this.asC())) } // g_value_set_object func (this *Value) SetObject(x unsafe.Pointer) { C.g_value_set_object(this.asC(), (*C.GObject)(x)) } // g_value_get_boxed func (this *Value) GetBoxed() unsafe.Pointer { return C.g_value_get_boxed(this.asC()) } // g_value_take_boxed func (this *Value) SetBoxed(x unsafe.Pointer) { C.g_value_take_boxed(this.asC(), x) } func (this *Value) GetBoxedInterface() interface{} { return *(*interface{})(C.g_value_get_boxed(this.asC())) } func (this *Value) SetBoxedInterface(x interface{}) { Holder.Grab(x) newboxed := C.malloc(C.size_t(unsafe.Sizeof([2]unsafe.Pointer{}))) C.memcpy(newboxed, unsafe.Pointer(&x), C.size_t(unsafe.Sizeof([2]unsafe.Pointer{}))) C.g_value_take_boxed(this.asC(), newboxed) } //-------------------------------------------------------------- // A giant glue for connecting GType and Go's reflection //-------------------------------------------------------------- var statictyper = reflect.TypeOf((*StaticTyper)(nil)).Elem() var objectlike = reflect.TypeOf((*ObjectLike)(nil)).Elem() func (this *Value) SetGoValue(v reflect.Value) { valuetype := this.GetType() var src Value if valuetype == GoInterface { // special case this.SetBoxedInterface(v.Interface()) return } transform := func() { ok := this.Transform(&src) if !ok { panic("Go value (" + v.Type().String() + ") is not transformable to " + valuetype.String()) } } switch v.Kind() { case reflect.Bool: src.Init(Boolean) src.SetBool(v.Bool()) transform() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: src.Init(Int64) src.SetInt(v.Int()) transform() case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: src.Init(UInt64) src.SetUint(v.Uint()) transform() case reflect.Float32, reflect.Float64: src.Init(Double) src.SetFloat(v.Float()) transform() case reflect.String: src.Init(String) src.SetString(v.String()) transform() src.Unset() case reflect.Ptr: gotype := v.Type() src.Init(GObject) if gotype.Implements(objectlike) { obj, ok := v.Interface().(ObjectLike) if !ok { panic(gotype.String() + " is not transformable to GValue") } src.SetObject(unsafe.Pointer(obj.InheritedFromGObject())) transform() } src.Unset() } } var CairoMarshaler func(*Value, reflect.Type) (reflect.Value, bool) func (this *Value) GetGoValue(t reflect.Type) reflect.Value { var out reflect.Value var dst Value if (this.GetType() == GoInterface) { return reflect.ValueOf(this.GetBoxedInterface()) } transform := func() { ok := dst.Transform(this) if !ok { panic("GValue is not transformable to " + t.String()) } } switch t.Kind() { case reflect.Bool: dst.Init(Boolean) transform() out = reflect.New(t).Elem() out.SetBool(dst.GetBool()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: dst.Init(Int64) transform() out = reflect.New(t).Elem() out.SetInt(dst.GetInt()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: dst.Init(UInt64) transform() out = reflect.New(t).Elem() out.SetUint(dst.GetUint()) case reflect.Float32, reflect.Float64: dst.Init(Double) transform() out = reflect.New(t).Elem() out.SetFloat(dst.GetFloat()) case reflect.String: dst.Init(String) transform() out = reflect.New(t).Elem() out.SetString(dst.GetString()) dst.Unset() // need to clean up in this case case reflect.Ptr: if t.Implements(objectlike) { // at this point we're sure that this is a pointer to the ObjectLike out = reflect.New(t) st, ok := out.Elem().Interface().(StaticTyper) if !ok { panic("ObjectLike type must implement StaticTyper as well") } dst.Init(st.GetStaticType()) transform() *(*unsafe.Pointer)(unsafe.Pointer(out.Pointer())) = ObjectWrap(dst.GetObject(), true) dst.Unset() out = out.Elem() } else { // cairo marshaler hook if CairoMarshaler != nil { var ok bool out, ok = CairoMarshaler(this, t) if ok { break } } // must be a struct then out = reflect.New(t) *(*unsafe.Pointer)(unsafe.Pointer(out.Pointer())) = this.GetBoxed() out = out.Elem() } } return out } func (this *Value) SetGoInterface(v interface{}) { this.SetGoValue(reflect.ValueOf(v)) } func (this *Value) GetGoInterface(v interface{}) { vp := reflect.ValueOf(v) if vp.Kind() != reflect.Ptr { panic("a pointer to value is expected for Value.GetGoInterface") } vp.Elem().Set(this.GetGoValue(vp.Type().Elem())) } go-gir-generator-master/lib.in/gobject-2.0/gobject.h000066400000000000000000000034071414263242200223760ustar00rootroot00000000000000#pragma once typedef struct _CGoInterface { uint8_t _data[2*sizeof(void*)]; } GoInterfaceHolder; typedef struct _GGoClosure GGoClosure; GType _g_param_spec_type(GParamSpec *pspec); GType _g_param_spec_value_type(GParamSpec *pspec); GType _g_object_type(GObject *obj); GType _g_value_type(GValue *val); GType _g_type_interface(); GType _g_type_char(); GType _g_type_uchar(); GType _g_type_boolean(); GType _g_type_int(); GType _g_type_uint(); GType _g_type_long(); GType _g_type_ulong(); GType _g_type_int64(); GType _g_type_uint64(); GType _g_type_enum(); GType _g_type_flags(); GType _g_type_float(); GType _g_type_double(); GType _g_type_string(); GType _g_type_pointer(); GType _g_type_boxed(); GType _g_type_param(); GType _g_type_object(); GType _g_type_gtype(); GType _g_type_variant(); GType _g_type_go_interface(); GType _g_type_param_boolean(); GType _g_type_param_boxed(); GType _g_type_param_char(); GType _g_type_param_double(); GType _g_type_param_enum(); GType _g_type_param_flags(); GType _g_type_param_float(); GType _g_type_param_gtype(); GType _g_type_param_int(); GType _g_type_param_int64(); GType _g_type_param_long(); GType _g_type_param_object(); GType _g_type_param_override(); GType _g_type_param_param(); GType _g_type_param_pointer(); GType _g_type_param_string(); GType _g_type_param_uchar(); GType _g_type_param_uint(); GType _g_type_param_uint64(); GType _g_type_param_ulong(); GType _g_type_param_unichar(); GType _g_type_param_value_array(); GType _g_type_param_variant(); GParamSpec *_g_object_find_property(GObject *object, const char *name); // null recv is allowed GGoClosure *g_goclosure_new(GoInterfaceHolder func, GoInterfaceHolder recv); GoInterfaceHolder g_goclosure_get_func(GGoClosure *clo); GoInterfaceHolder g_goclosure_get_recv(GGoClosure *clo); go-gir-generator-master/lib.in/gobject-2.0/gobject_test.go000066400000000000000000000010061414263242200236040ustar00rootroot00000000000000package gobject import "testing" import "fmt" func TestHolder(t *testing.T) { a := "a string" k := toGoInterfaceHolder(a) Holder.Grab(a) if fromGoInterfaceHolder(k) != a { fmt.Printf("K: %q != %q\n", a, fromGoInterfaceHolder(k)) t.Fail() } if nil != fromGoInterfaceHolder(toGoInterfaceHolder(nil)) { t.Fail() } } func TestHolderFunc(t *testing.T) { f := func() string { return "OK" } key := toGoInterfaceHolder(f) h := fromGoInterfaceHolder(key) if "OK" != h.(func() string)() { t.Fail() } } go-gir-generator-master/lib.in/gobject-2.0/holder.go000066400000000000000000000067121414263242200224160ustar00rootroot00000000000000package gobject import ( "sync" "unsafe" ) /* #include "gobject.gen.h" #include "gobject.h" typedef int32_t (*_GSourceFunc)(void*); extern uint32_t g_timeout_add(uint32_t, _GSourceFunc, void*); extern int32_t g_source_remove(uint32_t); extern int32_t fqueue_dispatcher(void*); static uint32_t _g_timeout_add_fqueue(uint32_t time) { return g_timeout_add(time, fqueue_dispatcher, 0); } */ import "C" //-------------------------------------------------------------- // Holder //-------------------------------------------------------------- // holy crap, what am I doing here.. type holder_key [2]unsafe.Pointer type holder_type map[holder_key]int func init() { var i interface{} = 0 if unsafe.Sizeof(i) != unsafe.Sizeof(holder_key{}) || unsafe.Sizeof(i) != unsafe.Sizeof(C.GoInterfaceHolder{}) { panic("The Go gir world be damaged because interface{} implement changed. :(") } } var Holder = holder_type(make(map[holder_key]int)) var holderLocker sync.Mutex func toGoInterfaceHolder(x interface{}) C.GoInterfaceHolder { return *(*C.GoInterfaceHolder)(unsafe.Pointer(&x)) } func fromGoInterfaceHolder(x C.GoInterfaceHolder) interface{} { return *(*interface{})(unsafe.Pointer(&x)) } func (this holder_type) Grab(x interface{}) { if x == nil { return } holderLocker.Lock() defer holderLocker.Unlock() key := *(*holder_key)(unsafe.Pointer(&x)) count := this[key] this[key] = count + 1 } func (this holder_type) Release(x interface{}) { if x == nil { return } holderLocker.Lock() defer holderLocker.Unlock() key := *(*holder_key)(unsafe.Pointer(&x)) count := this[key] if count <= 1 { delete(this, key) } else { this[key] = count - 1 } } //-------------------------------------------------------------- // FinalizerQueue //-------------------------------------------------------------- type finalizer_item struct { ptr unsafe.Pointer finalizer func(unsafe.Pointer) } type fqueue_type struct { sync.Mutex queue []finalizer_item exec_queue []finalizer_item tid uint32 } var FQueue fqueue_type func (this *fqueue_type) Start(interval int) { this.Lock() this.queue = make([]finalizer_item, 0, 50) this.exec_queue = make([]finalizer_item, 50) this.tid = uint32(C._g_timeout_add_fqueue(C.uint32_t(interval))) this.Unlock() } func (this *fqueue_type) Stop() { this.Lock() // TODO: we'll discard few items here at Stop, is it ok? this.queue = nil C.g_source_remove(C.uint32_t(this.tid)) this.Unlock() } // returns true if the item was enqueued, thread safe func (this *fqueue_type) Push(ptr unsafe.Pointer, finalizer func(unsafe.Pointer)) bool { this.Lock() if this.queue != nil { this.queue = append(this.queue, finalizer_item{ptr, finalizer}) this.Unlock() return true } this.Unlock() return false } // exec is only thread safe if executed by a single thread func (this *fqueue_type) exec() { // exec_queue is used for not holding the lock a lot this.Lock() // common case if len(this.queue) == 0 { this.Unlock() return } // non-empty queue, copy everything to exec_queue if len(this.queue) > len(this.exec_queue) { this.exec_queue = make([]finalizer_item, len(this.queue)) } nitems := copy(this.exec_queue, this.queue) this.queue = this.queue[:0] this.Unlock() // then do our work for i := 0; i < nitems; i++ { this.exec_queue[i].finalizer(this.exec_queue[i].ptr) this.exec_queue[i] = finalizer_item{} } } //export fqueue_dispatcher func fqueue_dispatcher(unused unsafe.Pointer) int32 { FQueue.exec() return 1 } go-gir-generator-master/lib.in/gobject-2.0/param.go000066400000000000000000000511061414263242200222360ustar00rootroot00000000000000package gobject import ( "runtime" "unsafe" ) /* #include "gobject.gen.h" #include "gobject.h" #include extern GParamSpec *g_param_spec_ref_sink(GParamSpec*); extern void g_param_spec_unref(GParamSpec*); */ import "C" //-------------------------------------------------------------- // ParamSpec utils //-------------------------------------------------------------- // Let's implement these manually (not Object based and small amount of things // to implement). // First some utils func param_spec_finalizer(pspec *ParamSpec) { if FQueue.Push(unsafe.Pointer(pspec), param_spec_finalizer2) { return } C.g_param_spec_unref((*C.GParamSpec)(pspec.C)) } func param_spec_finalizer2(pspec_un unsafe.Pointer) { pspec := (*ParamSpec)(pspec_un) C.g_param_spec_unref((*C.GParamSpec)(pspec.C)) } func set_param_spec_finalizer(pspec *ParamSpec) { runtime.SetFinalizer(pspec, param_spec_finalizer) } func ParamSpecGrabIfType(c unsafe.Pointer, t Type) unsafe.Pointer { if c == nil { return nil } obj := &ParamSpec{c} if obj.GetType().IsA(t) { C.g_param_spec_ref_sink((*C.GParamSpec)(obj.C)) set_param_spec_finalizer(obj) return unsafe.Pointer(obj) } return nil } func ParamSpecWrap(c unsafe.Pointer, grab bool) unsafe.Pointer { if c == nil { return nil } obj := &ParamSpec{c} if grab { C.g_param_spec_ref_sink((*C.GParamSpec)(obj.C)) } set_param_spec_finalizer(obj) return unsafe.Pointer(obj) } //-------------------------------------------------------------- // ParamSpec //-------------------------------------------------------------- type ParamSpecLike interface { InheritedFromGParamSpec() *C.GParamSpec } type ParamSpec struct { C unsafe.Pointer } func ToParamSpec(pspeclike ParamSpecLike) *ParamSpec { t := (*ParamSpec)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpec() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpec)(obj) } panic("cannot cast to ParamSpec") } func (this *ParamSpec) InheritedFromGParamSpec() *C.GParamSpec { return (*C.GParamSpec)(this.C) } func (this *ParamSpec) GetStaticType() Type { return Type(C._g_type_param()) } func (this *ParamSpec) GetType() Type { return Type(C._g_param_spec_type(this.InheritedFromGParamSpec())) } func (this *ParamSpec) GetValueType() Type { return Type(C._g_param_spec_value_type(this.InheritedFromGParamSpec())) } //-------------------------------------------------------------- // ParamSpecBoolean //-------------------------------------------------------------- type ParamSpecBooleanLike interface { InheritedFromGParamSpecBoolean() *C.GParamSpecBoolean } type ParamSpecBoolean struct { ParamSpec } func ToParamSpecBoolean(pspeclike ParamSpecBooleanLike) *ParamSpecBoolean { t := (*ParamSpecBoolean)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecBoolean() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecBoolean)(obj) } panic("cannot cast to ParamSpecBoolean") } func (this *ParamSpecBoolean) InheritedFromGParamSpecBoolean() *C.GParamSpecBoolean { return (*C.GParamSpecBoolean)(this.C) } func (this *ParamSpecBoolean) GetStaticType() Type { return Type(C._g_type_param_boolean()) } //-------------------------------------------------------------- // ParamSpecBoxed //-------------------------------------------------------------- type ParamSpecBoxedLike interface { InheritedFromGParamSpecBoxed() *C.GParamSpecBoxed } type ParamSpecBoxed struct { ParamSpec } func ToParamSpecBoxed(pspeclike ParamSpecBoxedLike) *ParamSpecBoxed { t := (*ParamSpecBoxed)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecBoxed() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecBoxed)(obj) } panic("cannot cast to ParamSpecBoxed") } func (this *ParamSpecBoxed) InheritedFromGParamSpecBoxed() *C.GParamSpecBoxed { return (*C.GParamSpecBoxed)(this.C) } func (this *ParamSpecBoxed) GetStaticType() Type { return Type(C._g_type_param_boxed()) } //-------------------------------------------------------------- // ParamSpecChar //-------------------------------------------------------------- type ParamSpecCharLike interface { InheritedFromGParamSpecChar() *C.GParamSpecChar } type ParamSpecChar struct { ParamSpec } func ToParamSpecChar(pspeclike ParamSpecCharLike) *ParamSpecChar { t := (*ParamSpecChar)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecChar() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecChar)(obj) } panic("cannot cast to ParamSpecChar") } func (this *ParamSpecChar) InheritedFromGParamSpecChar() *C.GParamSpecChar { return (*C.GParamSpecChar)(this.C) } func (this *ParamSpecChar) GetStaticType() Type { return Type(C._g_type_param_char()) } //-------------------------------------------------------------- // ParamSpecDouble //-------------------------------------------------------------- type ParamSpecDoubleLike interface { InheritedFromGParamSpecDouble() *C.GParamSpecDouble } type ParamSpecDouble struct { ParamSpec } func ToParamSpecDouble(pspeclike ParamSpecDoubleLike) *ParamSpecDouble { t := (*ParamSpecDouble)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecDouble() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecDouble)(obj) } panic("cannot cast to ParamSpecDouble") } func (this *ParamSpecDouble) InheritedFromGParamSpecDouble() *C.GParamSpecDouble { return (*C.GParamSpecDouble)(this.C) } func (this *ParamSpecDouble) GetStaticType() Type { return Type(C._g_type_param_double()) } //-------------------------------------------------------------- // ParamSpecEnum //-------------------------------------------------------------- type ParamSpecEnumLike interface { InheritedFromGParamSpecEnum() *C.GParamSpecEnum } type ParamSpecEnum struct { ParamSpec } func ToParamSpecEnum(pspeclike ParamSpecEnumLike) *ParamSpecEnum { t := (*ParamSpecEnum)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecEnum() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecEnum)(obj) } panic("cannot cast to ParamSpecEnum") } func (this *ParamSpecEnum) InheritedFromGParamSpecEnum() *C.GParamSpecEnum { return (*C.GParamSpecEnum)(this.C) } func (this *ParamSpecEnum) GetStaticType() Type { return Type(C._g_type_param_enum()) } //-------------------------------------------------------------- // ParamSpecFlags //-------------------------------------------------------------- type ParamSpecFlagsLike interface { InheritedFromGParamSpecFlags() *C.GParamSpecFlags } type ParamSpecFlags struct { ParamSpec } func ToParamSpecFlags(pspeclike ParamSpecFlagsLike) *ParamSpecFlags { t := (*ParamSpecFlags)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecFlags() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecFlags)(obj) } panic("cannot cast to ParamSpecFlags") } func (this *ParamSpecFlags) InheritedFromGParamSpecFlags() *C.GParamSpecFlags { return (*C.GParamSpecFlags)(this.C) } func (this *ParamSpecFlags) GetStaticType() Type { return Type(C._g_type_param_flags()) } //-------------------------------------------------------------- // ParamSpecFloat //-------------------------------------------------------------- type ParamSpecFloatLike interface { InheritedFromGParamSpecFloat() *C.GParamSpecFloat } type ParamSpecFloat struct { ParamSpec } func ToParamSpecFloat(pspeclike ParamSpecFloatLike) *ParamSpecFloat { t := (*ParamSpecFloat)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecFloat() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecFloat)(obj) } panic("cannot cast to ParamSpecFloat") } func (this *ParamSpecFloat) InheritedFromGParamSpecFloat() *C.GParamSpecFloat { return (*C.GParamSpecFloat)(this.C) } func (this *ParamSpecFloat) GetStaticType() Type { return Type(C._g_type_param_float()) } //-------------------------------------------------------------- // ParamSpecGType //-------------------------------------------------------------- type ParamSpecGTypeLike interface { InheritedFromGParamSpecGType() *C.GParamSpecGType } type ParamSpecGType struct { ParamSpec } func ToParamSpecGType(pspeclike ParamSpecGTypeLike) *ParamSpecGType { t := (*ParamSpecGType)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecGType() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecGType)(obj) } panic("cannot cast to ParamSpecGType") } func (this *ParamSpecGType) InheritedFromGParamSpecGType() *C.GParamSpecGType { return (*C.GParamSpecGType)(this.C) } func (this *ParamSpecGType) GetStaticType() Type { return Type(C._g_type_param_gtype()) } //-------------------------------------------------------------- // ParamSpecInt //-------------------------------------------------------------- type ParamSpecIntLike interface { InheritedFromGParamSpecInt() *C.GParamSpecInt } type ParamSpecInt struct { ParamSpec } func ToParamSpecInt(pspeclike ParamSpecIntLike) *ParamSpecInt { t := (*ParamSpecInt)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecInt() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecInt)(obj) } panic("cannot cast to ParamSpecInt") } func (this *ParamSpecInt) InheritedFromGParamSpecInt() *C.GParamSpecInt { return (*C.GParamSpecInt)(this.C) } func (this *ParamSpecInt) GetStaticType() Type { return Type(C._g_type_param_int()) } //-------------------------------------------------------------- // ParamSpecInt64 //-------------------------------------------------------------- type ParamSpecInt64Like interface { InheritedFromGParamSpecInt64() *C.GParamSpecInt64 } type ParamSpecInt64 struct { ParamSpec } func ToParamSpecInt64(pspeclike ParamSpecInt64Like) *ParamSpecInt64 { t := (*ParamSpecInt64)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecInt64() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecInt64)(obj) } panic("cannot cast to ParamSpecInt64") } func (this *ParamSpecInt64) InheritedFromGParamSpecInt64() *C.GParamSpecInt64 { return (*C.GParamSpecInt64)(this.C) } func (this *ParamSpecInt64) GetStaticType() Type { return Type(C._g_type_param_int64()) } //-------------------------------------------------------------- // ParamSpecLong //-------------------------------------------------------------- type ParamSpecLongLike interface { InheritedFromGParamSpecLong() *C.GParamSpecLong } type ParamSpecLong struct { ParamSpec } func ToParamSpecLong(pspeclike ParamSpecLongLike) *ParamSpecLong { t := (*ParamSpecLong)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecLong() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecLong)(obj) } panic("cannot cast to ParamSpecLong") } func (this *ParamSpecLong) InheritedFromGParamSpecLong() *C.GParamSpecLong { return (*C.GParamSpecLong)(this.C) } func (this *ParamSpecLong) GetStaticType() Type { return Type(C._g_type_param_long()) } //-------------------------------------------------------------- // ParamSpecObject //-------------------------------------------------------------- type ParamSpecObjectLike interface { InheritedFromGParamSpecObject() *C.GParamSpecObject } type ParamSpecObject struct { ParamSpec } func ToParamSpecObject(pspeclike ParamSpecObjectLike) *ParamSpecObject { t := (*ParamSpecObject)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecObject() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecObject)(obj) } panic("cannot cast to ParamSpecObject") } func (this *ParamSpecObject) InheritedFromGParamSpecObject() *C.GParamSpecObject { return (*C.GParamSpecObject)(this.C) } func (this *ParamSpecObject) GetStaticType() Type { return Type(C._g_type_param_object()) } //-------------------------------------------------------------- // ParamSpecOverride //-------------------------------------------------------------- type ParamSpecOverrideLike interface { InheritedFromGParamSpecOverride() *C.GParamSpecOverride } type ParamSpecOverride struct { ParamSpec } func ToParamSpecOverride(pspeclike ParamSpecOverrideLike) *ParamSpecOverride { t := (*ParamSpecOverride)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecOverride() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecOverride)(obj) } panic("cannot cast to ParamSpecOverride") } func (this *ParamSpecOverride) InheritedFromGParamSpecOverride() *C.GParamSpecOverride { return (*C.GParamSpecOverride)(this.C) } func (this *ParamSpecOverride) GetStaticType() Type { return Type(C._g_type_param_override()) } //-------------------------------------------------------------- // ParamSpecParam //-------------------------------------------------------------- type ParamSpecParamLike interface { InheritedFromGParamSpecParam() *C.GParamSpecParam } type ParamSpecParam struct { ParamSpec } func ToParamSpecParam(pspeclike ParamSpecParamLike) *ParamSpecParam { t := (*ParamSpecParam)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecParam() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecParam)(obj) } panic("cannot cast to ParamSpecParam") } func (this *ParamSpecParam) InheritedFromGParamSpecParam() *C.GParamSpecParam { return (*C.GParamSpecParam)(this.C) } func (this *ParamSpecParam) GetStaticType() Type { return Type(C._g_type_param_param()) } //-------------------------------------------------------------- // ParamSpecPointer //-------------------------------------------------------------- type ParamSpecPointerLike interface { InheritedFromGParamSpecPointer() *C.GParamSpecPointer } type ParamSpecPointer struct { ParamSpec } func ToParamSpecPointer(pspeclike ParamSpecPointerLike) *ParamSpecPointer { t := (*ParamSpecPointer)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecPointer() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecPointer)(obj) } panic("cannot cast to ParamSpecPointer") } func (this *ParamSpecPointer) InheritedFromGParamSpecPointer() *C.GParamSpecPointer { return (*C.GParamSpecPointer)(this.C) } func (this *ParamSpecPointer) GetStaticType() Type { return Type(C._g_type_param_pointer()) } //-------------------------------------------------------------- // ParamSpecString //-------------------------------------------------------------- type ParamSpecStringLike interface { InheritedFromGParamSpecString() *C.GParamSpecString } type ParamSpecString struct { ParamSpec } func ToParamSpecString(pspeclike ParamSpecStringLike) *ParamSpecString { t := (*ParamSpecString)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecString() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecString)(obj) } panic("cannot cast to ParamSpecString") } func (this *ParamSpecString) InheritedFromGParamSpecString() *C.GParamSpecString { return (*C.GParamSpecString)(this.C) } func (this *ParamSpecString) GetStaticType() Type { return Type(C._g_type_param_string()) } //-------------------------------------------------------------- // ParamSpecUChar //-------------------------------------------------------------- type ParamSpecUCharLike interface { InheritedFromGParamSpecUChar() *C.GParamSpecUChar } type ParamSpecUChar struct { ParamSpec } func ToParamSpecUChar(pspeclike ParamSpecUCharLike) *ParamSpecUChar { t := (*ParamSpecUChar)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecUChar() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecUChar)(obj) } panic("cannot cast to ParamSpecUChar") } func (this *ParamSpecUChar) InheritedFromGParamSpecUChar() *C.GParamSpecUChar { return (*C.GParamSpecUChar)(this.C) } func (this *ParamSpecUChar) GetStaticType() Type { return Type(C._g_type_param_uchar()) } //-------------------------------------------------------------- // ParamSpecUInt //-------------------------------------------------------------- type ParamSpecUIntLike interface { InheritedFromGParamSpecUInt() *C.GParamSpecUInt } type ParamSpecUInt struct { ParamSpec } func ToParamSpecUInt(pspeclike ParamSpecUIntLike) *ParamSpecUInt { t := (*ParamSpecUInt)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecUInt() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecUInt)(obj) } panic("cannot cast to ParamSpecUInt") } func (this *ParamSpecUInt) InheritedFromGParamSpecUInt() *C.GParamSpecUInt { return (*C.GParamSpecUInt)(this.C) } func (this *ParamSpecUInt) GetStaticType() Type { return Type(C._g_type_param_uint()) } //-------------------------------------------------------------- // ParamSpecUInt64 //-------------------------------------------------------------- type ParamSpecUInt64Like interface { InheritedFromGParamSpecUInt64() *C.GParamSpecUInt64 } type ParamSpecUInt64 struct { ParamSpec } func ToParamSpecUInt64(pspeclike ParamSpecUInt64Like) *ParamSpecUInt64 { t := (*ParamSpecUInt64)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecUInt64() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecUInt64)(obj) } panic("cannot cast to ParamSpecUInt64") } func (this *ParamSpecUInt64) InheritedFromGParamSpecUInt64() *C.GParamSpecUInt64 { return (*C.GParamSpecUInt64)(this.C) } func (this *ParamSpecUInt64) GetStaticType() Type { return Type(C._g_type_param_uint64()) } //-------------------------------------------------------------- // ParamSpecULong //-------------------------------------------------------------- type ParamSpecULongLike interface { InheritedFromGParamSpecULong() *C.GParamSpecULong } type ParamSpecULong struct { ParamSpec } func ToParamSpecULong(pspeclike ParamSpecULongLike) *ParamSpecULong { t := (*ParamSpecULong)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecULong() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecULong)(obj) } panic("cannot cast to ParamSpecULong") } func (this *ParamSpecULong) InheritedFromGParamSpecULong() *C.GParamSpecULong { return (*C.GParamSpecULong)(this.C) } func (this *ParamSpecULong) GetStaticType() Type { return Type(C._g_type_param_ulong()) } //-------------------------------------------------------------- // ParamSpecUnichar //-------------------------------------------------------------- type ParamSpecUnicharLike interface { InheritedFromGParamSpecUnichar() *C.GParamSpecUnichar } type ParamSpecUnichar struct { ParamSpec } func ToParamSpecUnichar(pspeclike ParamSpecUnicharLike) *ParamSpecUnichar { t := (*ParamSpecUnichar)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecUnichar() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecUnichar)(obj) } panic("cannot cast to ParamSpecUnichar") } func (this *ParamSpecUnichar) InheritedFromGParamSpecUnichar() *C.GParamSpecUnichar { return (*C.GParamSpecUnichar)(this.C) } func (this *ParamSpecUnichar) GetStaticType() Type { return Type(C._g_type_param_unichar()) } //-------------------------------------------------------------- // ParamSpecValueArray //-------------------------------------------------------------- type ParamSpecValueArrayLike interface { InheritedFromGParamSpecValueArray() *C.GParamSpecValueArray } type ParamSpecValueArray struct { ParamSpec } func ToParamSpecValueArray(pspeclike ParamSpecValueArrayLike) *ParamSpecValueArray { t := (*ParamSpecValueArray)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecValueArray() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecValueArray)(obj) } panic("cannot cast to ParamSpecValueArray") } func (this *ParamSpecValueArray) InheritedFromGParamSpecValueArray() *C.GParamSpecValueArray { return (*C.GParamSpecValueArray)(this.C) } func (this *ParamSpecValueArray) GetStaticType() Type { return Type(C._g_type_param_value_array()) } //-------------------------------------------------------------- // ParamSpecVariant //-------------------------------------------------------------- type ParamSpecVariantLike interface { InheritedFromGParamSpecVariant() *C.GParamSpecVariant } type ParamSpecVariant struct { ParamSpec } func ToParamSpecVariant(pspeclike ParamSpecVariantLike) *ParamSpecVariant { t := (*ParamSpecVariant)(nil).GetStaticType() c := pspeclike.InheritedFromGParamSpecVariant() obj := ParamSpecGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*ParamSpecVariant)(obj) } panic("cannot cast to ParamSpecVariant") } func (this *ParamSpecVariant) InheritedFromGParamSpecVariant() *C.GParamSpecVariant { return (*C.GParamSpecVariant)(this.C) } func (this *ParamSpecVariant) GetStaticType() Type { return Type(C._g_type_param_variant()) } go-gir-generator-master/lib.in/gtk-2.0/000077500000000000000000000000001414263242200177545ustar00rootroot00000000000000go-gir-generator-master/lib.in/gtk-2.0/config.json000066400000000000000000000104401414263242200221130ustar00rootroot00000000000000{ "namespace": "Gtk", "version": "2.0", "blacklist": { "objects": [ "Accessible", "Application", "LockButton", "MountOperation", "NumerableIcon", "PageSetup", "PrintSettings", "PrintContext", "PrintOperation" ], "structs": [ "PaperSize" ], "callbacks": [ "AccelMapForeach", "PageSetupDoneFunc", "RcPropertyParser", "CTreeGNodeFunc", "ClipboardRichTextReceivedFunc", "MenuPositionFunc", "TextBufferDeserializeFunc", "TextBufferSerializeFunc" ], "functions": [ "binding_entry_add_signal_from_string", "binding_entry_add_signall", "binding_entry_remove", "binding_entry_skip", "binding_entry_clear", "binding_set_find", "binding_parse_binding", "paper_size_get_default", "paper_size_get_paper_sizes", "rc_property_parse_border", "rc_property_parse_color", "rc_property_parse_enum", "rc_property_parse_flags", "rc_property_parse_requisition", "stock_add", "print_run_page_setup_dialog", "print_run_page_setup_dialog_async", "init_with_args", "rc_parse_color", "rc_parse_color_full", "rc_parse_priority", "rc_parse_state", "rc_find_pixmap_in_path", "stock_set_translate_func", "tree_row_reference_deleted", "tree_row_reference_inserted", "tree_row_reference_reordered", "signal_newv" ] }, "method-blacklist": { "ActionGroup": [ "add_actions_full", "add_radio_actions_full", "add_toggle_actions_full" ], "AccelMap": [ "foreach", "foreach_unfiltered", "load_scanner" ], "BindingEntry": [ "add_signal_from_string" ], "Builder": [ "value_from_string" ], "Buildable": [ "custom_tag_start" ], "Box": [ "query_child_packing" ], "CList": [ "get_pixtext", "get_selection_info", "set_row_data_full" ], "CTree": [ "get_node_info", "node_get_pixtext", "node_set_row_data_full" ], "ComboBox": [ "new_text", "get_popup_accessible" ], "ColorSelection": [ "get_color", "set_color" ], "IconView": [ "get_dest_item_at_pos", "get_drag_dest_item" ], "IconInfo": [ "get_attach_points" ], "IconTheme": [ "get_search_path" ], "ItemFactory": [ "popup_with_data" ], "IMContextSimple": [ "add_table" ], "Widget": [ "get_accessible" ], "ListStore": [ "insert_with_valuesv", "set", "set_valuesv" ], "TreeStore": [ "insert_with_valuesv", "insert_with_values", "set", "set_valuesv" ], "Menu": [ "popup_for_device", "attach_to_widget" ], "MenuItem": [ "toggle_size_request" ], "Notebook": [ "query_tab_label_packing" ], "Preview": [ "draw_row" ], "SelectionData": [ "get_data", "get_text" ], "StatusIcon": [ "position_menu" ], "TargetList": [ "find" ], "TextBuffer": [ "register_deserialize_format", "register_serialize_format" ], "TextLayout": [ "get_iter_at_position", "get_line_at_y", "get_line_yrange", "get_lines", "get_size" ], "TreeSortable": [ "get_sort_column_id" ], "TreeView": [ "set_hadjustment", "set_vadjustment", "tree_to_widget_coords", "widget_to_tree_coords" ], "TreeViewColumn": [ "cell_get_position" ], "TreeModel": [ "rows_reordered" ], "TreePath": [ "get_indices" ], "TreeRowReference": [ "reordered" ], "RcProperty": [ "parse_border", "parse_color", "parse_enum", "parse_flags", "parse_requisition" ], "Settings": [ "install_property", "install_property_parser" ], "StyleProvider": [ "get_style_property" ], "Window": [ "get_application", "set_application", "get_default_size" ], "Clipboard": [ "request_rich_text" ], "Object": [ "set_data_by_id_full", "set_data_full", "weakref", "weakunref" ] }, "method-whitelist": { "AppChooser": [] }, "renames": { "Dialog.AddButton": "_AddButton", "Widget.SetHexpand": "SetHExpand", "Widget.SetVexpand": "SetVExpand", "Widget.SetHexpandSet": "SetHExpandSet", "Widget.SetVexpandSet": "SetVExpandSet", "Widget.GetHexpand": "GetHExpand", "Widget.GetVexpand": "GetVExpand", "Widget.GetHexpandSet": "GetHExpandSet", "Widget.GetVexpandSet": "GetVExpandSet", "NewTreeStore": "_NewTreeStore", "TreeStore.Append": "_Append", "NewListStore": "_NewListStore", "ListStore.Append": "_Append" } } go-gir-generator-master/lib.in/gtk-2.0/gtk.go.in000066400000000000000000000070571414263242200215060ustar00rootroot00000000000000package gtk /* #include "gtk.gen.h" [<.g_object_ref_unref>] [<.g_free>] [<.g_error_free>] extern GtkWidget *gtk_message_dialog_new(GtkWindow*, GtkDialogFlags, GtkMessageType, GtkButtonsType, const char *msg); */ import "C" import "unsafe" import "errors" import "fmt" // package dependencies import ( "gobject/gdk-2.0" "gobject/gdkpixbuf-2.0" "gobject/gobject-2.0" "gobject/gio-2.0" "gobject/pango-1.0" "gobject/atk-1.0" ) [<.go_utils>] [<.go_bindings>] //---------------------------------------------------------------------------- // Dialog //---------------------------------------------------------------------------- func NewDialogWithButtons(title string, parent *Window, flags DialogFlags, buttons ...interface{}) *Dialog { dialog := NewDialog() if title != "" { dialog.SetTitle(title) } if parent != nil { dialog.SetTransientFor(parent) } if flags & DialogFlagsModal != 0 { dialog.SetModal(true) } if flags & DialogFlagsDestroyWithParent != 0 { dialog.SetDestroyWithParent(true) } if len(buttons) == 0 { return dialog } if len(buttons) & 1 != 0 { panic("the number of button specs should be even (name/response pairs)") } var ok bool var text string var response ResponseType for i, spec := range buttons { if i & 1 == 0 { text, ok = spec.(string) if !ok { panic("non-string button text") } } else { response, ok = spec.(ResponseType) if !ok { panic("non-ResponseType button response") } dialog._AddButton(text, int(response)) } } return dialog } func (this *Dialog) AddButton(text string, response ResponseType) *Widget { return this._AddButton(text, int(response)) } //---------------------------------------------------------------------------- // MessageDialog //---------------------------------------------------------------------------- func NewMessageDialogWithMarkup(parent0 WindowLike, flags0 DialogFlags, type0 MessageType, buttons0 ButtonsType, format string, args ...interface{}) *MessageDialog { var parent1 *C.GtkWindow var flags1 C.GtkDialogFlags var type1 C.GtkMessageType var buttons1 C.GtkButtonsType if parent0 != nil { parent1 = parent0.InheritedFromGtkWindow() } flags1 = C.GtkDialogFlags(flags0) type1 = C.GtkMessageType(type0) buttons1 = C.GtkButtonsType(buttons0) ret1 := C.gtk_message_dialog_new(parent1, flags1, type1, buttons1, nil) var ret2 *MessageDialog ret2 = (*MessageDialog)(gobject.ObjectWrap(unsafe.Pointer(ret1), true)) ret2.SetMarkup(fmt.Sprintf(format, args...)) return ret2 } //---------------------------------------------------------------------------- // TreeStore //---------------------------------------------------------------------------- func NewTreeStore(types ...gobject.Type) *TreeStore { return _NewTreeStore(types) } func (this *TreeStore) Append(parent *TreeIter, values ...interface{}) TreeIter { iter := this._Append(parent) for i, v := range values { var gvalue gobject.Value gvalue.Init(this.GetColumnType(i)) gvalue.SetGoInterface(v) this.SetValue(&iter, i, &gvalue) gvalue.Unset() } return iter } //---------------------------------------------------------------------------- // ListStore //---------------------------------------------------------------------------- func NewListStore(types ...gobject.Type) *ListStore { return _NewListStore(types) } func (this *ListStore) Append(values ...interface{}) TreeIter { iter := this._Append() for i, v := range values { var gvalue gobject.Value gvalue.Init(this.GetColumnType(i)) gvalue.SetGoInterface(v) this.SetValue(&iter, i, &gvalue) gvalue.Unset() } return iter } go-gir-generator-master/lib.in/gtk-3.0/000077500000000000000000000000001414263242200177555ustar00rootroot00000000000000go-gir-generator-master/lib.in/gtk-3.0/config.json000066400000000000000000000054661414263242200221300ustar00rootroot00000000000000{ "namespace": "Gtk", "version": "3.0", "blacklist": { "structs": [ "StockItem" // implemented manually ], "structdefs": [ // implemented manually "ActionEntry", "RadioActionEntry", "ToggleActionEntry" ], "callbacks": [ "AccelMapForeach", "RcPropertyParser", // uses glib.String // mess with void* or byte[] "ClipboardRichTextReceivedFunc", "TextBufferDeserializeFunc", "TextBufferSerializeFunc" ], "functions": [ "accelerator_parse_with_keycode", "binding_entry_add_signal_from_string", "binding_entry_add_signall", "binding_entry_remove", "binding_entry_skip", "binding_set_find", "paper_size_get_default", "paper_size_get_paper_sizes", "rc_property_parse_border", "rc_property_parse_color", "rc_property_parse_enum", "rc_property_parse_flags", "rc_property_parse_requisition", "print_run_page_setup_dialog", "print_run_page_setup_dialog_async", "init_with_args", "stock_add", // implemented manually and renamed to StockAddItems (name clash) "stock_lookup", // implemented manually "stock_add_static", // doesn't make sense "rc_parse_color", "rc_parse_color_full", "rc_parse_priority", "rc_parse_state", "rc_find_pixmap_in_path", "stock_set_translate_func", "tree_row_reference_deleted", "tree_row_reference_inserted" ] }, "method-blacklist": { "AccelMap": [ "foreach", // broken annotation "foreach_unfiltered", // broken annotation "load_scanner" // uses glib.Scanner ], "Buildable": [ "custom_tag_start" // uses glib.MarkupParser ], "ListStore": [ "reorder", // buggy "insert_with_valuesv", // to be implemented manually "set" // implemented manually ], "TreeStore": [ "insert_with_valuesv", // to be implemented manually "insert_with_values", // to be implemented manually "set" // implemented manually ], "Menu": [ "attach_to_widget", // it uses callback which has no userdata "popup" // implemented manually ], "MenuItem": [ "toggle_size_request" ], "TextBuffer": [ "register_deserialize_format", "register_serialize_format" ], "TreeView": [ // these two are deprecated "set_hadjustment", "set_vadjustment" ], "RcProperty": [ "parse_border", "parse_color", "parse_enum", "parse_flags", "parse_requisition" ], "Settings": [ "install_property", "install_property_parser" ], "StyleProvider": [ "get_style_property" ], "Clipboard": [ "request_rich_text" ], "Builder": [ "connect_signals" // custom implementation ] }, "renames": { "Main": "_Main", "InfoBar.AddButton": "_AddButton", "Dialog.AddButton": "_AddButton", "Dialog.Run": "_Run", "NewTreeStore": "_NewTreeStore", "TreeStore.Append": "_Append", "NewListStore": "_NewListStore", "ListStore.Append": "_Append" } } go-gir-generator-master/lib.in/gtk-3.0/gtk.go.in000066400000000000000000000402411414263242200214770ustar00rootroot00000000000000package gtk /* #include "gtk.gen.h" [<.g_object_ref_unref>] [<.g_free>] [<.g_error_free>] #include "gtk.h" extern GtkWidget *gtk_message_dialog_new(GtkWindow*, GtkDialogFlags, GtkMessageType, GtkButtonsType, const char *msg); */ import "C" import "unsafe" import "errors" import "reflect" import "fmt" // package dependencies import ( "gobject/gdk-3.0" "gobject/gdkpixbuf-2.0" "gobject/gobject-2.0" "gobject/gio-2.0" "gobject/cairo-1.0" "gobject/pango-1.0" "gobject/atk-1.0" "gobject/glib-2.0" ) [<.go_utils>] [<.go_bindings>] //---------------------------------------------------------------------------- // Custom utils //---------------------------------------------------------------------------- func for_pairs(slice []interface{}, closure func(key, value interface{})) { if len(slice) & 1 != 0 { panic("the number of arguments must be even (key/value pairs)") } var key interface{} for i, value := range slice { if i & 1 == 0 { key = value } else { closure(key, value) } } } func panic_if_not_type(ok bool, expected_type string, value interface{}) { if !ok { msg := fmt.Sprintf("expected type for argument: %s, got: %T", expected_type, value) panic(msg) } } //---------------------------------------------------------------------------- // Main //---------------------------------------------------------------------------- func Main() { gobject.FQueue.Start(100) _Main() gobject.FQueue.Stop() } //---------------------------------------------------------------------------- // TreePath //---------------------------------------------------------------------------- func NewTreePathFromIndices(indices ...int) *TreePath { this := NewTreePath() for _, i := range indices { this.AppendIndex(i) } return this } //---------------------------------------------------------------------------- // TreeViewColumn //---------------------------------------------------------------------------- func NewTreeViewColumnWithAttributes(title string, renderer CellRendererLike, attrs ...interface{}) *TreeViewColumn { c := NewTreeViewColumn() c.SetTitle(title) c.PackStart(renderer, true) for_pairs(attrs, func(key, value interface{}) { attr_name, ok := key.(string) panic_if_not_type(ok, "string", key) attr_col, ok := value.(int) panic_if_not_type(ok, "int", value) c.AddAttribute(renderer, attr_name, attr_col) }) return c } //---------------------------------------------------------------------------- // CellLayout //---------------------------------------------------------------------------- func (this *CellLayoutImpl) SetAttributes(renderer CellRendererLike, attrs ...interface{}) { this.ClearAttributes(renderer) for_pairs(attrs, func(key, value interface{}) { attr_name, ok := key.(string) panic_if_not_type(ok, "string", key) attr_col, ok := value.(int) panic_if_not_type(ok, "int", value) this.AddAttribute(renderer, attr_name, attr_col) }) } //---------------------------------------------------------------------------- // InfoBar //---------------------------------------------------------------------------- func NewInfoBarWithButtons(buttons ...interface{}) *InfoBar { bar := NewInfoBar() for_pairs(buttons, func(key, value interface{}) { text, ok := key.(string) panic_if_not_type(ok, "string", key) response, ok := value.(ResponseType) panic_if_not_type(ok, "ResponseType", value) bar.AddButton(text, response) }) return bar } func (this *InfoBar) AddButton(text string, response ResponseType) *Widget { return this._AddButton(text, int(response)) } //---------------------------------------------------------------------------- // Dialog //---------------------------------------------------------------------------- func NewDialogWithButtons(title string, parent *Window, flags DialogFlags, buttons ...interface{}) *Dialog { dialog := NewDialog() if title != "" { dialog.SetTitle(title) } if parent != nil { dialog.SetTransientFor(parent) } if flags & DialogFlagsModal != 0 { dialog.SetModal(true) } if flags & DialogFlagsDestroyWithParent != 0 { dialog.SetDestroyWithParent(true) } for_pairs(buttons, func(key, value interface{}) { text, ok := key.(string) panic_if_not_type(ok, "string", key) response, ok := value.(ResponseType) panic_if_not_type(ok, "ResponseType", value) dialog.AddButton(text, response) }) return dialog } func (this *Dialog) AddButton(text string, response ResponseType) *Widget { return this._AddButton(text, int(response)) } func (this *Dialog) Run() ResponseType { return ResponseType(this._Run()) } //---------------------------------------------------------------------------- // MessageDialog //---------------------------------------------------------------------------- func NewMessageDialog(parent0 WindowLike, flags0 DialogFlags, type0 MessageType, buttons0 ButtonsType, format string, args ...interface{}) *MessageDialog { var parent1 *C.GtkWindow var flags1 C.GtkDialogFlags var type1 C.GtkMessageType var buttons1 C.GtkButtonsType if parent0 != nil { parent1 = parent0.InheritedFromGtkWindow() } flags1 = C.GtkDialogFlags(flags0) type1 = C.GtkMessageType(type0) buttons1 = C.GtkButtonsType(buttons0) ret1 := C.gtk_message_dialog_new(parent1, flags1, type1, buttons1, nil) var ret2 *MessageDialog ret2 = (*MessageDialog)(gobject.ObjectWrap(unsafe.Pointer(ret1), true)) ret2.SetProperty("text", fmt.Sprintf(format, args...)) return ret2 } func NewMessageDialogWithMarkup(parent0 WindowLike, flags0 DialogFlags, type0 MessageType, buttons0 ButtonsType, format string, args ...interface{}) *MessageDialog { var parent1 *C.GtkWindow var flags1 C.GtkDialogFlags var type1 C.GtkMessageType var buttons1 C.GtkButtonsType if parent0 != nil { parent1 = parent0.InheritedFromGtkWindow() } flags1 = C.GtkDialogFlags(flags0) type1 = C.GtkMessageType(type0) buttons1 = C.GtkButtonsType(buttons0) ret1 := C.gtk_message_dialog_new(parent1, flags1, type1, buttons1, nil) var ret2 *MessageDialog ret2 = (*MessageDialog)(gobject.ObjectWrap(unsafe.Pointer(ret1), true)) ret2.SetMarkup(fmt.Sprintf(format, args...)) return ret2 } func (this *Dialog) FormatSecondaryText(format string, args ...interface{}) { this.SetProperty("secondary-use-markup", false) this.SetProperty("secondary-text", fmt.Sprintf(format, args...)) } func (this *Dialog) FormatSecondaryMarkup(format string, args ...interface{}) { this.SetProperty("secondary-use-markup", true) this.SetProperty("secondary-text", fmt.Sprintf(format, args...)) } //---------------------------------------------------------------------------- // TextBuffer //---------------------------------------------------------------------------- func (this *TextBuffer) CreateTag(tag_name string, properties ...interface{}) *TextTag { tag := NewTextTag(tag_name) for_pairs(properties, func(key, value interface{}) { name, ok := key.(string) panic_if_not_type(ok, "string", key) tag.SetProperty(name, value) }) this.GetTagTable().Add(tag) return tag } func (this *TextBuffer) InsertWithTags(iter *TextIter, text string, length int, tags ...*TextTag) { start_offset := iter.GetOffset() this.Insert(iter, text, length) if len(tags) == 0 { return } start := this.GetIterAtOffset(start_offset) for _, tag := range tags { this.ApplyTag(tag, &start, iter) } } func (this *TextBuffer) InsertWithTagsByName(iter *TextIter, text string, length int, tags ...string) { start_offset := iter.GetOffset() this.Insert(iter, text, length) if len(tags) == 0 { return } start := this.GetIterAtOffset(start_offset) for _, tag := range tags { this.ApplyTagByName(tag, &start, iter) } } //---------------------------------------------------------------------------- // TreeStore //---------------------------------------------------------------------------- func NewTreeStore(types ...gobject.Type) *TreeStore { return _NewTreeStore(types) } func (this *TreeStore) Append(parent *TreeIter, values ...interface{}) TreeIter { iter := this._Append(parent) for i, v := range values { var gvalue gobject.Value gvalue.Init(this.GetColumnType(i)) gvalue.SetGoInterface(v) this.SetValue(&iter, i, &gvalue) gvalue.Unset() } return iter } func (this *TreeStore) Set(iter *TreeIter, columnspecs ...interface{}) { for_pairs(columnspecs, func(key, value interface{}) { column, ok := key.(int) panic_if_not_type(ok, "int", key) var gvalue gobject.Value gvalue.Init(this.GetColumnType(column)) gvalue.SetGoInterface(value) this.SetValue(iter, column, &gvalue) gvalue.Unset() }) } //---------------------------------------------------------------------------- // ListStore //---------------------------------------------------------------------------- func NewListStore(types ...gobject.Type) *ListStore { return _NewListStore(types) } func (this *ListStore) Append(values ...interface{}) TreeIter { iter := this._Append() for i, v := range values { var gvalue gobject.Value gvalue.Init(this.GetColumnType(i)) gvalue.SetGoInterface(v) this.SetValue(&iter, i, &gvalue) gvalue.Unset() } return iter } func (this *ListStore) Set(iter *TreeIter, columnspecs ...interface{}) { for_pairs(columnspecs, func(key, value interface{}) { column, ok := key.(int) panic_if_not_type(ok, "int", key) var gvalue gobject.Value gvalue.Init(this.GetColumnType(column)) gvalue.SetGoInterface(value) this.SetValue(iter, column, &gvalue) gvalue.Unset() }) } //---------------------------------------------------------------------------- // TreeModelImpl //---------------------------------------------------------------------------- func (this *TreeModelImpl) Get(iter *TreeIter, columnspecs ...interface{}) { for_pairs(columnspecs, func(key, value interface{}) { column, ok := key.(int) panic_if_not_type(ok, "int", key) gvalue := this.GetValue(iter, column) gvalue.GetGoInterface(value) gvalue.Unset() }) } //---------------------------------------------------------------------------- // ActionGroup and related structs //---------------------------------------------------------------------------- type ActionEntry struct { Name string StockID string Label string Accelerator string Tooltip string Callback interface{} } type ToggleActionEntry struct { Name string StockID string Label string Accelerator string Tooltip string Callback interface{} IsActive bool } type RadioActionEntry struct { Name string StockID string Label string Accelerator string Tooltip string Value int } func (this *ActionGroup) AddActions(actions []ActionEntry) { for i := range actions { a := &actions[i] action := NewAction(a.Name, a.Label, a.Tooltip, a.StockID) if a.Callback != nil { action.Connect("activate", a.Callback) } this.AddActionWithAccel(action, a.Accelerator) } } func (this *ActionGroup) AddToggleActions(actions []ToggleActionEntry) { for i := range actions { a := &actions[i] action := NewToggleAction(a.Name, a.Label, a.Tooltip, a.StockID) action.SetActive(a.IsActive) if a.Callback != nil { action.Connect("activate", a.Callback) } this.AddActionWithAccel(action, a.Accelerator) } } func (this *ActionGroup) AddRadioActions(actions []RadioActionEntry, value int, on_change interface{}) { if len(actions) == 0 { return } var group *C.GSList var first_action *RadioAction for i := range actions { a := &actions[i] action := NewRadioAction(a.Name, a.Label, a.Tooltip, a.StockID, a.Value) if i == 0 { first_action = action } C.gtk_radio_action_set_group(action.InheritedFromGtkRadioAction(), group) group = C.gtk_radio_action_get_group(action.InheritedFromGtkRadioAction()) if a.Value == value { action.SetActive(true) } this.AddActionWithAccel(action, a.Accelerator) } if on_change != nil { first_action.Connect("changed", on_change) } } //---------------------------------------------------------------------------- // Container //---------------------------------------------------------------------------- func (this *Container) FindChildProperty(name string) *gobject.ParamSpec { cname := C.CString(name) ret := C._gtk_container_find_child_property(this.InheritedFromGtkContainer(), cname) C.free(unsafe.Pointer(cname)) return (*gobject.ParamSpec)(gobject.ParamSpecWrap(unsafe.Pointer(ret), true)) } func (this *Container) ChildGet(child WidgetLike, props ...interface{}) { for_pairs(props, func(key, value interface{}) { name, ok := key.(string) panic_if_not_type(ok, "string", key) pspec := this.FindChildProperty(name) if pspec == nil { panic("Container has no property with that name: " + name) } var gvalue gobject.Value gvalue.Init(pspec.GetValueType()) this.ChildGetProperty(child, name, &gvalue) gvalue.GetGoInterface(value) gvalue.Unset() }) } func (this *Container) ChildSet(child WidgetLike, props ...interface{}) { for_pairs(props, func(key, value interface{}) { name, ok := key.(string) panic_if_not_type(ok, "string", key) pspec := this.FindProperty(name) if pspec == nil { panic("Container has no property with that name: " + name) } var gvalue gobject.Value gvalue.Init(pspec.GetValueType()) gvalue.SetGoInterface(value) this.ChildSetProperty(child, name, &gvalue) gvalue.Unset() }) } //---------------------------------------------------------------------------- // Builder //---------------------------------------------------------------------------- func (this *Builder) ConnectSignals(recv interface{}) { t := reflect.TypeOf(recv) this.ConnectSignalsFull(func(builder *Builder, object *gobject.Object, signal_name, handler_name string, connect_object *gobject.Object, flags gobject.ConnectFlags) { // TODO: I'm ignoring here a lot is it ok? meth, ok := t.MethodByName(handler_name) if !ok { println("could not find signal handler: '" + handler_name + "'") return } object.ConnectMethod(signal_name, meth.Func.Interface(), recv) }) } //---------------------------------------------------------------------------- // StockItem //---------------------------------------------------------------------------- type StockItem struct { StockID string Label string Modifier gdk.ModifierType Keyval uint32 TranslationDomain string } func (this *StockItem) alloc_c(c *_CStockItem) { c.StockID = _GoStringToGString(this.StockID) c.Label = _GoStringToGString(this.Label) c.Modifier = C.GdkModifierType(this.Modifier) c.Keyval = C.uint32_t(this.Keyval) c.TranslationDomain = _GoStringToGString(this.TranslationDomain) } type _CStockItem struct { StockID *C.char Label *C.char Modifier C.GdkModifierType Keyval C.uint32_t TranslationDomain *C.char } func (this *_CStockItem) free() { if this.StockID != nil { C.free(unsafe.Pointer(this.StockID)) } if this.Label != nil { C.free(unsafe.Pointer(this.Label)) } if this.TranslationDomain != nil { C.free(unsafe.Pointer(this.TranslationDomain)) } } func StockAddItems(items []StockItem) { citems := make([]_CStockItem, len(items)) for i, item := range items { item.alloc_c(&citems[i]) defer citems[i].free() } first := (*C.GtkStockItem)(unsafe.Pointer(&citems[0])) C.gtk_stock_add(first, C.uint32_t(len(citems))) } func StockLookup(stock_id string) (StockItem, bool) { var stockitem StockItem var cstockitem _CStockItem cstock_id := _GoStringToGString(stock_id) ok := C.gtk_stock_lookup(cstock_id, (*C.GtkStockItem)(unsafe.Pointer(&cstockitem))) != 0 C.free(unsafe.Pointer(cstock_id)) if !ok { return stockitem, false } if cstockitem.StockID != nil { stockitem.StockID = C.GoString(cstockitem.StockID) } if cstockitem.Label != nil { stockitem.Label = C.GoString(cstockitem.Label) } if cstockitem.TranslationDomain != nil { stockitem.TranslationDomain = C.GoString(cstockitem.TranslationDomain) } stockitem.Keyval = uint32(cstockitem.Keyval) stockitem.Modifier = gdk.ModifierType(cstockitem.Modifier) return stockitem, true } //---------------------------------------------------------------------------- // Menu //---------------------------------------------------------------------------- func (this *Menu) Popup(parent_menu_shell WidgetLike, parent_menu_item WidgetLike, func_ MenuPositionFunc, button int, activate_time int) { this.PopupForDevice(nil, parent_menu_shell, parent_menu_item, func_, button, activate_time) } func (this *Menu) AttachToWidget(attach_widget0 WidgetLike) { C.gtk_menu_attach_to_widget(this.InheritedFromGtkMenu(), attach_widget0.InheritedFromGtkWidget(), nil) } go-gir-generator-master/lib.in/gtksource-3.0/000077500000000000000000000000001414263242200211765ustar00rootroot00000000000000go-gir-generator-master/lib.in/gtksource-3.0/config.json000066400000000000000000000000611414263242200233330ustar00rootroot00000000000000{ "namespace": "GtkSource", "version": "3.0" } go-gir-generator-master/lib.in/gtksource-3.0/gtksource.go.in000066400000000000000000000005551414263242200241450ustar00rootroot00000000000000package gtksource /* #include "gtksource.gen.h" [<.g_object_ref_unref>] [<.g_error_free>] [<.g_free>] */ import "C" import "unsafe" import "errors" // package dependencies import ( "gobject/gobject-2.0" "gobject/gdkpixbuf-2.0" "gobject/gdk-3.0" "gobject/gtk-3.0" "gobject/cairo-1.0" "gobject/gio-2.0" "gobject/atk-1.0" ) [<.go_utils>] [<.go_bindings>] go-gir-generator-master/lib.in/gudev-1.0/000077500000000000000000000000001414263242200203005ustar00rootroot00000000000000go-gir-generator-master/lib.in/gudev-1.0/config.json000066400000000000000000000000631414263242200224370ustar00rootroot00000000000000{ "namespace": "GUdev", "version": "1.0" } go-gir-generator-master/lib.in/gudev-1.0/fixwarning.go000066400000000000000000000002031414263242200227760ustar00rootroot00000000000000package gudev import "C" import "unsafe" //export _GUdev_go_callback_cleanup func _GUdev_go_callback_cleanup(unsafe.Pointer) { } go-gir-generator-master/lib.in/gudev-1.0/gudev.go.in000066400000000000000000000003151414263242200223450ustar00rootroot00000000000000package gudev /* #include "gudev.gen.h" [<.g_list_funcs>] #cgo pkg-config: gudev-1.0 */ import "C" import "unsafe" import ( "pkg.deepin.io/gir/gobject-2.0" ) [<.go_utils_no_cb>] [<.go_bindings>] go-gir-generator-master/lib.in/gudev-1.0/gudev_test.go000066400000000000000000000006401414263242200230000ustar00rootroot00000000000000package gudev import ( "testing" ) func TestClient(t *testing.T) { subsystems := []string{"power_supply"} client := NewClient(subsystems) t.Log("client:", client) devices := client.QueryBySubsystem("power_supply") for _, device := range devices { t.Log("device",device) sysfsPath := device.GetSysfsPath() t.Log("sysfs path:", sysfsPath) } client.Unref() } go-gir-generator-master/lib.in/pango-1.0/000077500000000000000000000000001414263242200202725ustar00rootroot00000000000000go-gir-generator-master/lib.in/pango-1.0/config.json000066400000000000000000000014751414263242200224410ustar00rootroot00000000000000{ "namespace": "Pango", "version": "1.0", "method-blacklist": { "AttrIterator": [ "range" ], "Attribute": [ "init" ], "Coverage": [ "to_bytes" ], "FontFace": [ "list_sizes" ], "GlyphItem": [ "get_logical_widths" ], "GlyphString": [ "get_logical_widths", "index_to_x", "x_to_index" ], "Language": [ "get_scripts" ], "Layout": [ "get_log_attrs_readonly", "move_cursor_visually" ], "TabArray": [ "get_tabs" ] }, "blacklist": { "functions": [ "find_paragraph_boundary", "font_description_from_string", "get_mirror_char", "language_from_string", "language_get_default", "log2vis_get_embedding_levels", "parse_stretch", "parse_style", "parse_variant", "parse_weight", "read_line", "scan_string", "scan_word" ] } } go-gir-generator-master/lib.in/pango-1.0/pango.go.in000066400000000000000000000004261414263242200223340ustar00rootroot00000000000000package pango /* #include "pango.gen.h" [<.g_object_ref_unref>] [<.g_free>] [<.g_error_free>] #cgo pkg-config: pango */ import "C" import "unsafe" import "errors" // package dependencies import ( "gobject/gobject-2.0" "gobject/glib-2.0" ) [<.go_utils>] [<.go_bindings>] go-gir-generator-master/lib.in/pangocairo-1.0/000077500000000000000000000000001414263242200213105ustar00rootroot00000000000000go-gir-generator-master/lib.in/pangocairo-1.0/config.json000066400000000000000000000004021414263242200234440ustar00rootroot00000000000000{ "namespace": "PangoCairo", "version": "1.0", "blacklist": { "functions": [ "font_map_new_for_font_type", "font_map_get_default", "font_map_new" ] }, "method-blacklist": { "FontMap": [ "new_for_font_type", "get_font_type" ] } } go-gir-generator-master/lib.in/pangocairo-1.0/pangocairo.go.in000066400000000000000000000004151414263242200243660ustar00rootroot00000000000000package pangocairo /* #include "pangocairo.gen.h" [<.g_object_ref_unref>] [<.g_free>] [<.g_error_free>] */ import "C" import "unsafe" // package dependencies import ( "gobject/cairo-1.0" "gobject/gobject-2.0" "gobject/pango-1.0" ) [<.go_utils>] [<.go_bindings>]go-gir-generator-master/rpm/000077500000000000000000000000001414263242200163155ustar00rootroot00000000000000go-gir-generator-master/rpm/go-gir-generator.spec000066400000000000000000000031521414263242200223420ustar00rootroot00000000000000#add 2020-04-26 %global _unpackaged_files_terminate_build 0 %global with_debug 1 %if 0%{?with_debug} %global debug_package %{nil} %endif Name: go-gir-generator Version: 2.0.5 Release: 1 Summary: Generate static golang bindings for GObject License: GPLv3 URL: ssh://gerrit.uniontech.com:29418/go-gir-generator Source0: %{name}-%{version}.orig.tar.xz #Patch0: SettingsBackendLike.patch # https://cr.deepin.io/#/c/go-gir-generator/+/41653/ #Patch1: %{name}_build-with-glib2.patch # e.g. el6 has ppc64 arch without gcc-go, so EA tag is required # If go_compiler is not set to 1, there is no virtual provide. Use golang instead. BuildRequires: compiler(go-compiler) BuildRequires: pkgconfig(gobject-introspection-1.0) BuildRequires: pkgconfig(gudev-1.0) Provides: golang(gir/gobject-2.0) Provides: golang(gir/gio-2.0) Provides: golang(gir/glib-2.0) Provides: golang(gir/gudev-1.0) Provides: pkgconfig(pkg.deepin.io/gir/gio-2.0) Provides: deepin-gir-generator %description Generate static golang bindings for GObject %prep %setup -q -n %{name}-%{version} #GIO_VER=$(v=$(rpm -q --qf %{RPMTAG_VERSION} gobject-introspection); echo ${v//./}) #if [ $GIO_VER -ge 1521 ]; then # Our gobject-introspection is too new # https://cr.deepin.io/#/c/16880/ #%patch0 -p1 #%patch1 -p1 #fi %build export GOPATH="%{gopath}" %make_build %install %make_install %files %doc README.md %license LICENSE %{_bindir}/gir-generator %{gopath}/src/pkg.deepin.io/gir/ %changelog * Thu Mar 23 2021 uoser - 2.0.5-1 - Update to 2.0.5 go-gir-generator-master/src/000077500000000000000000000000001414263242200163065ustar00rootroot00000000000000go-gir-generator-master/src/gi/000077500000000000000000000000001414263242200167055ustar00rootroot00000000000000go-gir-generator-master/src/gi/README000066400000000000000000000003051414263242200175630ustar00rootroot00000000000000This is the binding for gobject-introspection C library. It provides low level access to typelib files, which can be used to generate full-blown bindings. And I want to code that in Go, right? ;-) go-gir-generator-master/src/gi/gi.go000066400000000000000000001357501414263242200176460ustar00rootroot00000000000000/** * Copyright (C) 2015 Deepin 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 of the License, or * (at your option) any later version. **/ package gi /* #include #include static inline void free_string(char *p) { free(p); } static inline void free_gstring(gchar *p) { if (p) g_free(p); } static inline char *gpointer_to_charp(gpointer p) { return p; } static inline gchar **next_gcharptr(gchar **s) { return s+1; } #cgo pkg-config: gobject-introspection-1.0 */ import "C" import ( "errors" "strings" "runtime" "unsafe" "fmt" ) // utils // Convert GSList containing strings to []string func _GStringGSListToGoStringSlice(list *C.GSList) []string { var slice []string for list != nil { str := C.GoString(C.gpointer_to_charp(list.data)) slice = append(slice, str) list = list.next } return slice } // Convert gchar** null-terminated glib string array to []string, frees "arr" func _GStringArrayToGoStringSlice(arr **C.gchar) []string { var slice []string if arr == nil { return slice } iter := arr for *iter != nil { slice = append(slice, _GStringToGoString(*iter)) iter = C.next_gcharptr(iter) } C.g_strfreev(arr) return slice } // Go string to glib C string, "" == NULL func _GoStringToGString(s string) *C.gchar { if s == "" { return nil } return (*C.gchar)(unsafe.Pointer(C.CString(s))) } // glib C string to Go string, NULL == "" func _GStringToGoString(s *C.gchar) string { if s == nil { return "" } return C.GoString((*C.char)(unsafe.Pointer(s))) } // C string to Go string, NULL == "" func _CStringToGoString(s *C.char) string { if s == nil { return "" } return C.GoString(s) } // GError to os.Error, frees "err" func _GErrorToOSError(err *C.GError) (goerr error) { goerr = errors.New(_GStringToGoString(err.message)) C.g_error_free(err) return } // Check for type func _ExpectBaseInfoType(bil BaseInfoLike, types ...InfoType) { bi := bil.inheritedFromBaseInfo() for _, t := range types { if bi.Type() == t { return } } // error from here typeStrings := make([]string, len(types)) for i, t := range types { typeStrings[i] = t.String() } panic(fmt.Sprintf("Type mismatch, expected: %s, got: %s", strings.Join(typeStrings, " or "), bi.Type())) } // Finalizer for BaseInfo structure, does the unref func _BaseInfoFinalizer(bi *BaseInfo) { bi.Unref() } // Helper for initializing finalizer on BaseInfo func _SetBaseInfoFinalizer(bi *BaseInfo) *BaseInfo { runtime.SetFinalizer(bi, _BaseInfoFinalizer) return bi } //------------------------------------------------------------------------------ // .types //------------------------------------------------------------------------------ type BaseInfoLike interface { inheritedFromBaseInfo() *BaseInfo } func ToBaseInfo(bil BaseInfoLike) *BaseInfo { return bil.inheritedFromBaseInfo() } func ToArgInfo(bil BaseInfoLike) *ArgInfo { _ExpectBaseInfoType(bil, INFO_TYPE_ARG) return (*ArgInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToConstantInfo(bil BaseInfoLike) *ConstantInfo { _ExpectBaseInfoType(bil, INFO_TYPE_CONSTANT) return (*ConstantInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToFieldInfo(bil BaseInfoLike) *FieldInfo { _ExpectBaseInfoType(bil, INFO_TYPE_FIELD) return (*FieldInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToPropertyInfo(bil BaseInfoLike) *PropertyInfo { _ExpectBaseInfoType(bil, INFO_TYPE_PROPERTY) return (*PropertyInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToTypeInfo(bil BaseInfoLike) *TypeInfo { _ExpectBaseInfoType(bil, INFO_TYPE_TYPE) return (*TypeInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToCallableInfo(bil BaseInfoLike) *CallableInfo { _ExpectBaseInfoType(bil, INFO_TYPE_FUNCTION, INFO_TYPE_CALLBACK, INFO_TYPE_SIGNAL, INFO_TYPE_VFUNC) return (*CallableInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToFunctionInfo(bil BaseInfoLike) *FunctionInfo { _ExpectBaseInfoType(bil, INFO_TYPE_FUNCTION) return (*FunctionInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToSignalInfo(bil BaseInfoLike) *SignalInfo { _ExpectBaseInfoType(bil, INFO_TYPE_SIGNAL) return (*SignalInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToVFuncInfo(bil BaseInfoLike) *VFuncInfo { _ExpectBaseInfoType(bil, INFO_TYPE_VFUNC) return (*VFuncInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToRegisteredType(bil BaseInfoLike) *RegisteredType { _ExpectBaseInfoType(bil, INFO_TYPE_BOXED, INFO_TYPE_ENUM, INFO_TYPE_FLAGS, INFO_TYPE_INTERFACE, INFO_TYPE_OBJECT, INFO_TYPE_STRUCT, INFO_TYPE_UNION) return (*RegisteredType)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToEnumInfo(bil BaseInfoLike) *EnumInfo { _ExpectBaseInfoType(bil, INFO_TYPE_ENUM, INFO_TYPE_FLAGS) return (*EnumInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToInterfaceInfo(bil BaseInfoLike) *InterfaceInfo { _ExpectBaseInfoType(bil, INFO_TYPE_INTERFACE) return (*InterfaceInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToObjectInfo(bil BaseInfoLike) *ObjectInfo { _ExpectBaseInfoType(bil, INFO_TYPE_OBJECT) return (*ObjectInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToStructInfo(bil BaseInfoLike) *StructInfo { _ExpectBaseInfoType(bil, INFO_TYPE_STRUCT) return (*StructInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } func ToUnionInfo(bil BaseInfoLike) *UnionInfo { _ExpectBaseInfoType(bil, INFO_TYPE_UNION) return (*UnionInfo)(unsafe.Pointer(bil.inheritedFromBaseInfo())) } //------------------------------------------------------------------------------ // InfoType //------------------------------------------------------------------------------ type InfoType int const ( INFO_TYPE_INVALID InfoType = C.GI_INFO_TYPE_INVALID INFO_TYPE_FUNCTION InfoType = C.GI_INFO_TYPE_FUNCTION INFO_TYPE_CALLBACK InfoType = C.GI_INFO_TYPE_CALLBACK INFO_TYPE_STRUCT InfoType = C.GI_INFO_TYPE_STRUCT INFO_TYPE_BOXED InfoType = C.GI_INFO_TYPE_BOXED INFO_TYPE_ENUM InfoType = C.GI_INFO_TYPE_ENUM INFO_TYPE_FLAGS InfoType = C.GI_INFO_TYPE_FLAGS INFO_TYPE_OBJECT InfoType = C.GI_INFO_TYPE_OBJECT INFO_TYPE_INTERFACE InfoType = C.GI_INFO_TYPE_INTERFACE INFO_TYPE_CONSTANT InfoType = C.GI_INFO_TYPE_CONSTANT INFO_TYPE_INVALID_0 InfoType = C.GI_INFO_TYPE_INVALID_0 INFO_TYPE_UNION InfoType = C.GI_INFO_TYPE_UNION INFO_TYPE_VALUE InfoType = C.GI_INFO_TYPE_VALUE INFO_TYPE_SIGNAL InfoType = C.GI_INFO_TYPE_SIGNAL INFO_TYPE_VFUNC InfoType = C.GI_INFO_TYPE_VFUNC INFO_TYPE_PROPERTY InfoType = C.GI_INFO_TYPE_PROPERTY INFO_TYPE_FIELD InfoType = C.GI_INFO_TYPE_FIELD INFO_TYPE_ARG InfoType = C.GI_INFO_TYPE_ARG INFO_TYPE_TYPE InfoType = C.GI_INFO_TYPE_TYPE INFO_TYPE_UNRESOLVED InfoType = C.GI_INFO_TYPE_UNRESOLVED ) // g_info_type_to_string func (it InfoType) String() string { return _GStringToGoString(C.g_info_type_to_string(C.GIInfoType(it))) } //------------------------------------------------------------------------------ // Repository //------------------------------------------------------------------------------ type Repository struct { c *C.GIRepository } type RepositoryLoadFlags int const ( REPOSITORY_LOAD_FLAG_LAZY RepositoryLoadFlags = C.G_IREPOSITORY_LOAD_FLAG_LAZY ) // g_irepository_get_default func DefaultRepository() *Repository { ret := C.g_irepository_get_default() if ret == nil { return nil } return &Repository{ret} } // g_irepository_prepend_search_path func PreprendRepositorySearchPath(path string) { cpath := C.CString(path) C.g_irepository_prepend_search_path(cpath) C.free_string(cpath) } // g_irepository_get_search_path func RepositorySearchPath() []string { return _GStringGSListToGoStringSlice(C.g_irepository_get_search_path()) } //const char * g_irepository_load_typelib (GIRepository *repository, // GITypelib *typelib, // GIRepositoryLoadFlags flags, // GError **error); // g_irepository_is_registered func (r *Repository) IsRegistered(namespace, version string) bool { gnamespace := _GoStringToGString(namespace) gversion := _GoStringToGString(version) ret := C.g_irepository_is_registered(r.c, gnamespace, gversion) C.free_gstring(gversion) C.free_gstring(gnamespace) return ret != 0 } // g_irepository_find_by_name func (r *Repository) FindByName(namespace, name string) *BaseInfo { gnamespace := _GoStringToGString(namespace) gname := _GoStringToGString(name) ret := C.g_irepository_find_by_name(r.c, gnamespace, gname) C.free_gstring(gname) C.free_gstring(gnamespace) return _SetBaseInfoFinalizer(&BaseInfo{ret}) } // g_irepository_require func (r *Repository) Require(namespace, version string, flags RepositoryLoadFlags) (*Typelib, error) { var err *C.GError gnamespace := _GoStringToGString(namespace) gversion := _GoStringToGString(version) tl := C.g_irepository_require(r.c, gnamespace, gversion, C.GIRepositoryLoadFlags(flags), &err) C.free_gstring(gversion) C.free_gstring(gnamespace) if err != nil { return nil, _GErrorToOSError(err) } var tlwrap *Typelib if tl != nil { tlwrap = &Typelib{tl} } return tlwrap, nil } //GITypelib * g_irepository_require_private (GIRepository *repository, // const gchar *typelib_dir, // const gchar *namespace_, // const gchar *version, // GIRepositoryLoadFlags flags, // GError **error); // g_irepository_get_dependencies func (r *Repository) Dependencies(namespace string) []string { gnamespace := _GoStringToGString(namespace) arr := C.g_irepository_get_dependencies(r.c, gnamespace) C.free_gstring(gnamespace) return _GStringArrayToGoStringSlice(arr) } // g_irepository_get_loaded_namespaces func (r *Repository) LoadedNamespaces() []string { arr := C.g_irepository_get_loaded_namespaces(r.c) return _GStringArrayToGoStringSlice(arr) } //GIBaseInfo * g_irepository_find_by_gtype (GIRepository *repository, // GType gtype); // g_irepository_get_n_infos func (r *Repository) NumInfo(namespace string) int { gnamespace := _GoStringToGString(namespace) num := C.g_irepository_get_n_infos(r.c, gnamespace) C.free_gstring(gnamespace) return int(num) } // g_irepository_get_info func (r *Repository) Info(namespace string, index int) *BaseInfo { gnamespace := _GoStringToGString(namespace) info := C.g_irepository_get_info(r.c, gnamespace, C.gint(index)) C.free_gstring(gnamespace) return _SetBaseInfoFinalizer(&BaseInfo{info}) } // g_irepository_get_typelib_path func (r *Repository) TypelibPath(namespace string) string { gnamespace := _GoStringToGString(namespace) path := C.g_irepository_get_typelib_path(r.c, gnamespace) C.free_gstring(gnamespace) return _GStringToGoString(path) } // g_irepository_get_shared_library func (r *Repository) SharedLibrary(namespace string) string { gnamespace := _GoStringToGString(namespace) shlib := C.g_irepository_get_shared_library(r.c, gnamespace) C.free_gstring(gnamespace) return _GStringToGoString(shlib) } // g_irepository_get_version func (r *Repository) Version(namespace string) string { gnamespace := _GoStringToGString(namespace) ver := C.g_irepository_get_version(r.c, gnamespace) C.free_gstring(gnamespace) return _GStringToGoString(ver) } //GOptionGroup * g_irepository_get_option_group (void); // g_irepository_get_c_prefix func (r *Repository) CPrefix(namespace string) string { gnamespace := _GoStringToGString(namespace) prefix := C.g_irepository_get_c_prefix(r.c, gnamespace) C.free_gstring(gnamespace) return _GStringToGoString(prefix) } //gboolean g_irepository_dump (const char *arg, // GError **error); //GList * g_irepository_enumerate_versions (GIRepository *repository, // const gchar *namespace_); //------------------------------------------------------------------------------ // Typelib //------------------------------------------------------------------------------ type Typelib struct { c *C.GITypelib } //GITypelib * g_typelib_new_from_memory (guint8 *memory, // gsize len, // GError **error); //GITypelib * g_typelib_new_from_const_memory (const guint8 *memory, // gsize len, // GError **error); //GITypelib * g_typelib_new_from_mapped_file (GMappedFile *mfile, // GError **error); //void g_typelib_free (GITypelib *typelib); //gboolean g_typelib_symbol (GITypelib *typelib, // const gchar *symbol_name, // gpointer *symbol); //const gchar * g_typelib_get_namespace (GITypelib *typelib); //------------------------------------------------------------------------------ // BaseInfo //------------------------------------------------------------------------------ type BaseInfo struct { c *C.GIBaseInfo } func (bi *BaseInfo) inheritedFromBaseInfo() *BaseInfo { return bi } // g_base_info_ref func (bi *BaseInfo) Ref() *BaseInfo { C.g_base_info_ref(bi.c) return bi } // g_base_info_unref func (bi *BaseInfo) Unref() { C.g_base_info_unref(bi.c) } // g_base_info_get_type func (bi *BaseInfo) Type() InfoType { return InfoType(C.g_base_info_get_type(bi.c)) } // g_base_info_get_name func (bi *BaseInfo) Name() string { return _GStringToGoString(C.g_base_info_get_name(bi.c)) } // g_base_info_get_namespace func (bi *BaseInfo) Namespace() string { return _GStringToGoString(C.g_base_info_get_namespace(bi.c)) } // g_base_info_is_deprecated func (bi *BaseInfo) IsDeprecated() bool { return C.g_base_info_is_deprecated(bi.c) != 0 } // g_base_info_get_attribute func (bi *BaseInfo) Attribute(name string) string { gname := _GoStringToGString(name) ret := _GStringToGoString(C.g_base_info_get_attribute(bi.c, gname)) C.free_gstring(gname) return ret } // g_base_info_iterate_attributes func (bi *BaseInfo) IterateAttributes(cb func(name, value string)) { var iter C.GIAttributeIter var cname, cvalue *C.char for C.g_base_info_iterate_attributes(bi.c, &iter, &cname, &cvalue) != 0 { name, value := C.GoString(cname), C.GoString(cvalue) cb(name, value) } } // g_base_info_get_container func (bi *BaseInfo) Container() *BaseInfo { c := C.g_base_info_get_container(bi.c) if c == nil { return nil } return &BaseInfo{c} } // g_base_info_get_typelib func (bi *BaseInfo) Typelib() *Typelib { return &Typelib{C.g_base_info_get_typelib(bi.c)} } //gboolean g_base_info_equal (GIBaseInfo *info1, // GIBaseInfo *info2); //------------------------------------------------------------------------------ // ArgInfo //------------------------------------------------------------------------------ type ArgInfo struct { BaseInfo } type Direction int type ScopeType int type Transfer int const ( DIRECTION_IN Direction = C.GI_DIRECTION_IN DIRECTION_OUT Direction = C.GI_DIRECTION_OUT DIRECTION_INOUT Direction = C.GI_DIRECTION_INOUT ) const ( SCOPE_TYPE_INVALID ScopeType = C.GI_SCOPE_TYPE_INVALID SCOPE_TYPE_CALL ScopeType = C.GI_SCOPE_TYPE_CALL SCOPE_TYPE_ASYNC ScopeType = C.GI_SCOPE_TYPE_ASYNC SCOPE_TYPE_NOTIFIED ScopeType = C.GI_SCOPE_TYPE_NOTIFIED ) const ( TRANSFER_NOTHING Transfer = C.GI_TRANSFER_NOTHING TRANSFER_CONTAINER Transfer = C.GI_TRANSFER_CONTAINER TRANSFER_EVERYTHING Transfer = C.GI_TRANSFER_EVERYTHING ) // g_arg_info_get_direction func (ai *ArgInfo) Direction() Direction { return Direction(C.g_arg_info_get_direction((*C.GIArgInfo)(ai.c))) } // g_arg_info_is_caller_allocates func (ai *ArgInfo) IsCallerAllocates() bool { return C.g_arg_info_is_caller_allocates((*C.GIArgInfo)(ai.c)) != 0 } // g_arg_info_is_return_value func (ai *ArgInfo) IsReturnValue() bool { return C.g_arg_info_is_return_value((*C.GIArgInfo)(ai.c)) != 0 } // g_arg_info_is_optional func (ai *ArgInfo) IsOptional() bool { return C.g_arg_info_is_optional((*C.GIArgInfo)(ai.c)) != 0 } // g_arg_info_may_be_null func (ai *ArgInfo) MayBeNil() bool { return C.g_arg_info_may_be_null((*C.GIArgInfo)(ai.c)) != 0 } // g_arg_info_is_skip func (ai *ArgInfo) IsSkip() bool { return C.g_arg_info_is_skip((*C.GIArgInfo)(ai.c)) != 0 } // g_arg_info_get_ownership_transfer func (ai *ArgInfo) OwnershipTransfer() Transfer { return Transfer(C.g_arg_info_get_ownership_transfer((*C.GIArgInfo)(ai.c))) } // g_arg_info_get_scope func (ai *ArgInfo) Scope() ScopeType { return ScopeType(C.g_arg_info_get_scope((*C.GIArgInfo)(ai.c))) } // g_arg_info_get_closure func (ai *ArgInfo) Closure() int { return int(C.g_arg_info_get_closure((*C.GIArgInfo)(ai.c))) } // g_arg_info_get_destroy func (ai *ArgInfo) Destroy() int { return int(C.g_arg_info_get_destroy((*C.GIArgInfo)(ai.c))) } // g_arg_info_get_type func (ai *ArgInfo) Type() *TypeInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_arg_info_get_type((*C.GIArgInfo)(ai.c)))} return (*TypeInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } //void g_arg_info_load_type (GIArgInfo *info, // GITypeInfo *type) //------------------------------------------------------------------------------ // ConstantInfo //------------------------------------------------------------------------------ type ConstantInfo struct { BaseInfo } // g_constant_info_get_type func (ci *ConstantInfo) Type() *TypeInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_constant_info_get_type((*C.GIConstantInfo)(ci.c)))} return (*TypeInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_constant_info_get_value func (ci *ConstantInfo) Value() interface{} { var arg C.GIArgument C.g_constant_info_get_value((*C.GIConstantInfo)(ci.c), &arg) ti := ci.Type() switch ti.Tag() { case TYPE_TAG_BOOLEAN: return *(*C.gboolean)(unsafe.Pointer(&arg)) != 0 case TYPE_TAG_INT8: return *(*int8)(unsafe.Pointer(&arg)) case TYPE_TAG_UINT8: return *(*uint8)(unsafe.Pointer(&arg)) case TYPE_TAG_INT16: return *(*int16)(unsafe.Pointer(&arg)) case TYPE_TAG_UINT16: return *(*uint16)(unsafe.Pointer(&arg)) case TYPE_TAG_INT32: return *(*int32)(unsafe.Pointer(&arg)) case TYPE_TAG_UINT32: return *(*uint32)(unsafe.Pointer(&arg)) case TYPE_TAG_INT64: return *(*int64)(unsafe.Pointer(&arg)) case TYPE_TAG_UINT64: return *(*uint64)(unsafe.Pointer(&arg)) case TYPE_TAG_FLOAT: return *(*float32)(unsafe.Pointer(&arg)) case TYPE_TAG_DOUBLE: return *(*float64)(unsafe.Pointer(&arg)) case TYPE_TAG_UTF8, TYPE_TAG_FILENAME: return C.GoString(*(**C.char)(unsafe.Pointer(&arg))) } panic("unsupported constant value") return nil } //gint g_constant_info_get_value (GIConstantInfo *info, // GIArgument *value); //------------------------------------------------------------------------------ // FieldInfo //------------------------------------------------------------------------------ type FieldInfo struct { BaseInfo } type FieldInfoFlags int const ( FIELD_IS_READABLE FieldInfoFlags = C.GI_FIELD_IS_READABLE FIELD_IS_WRITABLE FieldInfoFlags = C.GI_FIELD_IS_WRITABLE ) // g_field_info_get_flags func (fi *FieldInfo) Flags() FieldInfoFlags { return FieldInfoFlags(C.g_field_info_get_flags((*C.GIFieldInfo)(fi.c))) } // g_field_info_get_size func (fi *FieldInfo) Size() int { return int(C.g_field_info_get_size((*C.GIFieldInfo)(fi.c))) } // g_field_info_get_offset func (fi *FieldInfo) Offset() int { return int(C.g_field_info_get_offset((*C.GIFieldInfo)(fi.c))) } // g_field_info_get_type func (fi *FieldInfo) Type() *TypeInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_field_info_get_type((*C.GIFieldInfo)(fi.c)))} return (*TypeInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } //gboolean g_field_info_get_field (GIFieldInfo *field_info, // gpointer mem, // GIArgument *value); //gboolean g_field_info_set_field (GIFieldInfo *field_info, // gpointer mem, // const GIArgument *value); //------------------------------------------------------------------------------ // PropertyInfo //------------------------------------------------------------------------------ type PropertyInfo struct { BaseInfo } //GParamFlags g_property_info_get_flags (GIPropertyInfo *info); // g_property_info_get_type func (pi *PropertyInfo) Type() *TypeInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_property_info_get_type((*C.GIPropertyInfo)(pi.c)))} return (*TypeInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_property_info_get_ownership_transfer func (pi *PropertyInfo) OwnershipTransfer() Transfer { return Transfer(C.g_property_info_get_ownership_transfer((*C.GIPropertyInfo)(pi.c))) } //------------------------------------------------------------------------------ // TypeInfo //------------------------------------------------------------------------------ type TypeInfo struct { BaseInfo } type ArrayType int type TypeTag int const ( ARRAY_TYPE_C ArrayType = C.GI_ARRAY_TYPE_C ARRAY_TYPE_ARRAY ArrayType = C.GI_ARRAY_TYPE_ARRAY ARRAY_TYPE_PTR_ARRAY ArrayType = C.GI_ARRAY_TYPE_PTR_ARRAY ARRAY_TYPE_BYTE_ARRAY ArrayType = C.GI_ARRAY_TYPE_BYTE_ARRAY ) const ( TYPE_TAG_VOID TypeTag = C.GI_TYPE_TAG_VOID TYPE_TAG_BOOLEAN TypeTag = C.GI_TYPE_TAG_BOOLEAN TYPE_TAG_INT8 TypeTag = C.GI_TYPE_TAG_INT8 TYPE_TAG_UINT8 TypeTag = C.GI_TYPE_TAG_UINT8 TYPE_TAG_INT16 TypeTag = C.GI_TYPE_TAG_INT16 TYPE_TAG_UINT16 TypeTag = C.GI_TYPE_TAG_UINT16 TYPE_TAG_INT32 TypeTag = C.GI_TYPE_TAG_INT32 TYPE_TAG_UINT32 TypeTag = C.GI_TYPE_TAG_UINT32 TYPE_TAG_INT64 TypeTag = C.GI_TYPE_TAG_INT64 TYPE_TAG_UINT64 TypeTag = C.GI_TYPE_TAG_UINT64 TYPE_TAG_FLOAT TypeTag = C.GI_TYPE_TAG_FLOAT TYPE_TAG_DOUBLE TypeTag = C.GI_TYPE_TAG_DOUBLE TYPE_TAG_GTYPE TypeTag = C.GI_TYPE_TAG_GTYPE TYPE_TAG_UTF8 TypeTag = C.GI_TYPE_TAG_UTF8 TYPE_TAG_FILENAME TypeTag = C.GI_TYPE_TAG_FILENAME TYPE_TAG_ARRAY TypeTag = C.GI_TYPE_TAG_ARRAY TYPE_TAG_INTERFACE TypeTag = C.GI_TYPE_TAG_INTERFACE TYPE_TAG_GLIST TypeTag = C.GI_TYPE_TAG_GLIST TYPE_TAG_GSLIST TypeTag = C.GI_TYPE_TAG_GSLIST TYPE_TAG_GHASH TypeTag = C.GI_TYPE_TAG_GHASH TYPE_TAG_ERROR TypeTag = C.GI_TYPE_TAG_ERROR TYPE_TAG_UNICHAR TypeTag = C.GI_TYPE_TAG_UNICHAR ) // g_type_tag_to_string func (tt TypeTag) String() string { ret := C.g_type_tag_to_string(C.GITypeTag(tt)) return _GStringToGoString(ret) } // g_type_info_is_pointer func (ti *TypeInfo) IsPointer() bool { return C.g_type_info_is_pointer((*C.GITypeInfo)(ti.c)) != 0 } // g_type_info_get_tag func (ti *TypeInfo) Tag() TypeTag { return TypeTag(C.g_type_info_get_tag((*C.GITypeInfo)(ti.c))) } // g_type_info_get_param_type func (ti *TypeInfo) ParamType(n int) *TypeInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_type_info_get_param_type((*C.GITypeInfo)(ti.c), C.gint(n)))} return (*TypeInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_type_info_get_interface func (ti *TypeInfo) Interface() *BaseInfo { cptr := C.g_type_info_get_interface((*C.GITypeInfo)(ti.c)) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return _SetBaseInfoFinalizer(ptr) } // g_type_info_get_array_length func (ti *TypeInfo) ArrayLength() int { return int(C.g_type_info_get_array_length((*C.GITypeInfo)(ti.c))) } // g_type_info_get_array_fixed_size func (ti *TypeInfo) ArrayFixedSize() int { return int(C.g_type_info_get_array_fixed_size((*C.GITypeInfo)(ti.c))) } // g_type_info_is_zero_terminated func (ti *TypeInfo) IsZeroTerminated() bool { return C.g_type_info_is_zero_terminated((*C.GITypeInfo)(ti.c)) != 0 } // g_type_info_get_array_type func (ti *TypeInfo) ArrayType() ArrayType { return ArrayType(C.g_type_info_get_array_type((*C.GITypeInfo)(ti.c))) } //------------------------------------------------------------------------------ // CallableInfo //------------------------------------------------------------------------------ type CallableInfo struct { BaseInfo } // g_callable_info_get_return_type func (ci *CallableInfo) ReturnType() *TypeInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_callable_info_get_return_type((*C.GICallableInfo)(ci.c)))} return (*TypeInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_callable_info_get_caller_owns func (ci *CallableInfo) CallerOwns() Transfer { return Transfer(C.g_callable_info_get_caller_owns((*C.GICallableInfo)(ci.c))) } // g_callable_info_may_return_null func (ci *CallableInfo) MayReturnNil() bool { return C.g_callable_info_may_return_null((*C.GICallableInfo)(ci.c)) != 0 } // g_callable_info_get_return_attribute func (ci *CallableInfo) ReturnAttribute(name string) string { gname := _GoStringToGString(name) ret := C.g_callable_info_get_return_attribute((*C.GICallableInfo)(ci.c), gname) C.free_gstring(gname) return _GStringToGoString(ret) } // g_callable_info_iterate_return_attributes func (ci *CallableInfo) IterateReturnAttributes(cb func(name, value string)) { var iter C.GIAttributeIter var cname, cvalue *C.char for C.g_callable_info_iterate_return_attributes((*C.GICallableInfo)(ci.c), &iter, &cname, &cvalue) != 0 { name, value := C.GoString(cname), C.GoString(cvalue) cb(name, value) } } // g_callable_info_get_n_args func (ci *CallableInfo) NumArg() int { return int(C.g_callable_info_get_n_args((*C.GICallableInfo)(ci.c))) } // g_callable_info_get_arg func (ci *CallableInfo) Arg(n int) *ArgInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_callable_info_get_arg((*C.GICallableInfo)(ci.c), C.gint(n)))} return (*ArgInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } //void g_callable_info_load_arg (GICallableInfo *info, // gint n, // GIArgInfo *arg); //void g_callable_info_load_return_type (GICallableInfo *info, // GITypeInfo *type); //------------------------------------------------------------------------------ // FunctionInfo //------------------------------------------------------------------------------ type FunctionInfo struct { CallableInfo } type FunctionInfoFlags int const ( FUNCTION_IS_METHOD FunctionInfoFlags = C.GI_FUNCTION_IS_METHOD FUNCTION_IS_CONSTRUCTOR FunctionInfoFlags = C.GI_FUNCTION_IS_CONSTRUCTOR FUNCTION_IS_GETTER FunctionInfoFlags = C.GI_FUNCTION_IS_GETTER FUNCTION_IS_SETTER FunctionInfoFlags = C.GI_FUNCTION_IS_SETTER FUNCTION_WRAPS_VFUNC FunctionInfoFlags = C.GI_FUNCTION_WRAPS_VFUNC FUNCTION_THROWS FunctionInfoFlags = C.GI_FUNCTION_THROWS ) // g_function_info_get_symbol func (fi *FunctionInfo) Symbol() string { ret := C.g_function_info_get_symbol((*C.GIFunctionInfo)(fi.c)) return _GStringToGoString(ret) } // g_function_info_get_flags func (fi *FunctionInfo) Flags() FunctionInfoFlags { return FunctionInfoFlags(C.g_function_info_get_flags((*C.GIFunctionInfo)(fi.c))) } // g_function_info_get_property func (fi *FunctionInfo) Property() *PropertyInfo { cptr := (*C.GIBaseInfo)(C.g_function_info_get_property((*C.GIFunctionInfo)(fi.c))) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*PropertyInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_function_info_get_vfunc func (fi *FunctionInfo) VFunc() *VFuncInfo { cptr := (*C.GIBaseInfo)(C.g_function_info_get_vfunc((*C.GIFunctionInfo)(fi.c))) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*VFuncInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } //gboolean g_function_info_invoke (GIFunctionInfo *info, // const GIArgument *in_args, // int n_in_args, // const GIArgument *out_args, // int n_out_args, // GIArgument *return_value, // GError **error); //------------------------------------------------------------------------------ // SignalInfo //------------------------------------------------------------------------------ type SignalInfo struct { CallableInfo } //GSignalFlags g_signal_info_get_flags (GISignalInfo *info); // g_signal_info_get_class_closure func (si *SignalInfo) ClassClosure() *VFuncInfo { cptr := (*C.GIBaseInfo)(C.g_signal_info_get_class_closure((*C.GISignalInfo)(si.c))) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*VFuncInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_signal_info_true_stops_emit func (si *SignalInfo) TrueStopsEmit() bool { return C.g_signal_info_true_stops_emit((*C.GISignalInfo)(si.c)) != 0 } //------------------------------------------------------------------------------ // VFuncInfo //------------------------------------------------------------------------------ type VFuncInfo struct { CallableInfo } type VFuncInfoFlags int const ( VFUNC_MUST_CHAIN_UP VFuncInfoFlags = C.GI_VFUNC_MUST_CHAIN_UP VFUNC_MUST_OVERRIDE VFuncInfoFlags = C.GI_VFUNC_MUST_OVERRIDE VFUNC_MUST_NOT_OVERRIDE VFuncInfoFlags = C.GI_VFUNC_MUST_NOT_OVERRIDE ) // g_vfunc_info_get_flags func (vfi *VFuncInfo) Flags() VFuncInfoFlags { return VFuncInfoFlags(C.g_vfunc_info_get_flags((*C.GIVFuncInfo)(vfi.c))) } // g_vfunc_info_get_offset func (vfi *VFuncInfo) Offset() int { return int(C.g_vfunc_info_get_offset((*C.GIVFuncInfo)(vfi.c))) } // g_vfunc_info_get_signal func (vfi *VFuncInfo) Signal() *SignalInfo { cptr := (*C.GIBaseInfo)(C.g_vfunc_info_get_signal((*C.GIVFuncInfo)(vfi.c))) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*SignalInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_vfunc_info_get_invoker func (vfi *VFuncInfo) Invoker() *FunctionInfo { cptr := (*C.GIBaseInfo)(C.g_vfunc_info_get_invoker((*C.GIVFuncInfo)(vfi.c))) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*FunctionInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } //------------------------------------------------------------------------------ // RegisteredType //------------------------------------------------------------------------------ type RegisteredType struct { BaseInfo } // g_registered_type_info_get_type_name func (rt *RegisteredType) TypeName() string { ret := C.g_registered_type_info_get_type_name((*C.GIRegisteredTypeInfo)(rt.c)) return _GStringToGoString(ret) } // g_registered_type_info_get_type_init func (rt *RegisteredType) TypeInit() string { ret := C.g_registered_type_info_get_type_init((*C.GIRegisteredTypeInfo)(rt.c)) return _GStringToGoString(ret) } //GType g_registered_type_info_get_g_type (GIRegisteredTypeInfo *info); //------------------------------------------------------------------------------ // EnumInfo //------------------------------------------------------------------------------ type EnumInfo struct { RegisteredType } type ValueInfo struct { BaseInfo } // g_enum_info_get_n_values func (ei *EnumInfo) NumValue() int { return int(C.g_enum_info_get_n_values((*C.GIEnumInfo)(ei.c))) } // g_enum_info_get_value func (ei *EnumInfo) Value(n int) *ValueInfo { cptr := (*C.GIBaseInfo)(C.g_enum_info_get_value((*C.GIEnumInfo)(ei.c), C.gint(n))) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*ValueInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_enum_info_get_n_methods func (ei *EnumInfo) NumMethod() int { return int(C.g_enum_info_get_n_methods((*C.GIEnumInfo)(ei.c))) } // g_enum_info_get_method func (ii *EnumInfo) Method(n int) *FunctionInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_enum_info_get_method((*C.GIEnumInfo)(ii.c), C.gint(n)))} return (*FunctionInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_enum_info_get_storage_type func (ei *EnumInfo) StorageType() TypeTag { return TypeTag(C.g_enum_info_get_storage_type((*C.GIEnumInfo)(ei.c))) } // g_value_info_get_value func (vi *ValueInfo) Value() int64 { return int64(C.g_value_info_get_value((*C.GIValueInfo)(vi.c))) } //------------------------------------------------------------------------------ // InterfaceInfo //------------------------------------------------------------------------------ type InterfaceInfo struct { RegisteredType } // g_interface_info_get_n_prerequisites func (ii *InterfaceInfo) NumPrerequisite() int { return int(C.g_interface_info_get_n_prerequisites((*C.GIInterfaceInfo)(ii.c))) } // g_interface_info_get_prerequisite func (ii *InterfaceInfo) Prerequisite(n int) *BaseInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_interface_info_get_prerequisite((*C.GIInterfaceInfo)(ii.c), C.gint(n)))} return (*BaseInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_interface_info_get_n_properties func (ii *InterfaceInfo) NumProperty() int { return int(C.g_interface_info_get_n_properties((*C.GIInterfaceInfo)(ii.c))) } // g_interface_info_get_property func (ii *InterfaceInfo) Property(n int) *PropertyInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_interface_info_get_property((*C.GIInterfaceInfo)(ii.c), C.gint(n)))} return (*PropertyInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_interface_info_get_n_methods func (ii *InterfaceInfo) NumMethod() int { return int(C.g_interface_info_get_n_methods((*C.GIInterfaceInfo)(ii.c))) } // g_interface_info_get_method func (ii *InterfaceInfo) Method(n int) *FunctionInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_interface_info_get_method((*C.GIInterfaceInfo)(ii.c), C.gint(n)))} return (*FunctionInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_interface_info_find_method func (ii *InterfaceInfo) FindMethod(name string) *FunctionInfo { gname := _GoStringToGString(name) cptr := (*C.GIBaseInfo)(C.g_interface_info_find_method((*C.GIInterfaceInfo)(ii.c), gname)) C.free_gstring(gname) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*FunctionInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_interface_info_get_n_signals func (ii *InterfaceInfo) NumSignal() int { return int(C.g_interface_info_get_n_signals((*C.GIInterfaceInfo)(ii.c))) } // g_interface_info_get_signal func (ii *InterfaceInfo) Signal(n int) *SignalInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_interface_info_get_signal((*C.GIInterfaceInfo)(ii.c), C.gint(n)))} return (*SignalInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_interface_info_get_n_vfuncs func (ii *InterfaceInfo) NumVFunc() int { return int(C.g_interface_info_get_n_vfuncs((*C.GIInterfaceInfo)(ii.c))) } // g_interface_info_get_vfunc func (ii *InterfaceInfo) VFunc(n int) *VFuncInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_interface_info_get_vfunc((*C.GIInterfaceInfo)(ii.c), C.gint(n)))} return (*VFuncInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_interface_info_get_n_constants func (ii *InterfaceInfo) NumConstant() int { return int(C.g_interface_info_get_n_constants((*C.GIInterfaceInfo)(ii.c))) } // g_interface_info_get_constant func (ii *InterfaceInfo) Constant(n int) *ConstantInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_interface_info_get_constant((*C.GIInterfaceInfo)(ii.c), C.gint(n)))} return (*ConstantInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } //GIStructInfo * g_interface_info_get_iface_struct (GIInterfaceInfo *info); // g_interface_info_get_iface_struct func (ii *InterfaceInfo) InterfaceStruct() *StructInfo { cptr := (*C.GIBaseInfo)(C.g_interface_info_get_iface_struct((*C.GIInterfaceInfo)(ii.c))) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*StructInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_interface_info_find_vfunc func (ii *InterfaceInfo) FindVFunc(name string) *VFuncInfo { gname := _GoStringToGString(name) cptr := (*C.GIBaseInfo)(C.g_interface_info_find_vfunc((*C.GIInterfaceInfo)(ii.c), gname)) C.free_gstring(gname) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*VFuncInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } //------------------------------------------------------------------------------ // ObjectInfo //------------------------------------------------------------------------------ type ObjectInfo struct { RegisteredType } // g_object_info_get_type_name func (oi *ObjectInfo) TypeName() string { ret := C.g_object_info_get_type_name((*C.GIObjectInfo)(oi.c)) return _GStringToGoString(ret) } // g_object_info_get_type_init func (oi *ObjectInfo) TypeInit() string { ret := C.g_object_info_get_type_init((*C.GIObjectInfo)(oi.c)) return _GStringToGoString(ret) } // g_object_info_get_abstract func (oi *ObjectInfo) Abstract() bool { return C.g_object_info_get_abstract((*C.GIObjectInfo)(oi.c)) != 0 } // g_object_info_get_fundamental func (oi *ObjectInfo) Fundamental() bool { return C.g_object_info_get_fundamental((*C.GIObjectInfo)(oi.c)) != 0 } // g_object_info_get_parent func (oi *ObjectInfo) Parent() *ObjectInfo { cptr := (*C.GIBaseInfo)(C.g_object_info_get_parent((*C.GIObjectInfo)(oi.c))) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*ObjectInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_object_info_get_n_interfaces func (oi *ObjectInfo) NumInterface() int { return int(C.g_object_info_get_n_interfaces((*C.GIObjectInfo)(oi.c))) } // g_object_info_get_interface func (oi *ObjectInfo) Interface(n int) *InterfaceInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_object_info_get_interface((*C.GIObjectInfo)(oi.c), C.gint(n)))} return (*InterfaceInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_object_info_get_n_fields func (oi *ObjectInfo) NumField() int { return int(C.g_object_info_get_n_fields((*C.GIObjectInfo)(oi.c))) } // g_object_info_get_field func (oi *ObjectInfo) Field(n int) *FieldInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_object_info_get_field((*C.GIObjectInfo)(oi.c), C.gint(n)))} return (*FieldInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_object_info_get_n_properties func (oi *ObjectInfo) NumProperty() int { return int(C.g_object_info_get_n_properties((*C.GIObjectInfo)(oi.c))) } // g_object_info_get_field func (oi *ObjectInfo) Property(n int) *PropertyInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_object_info_get_property((*C.GIObjectInfo)(oi.c), C.gint(n)))} return (*PropertyInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_object_info_get_n_methods func (oi *ObjectInfo) NumMethod() int { return int(C.g_object_info_get_n_methods((*C.GIObjectInfo)(oi.c))) } // g_object_info_get_method func (oi *ObjectInfo) Method(n int) *FunctionInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_object_info_get_method((*C.GIObjectInfo)(oi.c), C.gint(n)))} return (*FunctionInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_object_info_find_method func (oi *ObjectInfo) FindMethod(name string) *FunctionInfo { gname := _GoStringToGString(name) cptr := (*C.GIBaseInfo)(C.g_object_info_find_method((*C.GIObjectInfo)(oi.c), gname)) C.free_gstring(gname) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*FunctionInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_object_info_get_n_signals func (oi *ObjectInfo) NumSignal() int { return int(C.g_object_info_get_n_signals((*C.GIObjectInfo)(oi.c))) } // g_object_info_get_signal func (oi *ObjectInfo) Signal(n int) *SignalInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_object_info_get_signal((*C.GIObjectInfo)(oi.c), C.gint(n)))} return (*SignalInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_object_info_get_n_vfuncs func (oi *ObjectInfo) NumVFunc() int { return int(C.g_object_info_get_n_vfuncs((*C.GIObjectInfo)(oi.c))) } // g_object_info_get_vfunc func (oi *ObjectInfo) VFunc(n int) *VFuncInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_object_info_get_vfunc((*C.GIObjectInfo)(oi.c), C.gint(n)))} return (*VFuncInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_object_info_get_n_constants func (oi *ObjectInfo) NumConstant() int { return int(C.g_object_info_get_n_constants((*C.GIObjectInfo)(oi.c))) } // g_object_info_get_constant func (oi *ObjectInfo) Constant(n int) *ConstantInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_object_info_get_constant((*C.GIObjectInfo)(oi.c), C.gint(n)))} return (*ConstantInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_object_info_get_class_struct func (oi *ObjectInfo) ClassStruct() *StructInfo { cptr := (*C.GIBaseInfo)(C.g_object_info_get_class_struct((*C.GIObjectInfo)(oi.c))) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*StructInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_object_info_find_vfunc func (oi *ObjectInfo) FindVFunc(name string) *VFuncInfo { gname := _GoStringToGString(name) cptr := (*C.GIBaseInfo)(C.g_object_info_find_vfunc((*C.GIObjectInfo)(oi.c), gname)) C.free_gstring(gname) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*VFuncInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_object_info_get_unref_function func (oi *ObjectInfo) UnrefFunction() string { ret := C.g_object_info_get_unref_function((*C.GIObjectInfo)(oi.c)) return _CStringToGoString(ret) } //GIObjectInfoUnrefFunction g_object_info_get_unref_function_pointer // (GIObjectInfo *info); // g_object_info_get_ref_function func (oi *ObjectInfo) RefFunction() string { ret := C.g_object_info_get_ref_function((*C.GIObjectInfo)(oi.c)) return _CStringToGoString(ret) } //GIObjectInfoRefFunction g_object_info_get_ref_function_pointer // (GIObjectInfo *info); // g_object_info_get_set_value_function func (oi *ObjectInfo) SetValueFunction() string { ret := C.g_object_info_get_set_value_function((*C.GIObjectInfo)(oi.c)) return _CStringToGoString(ret) } //GIObjectInfoSetValueFunction g_object_info_get_set_value_function_pointer // (GIObjectInfo *info); // g_object_info_get_get_value_function func (oi *ObjectInfo) GetValueFunction() string { ret := C.g_object_info_get_get_value_function((*C.GIObjectInfo)(oi.c)) return _CStringToGoString(ret) } //GIObjectInfoGetValueFunction g_object_info_get_get_value_function_pointer // (GIObjectInfo *info); //------------------------------------------------------------------------------ // StructInfo //------------------------------------------------------------------------------ type StructInfo struct { RegisteredType } // g_struct_info_get_n_fields func (si *StructInfo) NumField() int { return int(C.g_struct_info_get_n_fields((*C.GIStructInfo)(si.c))) } // g_struct_info_get_field func (si *StructInfo) Field(n int) *FieldInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_struct_info_get_field((*C.GIStructInfo)(si.c), C.gint(n)))} return (*FieldInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_struct_info_get_n_methods func (si *StructInfo) NumMethod() int { return int(C.g_struct_info_get_n_methods((*C.GIStructInfo)(si.c))) } // g_struct_info_get_method func (si *StructInfo) Method(n int) *FunctionInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_struct_info_get_method((*C.GIStructInfo)(si.c), C.gint(n)))} return (*FunctionInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_struct_info_find_method func (si *StructInfo) FindMethod(name string) *FunctionInfo { gname := _GoStringToGString(name) cptr := (*C.GIBaseInfo)(C.g_struct_info_find_method((*C.GIStructInfo)(si.c), gname)) C.free_gstring(gname) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*FunctionInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_struct_info_get_size func (si *StructInfo) Size() int { return int(C.g_struct_info_get_size((*C.GIStructInfo)(si.c))) } // g_struct_info_get_alignment func (si *StructInfo) Alignment() int { return int(C.g_struct_info_get_alignment((*C.GIStructInfo)(si.c))) } // g_struct_info_is_gtype_struct func (si *StructInfo) IsGTypeStruct() bool { return C.g_struct_info_is_gtype_struct((*C.GIStructInfo)(si.c)) != 0 } // g_struct_info_is_foreign func (si *StructInfo) IsForeign() bool { return C.g_struct_info_is_foreign((*C.GIStructInfo)(si.c)) != 0 } //------------------------------------------------------------------------------ // UnionInfo //------------------------------------------------------------------------------ type UnionInfo struct { RegisteredType } // g_union_info_get_n_fields func (ui *UnionInfo) NumField() int { return int(C.g_union_info_get_n_fields((*C.GIUnionInfo)(ui.c))) } // g_union_info_get_field func (ui *UnionInfo) Field(n int) FieldInfo { return FieldInfo{BaseInfo{ (*C.GIBaseInfo)(C.g_union_info_get_field((*C.GIUnionInfo)(ui.c), C.gint(n)))}} } // g_union_info_get_n_methods func (ui *UnionInfo) NumMethod() int { return int(C.g_union_info_get_n_methods((*C.GIUnionInfo)(ui.c))) } // g_union_info_get_method func (ui *UnionInfo) Method(n int) *FunctionInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_union_info_get_method((*C.GIUnionInfo)(ui.c), C.gint(n)))} return (*FunctionInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_union_info_is_discriminated func (ui *UnionInfo) IsDiscriminated() bool { return C.g_union_info_is_discriminated((*C.GIUnionInfo)(ui.c)) != 0 } // g_union_info_get_discriminator_offset func (ui *UnionInfo) DiscriminatorOffset() int { return int(C.g_union_info_get_discriminator_offset((*C.GIUnionInfo)(ui.c))) } // g_union_info_get_discriminator_type func (ui *UnionInfo) DiscriminatorType() *TypeInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_union_info_get_discriminator_type((*C.GIUnionInfo)(ui.c)))} return (*TypeInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_union_info_get_discriminator func (ui *UnionInfo) Discriminator(n int) *ConstantInfo { ptr := &BaseInfo{(*C.GIBaseInfo)(C.g_union_info_get_discriminator((*C.GIUnionInfo)(ui.c), C.gint(n)))} return (*ConstantInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_union_info_find_method func (ui *UnionInfo) FindMethod(name string) *FunctionInfo { gname := _GoStringToGString(name) cptr := (*C.GIBaseInfo)(C.g_union_info_find_method((*C.GIUnionInfo)(ui.c), gname)) C.free_gstring(gname) if cptr == nil { return nil } ptr := &BaseInfo{cptr} return (*FunctionInfo)(unsafe.Pointer(_SetBaseInfoFinalizer(ptr))) } // g_union_info_get_size func (ui *UnionInfo) Size() int { return int(C.g_union_info_get_size((*C.GIUnionInfo)(ui.c))) } // g_union_info_get_alignment func (ui *UnionInfo) Alignment() int { return int(C.g_union_info_get_alignment((*C.GIUnionInfo)(ui.c))) } go-gir-generator-master/src/gir-generator/000077500000000000000000000000001414263242200210535ustar00rootroot00000000000000go-gir-generator-master/src/gir-generator/binding_generator.go000066400000000000000000000660001414263242200250640ustar00rootroot00000000000000/** * Copyright (C) 2015 Deepin 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 of the License, or * (at your option) any later version. **/ package main import ( "bufio" "bytes" "fmt" "gi" "os" "strings" ) type binding_generator struct { file_go *os.File file_c *os.File file_h *os.File out_go *bufio.Writer out_c *bufio.Writer out_h *bufio.Writer // temporary buffer for 'go_bindings' go_bindings bytes.Buffer // map for C header generator to avoid duplicates declared_c_funcs map[string]bool } func new_binding_generator(out_base string) *binding_generator { var err error this := new(binding_generator) this.declared_c_funcs = make(map[string]bool) this.file_go, err = os.Create(out_base + ".go") panic_if_error(err) this.file_c, err = os.Create(out_base + ".gen.c") panic_if_error(err) this.file_h, err = os.Create(out_base + ".gen.h") panic_if_error(err) this.out_go = bufio.NewWriter(this.file_go) this.out_c = bufio.NewWriter(this.file_c) this.out_h = bufio.NewWriter(this.file_h) return this } func (this *binding_generator) release() { this.out_go.Flush() this.out_c.Flush() this.out_h.Flush() this.file_go.Close() this.file_c.Close() this.file_h.Close() } func (this *binding_generator) generate(go_template string) { // this will fill the 'go_bindings' buffer repo := gi.DefaultRepository() for i, n := 0, repo.NumInfo(config.namespace); i < n; i++ { this.process_base_info(repo.Info(config.namespace, i)) } t := must_template(go_template) t.Execute(this.out_go, map[string]interface{}{ "g_list_funcs": g_list_funcs, "g_object_ref_unref": g_object_ref_unref, "go_utils": go_utils(true), "go_utils_no_cb": go_utils(false), "go_bindings": this.go_bindings.String(), "g_error_free": g_error_free, "g_free": g_free, }) // write source/header preambles p := printer_to(this.out_h) p(c_header) // TODO: using config.pkg here is probably incorrect, we should use the // filename c_template.Execute(this.out_c, map[string]interface{}{ "namespace": config.namespace, "package": config.pkg, }) p = printer_to(this.out_c) p("\n\n") // this will write the rest of .c/.h files this.c_forward_declarations() } func (this *binding_generator) c_func_forward_declaration(fi *gi.FunctionInfo) { symbol := fi.Symbol() if _, declared := this.declared_c_funcs[symbol]; declared { return } this.declared_c_funcs[symbol] = true container := fi.Container() ph := printer_to(this.out_h) pc := printer_to(this.out_c) flags := fi.Flags() narg := fi.NumArg() if flags&gi.FUNCTION_THROWS != 0 { narg++ } ph("extern %s %s(", c_type(fi.ReturnType(), type_none), symbol) if flags&gi.FUNCTION_IS_METHOD != 0 { ph("%s", c_type_for_interface(container, type_pointer)) if narg > 0 { ph(", ") } } var closure_scope gi.ScopeType = gi.SCOPE_TYPE_INVALID var closure_userdata int = -1 var closure_destroy int = -1 var closure_callback int = -1 for i, n := 0, narg; i < n; i++ { if i != 0 { ph(", ") } if i == n-1 && flags&gi.FUNCTION_THROWS != 0 { ph("GError**") continue } arg := fi.Arg(i) t := arg.Type() if uarg := arg.Closure(); uarg != -1 { if t.Tag() == gi.TYPE_TAG_INTERFACE { if t.Interface().Type() == gi.INFO_TYPE_CALLBACK { if darg := arg.Destroy(); darg != -1 { closure_destroy = darg } closure_userdata = uarg closure_callback = i closure_scope = arg.Scope() } } } ph("%s", c_type(t, type_none)) switch arg.Direction() { case gi.DIRECTION_INOUT, gi.DIRECTION_OUT: ph("*") } } ph(");\n") if closure_scope == gi.SCOPE_TYPE_INVALID { return } // Also if this function is actually blacklisted, we don't want to // generate wrappers if config.is_object_blacklisted(gi.ToBaseInfo(fi)) { return } // Or maybe this is a method and method's owner is blacklisted if container != nil && config.is_object_blacklisted(container) { return } // in case if the function takes callback, generate appropriate wrappers // for Go (gc compiler mainly) var tmp bytes.Buffer p := printer_to(&tmp) p("%s _%s(", c_type(fi.ReturnType(), type_none), symbol) if flags&gi.FUNCTION_IS_METHOD != 0 { p("%s this", c_type_for_interface(container, type_pointer)) if narg > 0 { p(", ") } } for i, n := 0, narg; i < n; i++ { if i == closure_userdata || i == closure_destroy { // skip userdata and destroy func in the wrapper continue } if i != 0 { p(", ") } if i == closure_callback { // replace callback argument with Go function pointer // and optional unique id (if scope is not CALL) p("void* gofunc") continue } if i == n-1 && flags&gi.FUNCTION_THROWS != 0 { p("GError** arg%d", i) continue } arg := fi.Arg(i) p("%s", c_type(arg.Type(), type_none)) switch arg.Direction() { case gi.DIRECTION_INOUT, gi.DIRECTION_OUT: p("*") } p(" arg%d", i) } p(")") ph("extern %s;\n", tmp.String()) pc("%s {\n", tmp.String()) // body defcall := func(argprint func(i int, t *gi.TypeInfo)) { pc("\t\t") if ret := fi.ReturnType(); !(ret.Tag() == gi.TYPE_TAG_VOID && !ret.IsPointer()) { pc("return ") } pc("%s(", symbol) if flags&gi.FUNCTION_IS_METHOD != 0 { pc("this") if narg > 0 { pc(", ") } } for i, n := 0, narg; i < n; i++ { arg := fi.Arg(i) t := arg.Type() if i != 0 { pc(", ") } argprint(i, t) } pc(");\n") } pc("\tif (gofunc) {\n") defcall(func(i int, t *gi.TypeInfo) { switch i { case closure_userdata: pc("gofunc") case closure_destroy: pc("_c_callback_cleanup") case closure_callback: pc("_%s_c_wrapper", c_type(t, type_none)) if closure_scope == gi.SCOPE_TYPE_ASYNC { pc("_once") } default: pc("arg%d", i) } }) pc("\t} else {\n") defcall(func(i int, t *gi.TypeInfo) { switch i { case closure_userdata, closure_destroy, closure_callback: pc("0") default: pc("arg%d", i) } }) pc("\t}\n") pc("}\n") } // generating forward C declarations properly: // 10 - various typedefs // 20 - functions and methods // 30 - struct definitions func (this *binding_generator) c_forward_declaration10(bi *gi.BaseInfo) { p := printer_to(this.out_h) switch bi.Type() { case gi.INFO_TYPE_OBJECT: cctype := c_type_for_interface(bi, type_none) p("typedef struct _%s %s;\n", cctype, cctype) case gi.INFO_TYPE_FLAGS, gi.INFO_TYPE_ENUM: ei := gi.ToEnumInfo(bi) p("typedef %s %s;\n", c_type_for_tag(ei.StorageType(), type_none), c_type_for_interface(bi, type_none)) case gi.INFO_TYPE_STRUCT, gi.INFO_TYPE_INTERFACE, gi.INFO_TYPE_UNION: fullnm := strings.ToLower(bi.Namespace()) + "." + bi.Name() cctype := c_type_for_interface(bi, type_none) if config.is_disguised(fullnm) { p("typedef void *%s;\n", cctype) } else { p("typedef struct _%s %s;\n", cctype, cctype) } case gi.INFO_TYPE_CALLBACK: pc := printer_to(this.out_c) ctype := c_type_for_interface(bi, type_none) ci := gi.ToCallableInfo(bi) // type doesn't matter here, it's just a pointer after all p("typedef void* %s;\n", ctype) // and wrapper declarations for .c file only (cgo has problems // with that) pc("extern %s _%s_c_wrapper();\n", c_type(ci.ReturnType(), type_none), ctype) pc("extern %s _%s_c_wrapper_once();\n", c_type(ci.ReturnType(), type_none), ctype) } } func (this *binding_generator) c_forward_declaration20(bi *gi.BaseInfo) { p := printer_to(this.out_h) switch bi.Type() { case gi.INFO_TYPE_FUNCTION: fi := gi.ToFunctionInfo(bi) this.c_func_forward_declaration(fi) case gi.INFO_TYPE_OBJECT: oi := gi.ToObjectInfo(bi) for i, n := 0, oi.NumMethod(); i < n; i++ { meth := oi.Method(i) this.c_func_forward_declaration(meth) } p("extern GType %s();\n", oi.TypeInit()) case gi.INFO_TYPE_INTERFACE: ii := gi.ToInterfaceInfo(bi) for i, n := 0, ii.NumMethod(); i < n; i++ { meth := ii.Method(i) this.c_func_forward_declaration(meth) } p("extern GType %s();\n", ii.TypeInit()) case gi.INFO_TYPE_STRUCT: si := gi.ToStructInfo(bi) for i, n := 0, si.NumMethod(); i < n; i++ { meth := si.Method(i) this.c_func_forward_declaration(meth) } case gi.INFO_TYPE_UNION: ui := gi.ToUnionInfo(bi) for i, n := 0, ui.NumMethod(); i < n; i++ { meth := ui.Method(i) this.c_func_forward_declaration(meth) } } } func (this *binding_generator) c_forward_declaration30(bi *gi.BaseInfo) { p := printer_to(this.out_h) fullnm := strings.ToLower(bi.Namespace()) + "." + bi.Name() switch bi.Type() { case gi.INFO_TYPE_STRUCT: si := gi.ToStructInfo(bi) size := si.Size() if config.is_disguised(fullnm) { return } cctype := c_type_for_interface(bi, type_none) if size == 0 { p("struct _%s {};\n", cctype) } else { p("struct _%s { uint8_t _data[%d]; };\n", cctype, size) } case gi.INFO_TYPE_UNION: ui := gi.ToUnionInfo(bi) size := ui.Size() cctype := c_type_for_interface(bi, type_none) if size == 0 { p("struct _%s {};\n", cctype) } else { p("struct _%s { uint8_t _data[%d]; };\n", cctype, size) } } } func get_dependcies_declarations(namespace string) (ret []string) { repo := gi.DefaultRepository() deps := repo.Dependencies(namespace) for _, dep := range deps { depv := strings.Split(dep, "-") deps = append(deps, get_dependcies_declarations(depv[0])...) } tmp := list_to_map(deps) for k, _ := range tmp { ret = append(ret, k) } return } func (this *binding_generator) c_forward_declarations() { repo := gi.DefaultRepository() deps := get_dependcies_declarations(config.namespace) for _, dep := range deps { depv := strings.Split(dep, "-") _, err := repo.Require(depv[0], depv[1], 0) if err != nil { panic(err) } for i, n := 0, repo.NumInfo(depv[0]); i < n; i++ { this.c_forward_declaration10(repo.Info(depv[0], i)) this.c_forward_declaration30(repo.Info(depv[0], i)) } } for i, n := 0, repo.NumInfo(config.namespace); i < n; i++ { this.c_forward_declaration10(repo.Info(config.namespace, i)) } for i, n := 0, repo.NumInfo(config.namespace); i < n; i++ { this.c_forward_declaration20(repo.Info(config.namespace, i)) } for i, n := 0, repo.NumInfo(config.namespace); i < n; i++ { this.c_forward_declaration30(repo.Info(config.namespace, i)) } } func go_utils(cb bool) string { var out bytes.Buffer go_utils_template.Execute(&out, map[string]interface{}{ "gobjectns": config.gns, "namespace": config.namespace, "nocallbacks": !cb, }) return out.String() } //------------------------------------------------------------------------ //------------------------------------------------------------------------ func (this *binding_generator) process_object_info(oi *gi.ObjectInfo) { p := printer_to(&this.go_bindings) parent := "C unsafe.Pointer" parentlike := "" if p := oi.Parent(); p != nil { parent = "" if ns := p.Namespace(); ns != config.namespace { parent += strings.ToLower(ns) + "." } parent += p.Name() parentlike = parent + "Like" } // interface that this class and its subclasses implement cprefix := gi.DefaultRepository().CPrefix(config.namespace) name := oi.Name() cgotype := cgo_type_for_interface(gi.ToBaseInfo(oi), type_pointer) var interfaces bytes.Buffer pi := printer_to(&interfaces) for i, n := 0, oi.NumInterface(); i < n; i++ { ii := oi.Interface(i) name := ii.Name() ns := ii.Namespace() if i != 0 { pi("\n\t") } if ns != config.namespace { pi("%s.", strings.ToLower(ns)) } pi("%sImpl", name) } p("%s\n", execute_template(object_template, map[string]string{ "name": name, "cprefix": cprefix, "cgotype": cgotype, "parent": parent, "parentlike": parentlike, "typeinit": oi.TypeInit(), "gobjectns": config.gns, "interfaces": interfaces.String(), })) for i, n := 0, oi.NumMethod(); i < n; i++ { meth := oi.Method(i) if config.is_method_blacklisted(name, meth.Name()) { p("// blacklisted: %s.%s (method)\n", name, meth.Name()) continue } this.process_function_info(meth) } } func (this *binding_generator) process_struct_info(si *gi.StructInfo) { p := printer_to(&this.go_bindings) name := si.Name() size := si.Size() if si.IsGTypeStruct() { return } if strings.HasSuffix(name, "Private") { return } fullnm := strings.ToLower(si.Namespace()) + "." + name if config.is_disguised(fullnm) { size = -1 } if !config.is_blacklisted("structdefs", name) { switch size { case -1: p("type %s struct { Pointer unsafe.Pointer }\n", name) case 0: p("type %s struct {}\n", name) default: p("type %s struct {\n", name) offset := 0 for i, n := 0, si.NumField(); i < n; i++ { field := si.Field(i) fo := field.Offset() ft := field.Type() nm := field.Name() if fo != offset { pad := fo - offset p("\t_ [%d]byte\n", pad) offset += pad } if type_needs_wrapper(ft) { p("\t%s0 %s\n", nm, cgo_type(ft, type_exact)) } else { p("\t%s %s\n", lower_case_to_camel_case(nm), go_type(ft, type_exact)) } offset += type_size(ft, type_exact) } if size != offset { p("\t_ [%d]byte\n", size-offset) } p("}\n") //printf("type %s struct { data [%d]byte }\n", name, size) } // for each field that needs a wrapper, generate it for i, n := 0, si.NumField(); i < n; i++ { field := si.Field(i) ft := field.Type() nm := field.Name() if !type_needs_wrapper(ft) { continue } gotype := go_type(ft, type_return) p("func (this0 *%s) %s() %s {\n", name, lower_case_to_camel_case(nm), gotype) p("\tvar %s1 %s\n", nm, gotype) conv := cgo_to_go(ft, "this0."+nm+"0", nm+"1", conv_own_none, 0) p("%s", print_lines_with_indent(conv)) p("\treturn %s1\n", nm) p("}\n") } } for i, n := 0, si.NumMethod(); i < n; i++ { meth := si.Method(i) if config.is_method_blacklisted(name, meth.Name()) { continue } this.process_function_info(meth) } } func (this *binding_generator) process_union_info(ui *gi.UnionInfo) { p := printer_to(&this.go_bindings) name := ui.Name() p("type %s struct {\n", name) p("\t_data [%d]byte\n", ui.Size()) p("}\n") for i, n := 0, ui.NumMethod(); i < n; i++ { meth := ui.Method(i) if config.is_method_blacklisted(name, meth.Name()) { continue } this.process_function_info(meth) } } func (this *binding_generator) process_enum_info(ei *gi.EnumInfo) { p := printer_to(&this.go_bindings) p("type %s %s\n", ei.Name(), cgo_type_for_tag(ei.StorageType(), type_none)) p("const (\n") for i, n := 0, ei.NumValue(); i < n; i++ { val := ei.Value(i) p("\t%s%s %s = %d\n", ei.Name(), lower_case_to_camel_case(val.Name()), ei.Name(), val.Value()) } p(")\n") } func (this *binding_generator) process_constant_info(ci *gi.ConstantInfo) { p := printer_to(&this.go_bindings) name := ci.Name() if config.namespace == "Gdk" && strings.HasPrefix(name, "KEY_") { // KEY_ constants deserve a special treatment p("const Key_%s = %#v\n", name[4:], ci.Value()) return } p("const %s = %#v\n", lower_case_to_camel_case(strings.ToLower(name)), ci.Value()) } func (this *binding_generator) process_callback_info(ci *gi.CallableInfo) { p := printer_to(&this.go_bindings) // list of args var args []*gi.ArgInfo for i, n := 0, ci.NumArg(); i < n; i++ { arg := ci.Arg(i) args = append(args, arg) } userdata := -1 for i, arg := range args { if arg.Closure() != -1 { userdata = i break } // treat any void* as userdata O_o t := arg.Type() if t.Tag() == gi.TYPE_TAG_VOID && t.IsPointer() { userdata = i break } } if userdata == -1 { p("// blacklisted (no userdata): ") } name := ci.Name() p("type %s func(", name) for i, ri, n := 0, 0, len(args); i < n; i++ { if i == userdata { continue } // I use here TypeReturn because for closures it's inverted // C code calls closure and it has to be concrete and Go code // returns stuff to C (like calling a C function) arg := args[i] if ri != 0 { p(", ") } p("%s %s", arg.Name(), go_type(arg.Type(), type_return)) ri++ } rt := ci.ReturnType() if !rt.IsPointer() && rt.Tag() == gi.TYPE_TAG_VOID { p(")\n") } else { p(") %s\n", go_type(rt, type_none)) } if userdata == -1 { return } // now we need to generate two wrappers, it's a bit tricky due to cgo // ugliness. // 1. Function signature should consist of basic types and unsafe.Pointer // for any pointer type, cgo cannot export other kinds of functions. // 2. Convert these types to C.* ones. // 3. Convert C.* types to Go values. // 4. Call Go callback (function pointer is in the userdata). // 5. Convert all returned Go values to C.* types and then to basic cgo // friendly types. // signature ctype := c_type_for_interface(gi.ToBaseInfo(ci), type_none) p("//export _%s_c_wrapper\n", ctype) p("func _%s_c_wrapper(", ctype) for i, arg := range args { if i != 0 { p(", ") } p("%s0 %s", arg.Name(), simple_cgo_type(arg.Type(), type_none)) } p(") ") if ret := ci.ReturnType(); ret != nil && ret.Tag() != gi.TYPE_TAG_VOID { p("%s ", simple_cgo_type(ret, type_none)) } p("{\n") // --- body stage 1 (C to Go conversions) // var declarations for i, arg := range args { gotype := go_type(arg.Type(), type_return) if i == userdata { gotype = name } p("\tvar %s1 %s\n", arg.Name(), gotype) } // conversions for i, arg := range args { t := arg.Type() aname := arg.Name() if i == userdata { p("\t%s1 = *(*%s)(%s0)\n", aname, name, aname) continue } ownership := ownership_to_conv_flags(arg.OwnershipTransfer()) conv := simple_cgo_to_go(t, aname+"0", aname+"1", ownership) p("%s", print_lines_with_indent(conv)) } // --- body stage 2 (the callback call) p("\t") if ret := ci.ReturnType(); ret != nil && ret.Tag() != gi.TYPE_TAG_VOID { p("ret1 := ") } p("%s1(", args[userdata].Name()) for i, ri, n := 0, 0, len(args); i < n; i++ { if i == userdata { continue } if ri != 0 { p(", ") } p("%s1", args[i].Name()) ri++ } p(")\n") // --- body stage 3 (return value) if ret := ci.ReturnType(); ret != nil && ret.Tag() != gi.TYPE_TAG_VOID { p("\tvar ret2 %s\n", cgo_type(ret, type_none)) ownership := ownership_to_conv_flags(ci.CallerOwns()) conv := go_to_cgo(ret, "ret1", "ret2", ownership) p("%s", print_lines_with_indent(conv)) p("\treturn (%s)(ret2)\n", simple_cgo_type(ret, type_none)) } p("}\n") // and finally add "_once" wrapper p("//export _%s_c_wrapper_once\n", ctype) p("func _%s_c_wrapper_once(", ctype) for i, arg := range args { if i != 0 { p(", ") } p("%s0 %s", arg.Name(), simple_cgo_type(arg.Type(), type_none)) } p(") ") if ret := ci.ReturnType(); ret != nil && ret.Tag() != gi.TYPE_TAG_VOID { p("%s ", simple_cgo_type(ret, type_none)) } p("{\n\t") if ret := ci.ReturnType(); ret != nil && ret.Tag() != gi.TYPE_TAG_VOID { p("ret := ") } p("_%s_c_wrapper(", ctype) for i, arg := range args { if i != 0 { p(", ") } p("%s0", arg.Name()) } p(")\n") p("\t%sHolder.Release(%s0)\n", config.gns, args[userdata].Name()) if ret := ci.ReturnType(); ret != nil && ret.Tag() != gi.TYPE_TAG_VOID { p("\treturn ret\n") } p("}\n") } func (this *binding_generator) process_function_info(fi *gi.FunctionInfo) { p := printer_to(&this.go_bindings) var fullnm string flags := fi.Flags() name := fi.Name() container := fi.Container() // --- header fb := new_function_builder(fi) p("func ") if flags&gi.FUNCTION_IS_METHOD != 0 { // add receiver if it's a method p("(this0 %s) ", go_type_for_interface(container, type_pointer|type_receiver)) fullnm = container.Name() + "." } switch { case flags&gi.FUNCTION_IS_CONSTRUCTOR != 0: // special names for constructors name = fmt.Sprintf("New%s%s", container.Name(), ctor_suffix(name)) case flags&gi.FUNCTION_IS_METHOD == 0 && container != nil: name = fmt.Sprintf("%s%s", container.Name(), lower_case_to_camel_case(name)) default: name = fmt.Sprintf("%s", lower_case_to_camel_case(name)) } fullnm += name name = config.rename(fullnm, name) p("%s(", name) for i, arg := range fb.args { if i != 0 { p(", ") } p("%s0 %s", arg.arg_info.Name(), go_type(arg.type_info, type_none)) } p(")") switch len(fb.rets) { case 0: // do nothing if there are not return values case 1: if flags&gi.FUNCTION_IS_CONSTRUCTOR != 0 { // override return types for constructors, We can't // return generic widget here as C does. Go's type // system is stronger. p(" %s", go_type_for_interface(container, type_pointer|type_return)) break } if fb.rets[0].index == -2 { p(" error") } else { p(" %s", go_type(fb.rets[0].type_info, type_return)) } default: p(" (") for i, ret := range fb.rets { if ret.index == -2 { // special error type in Go to represent GError p("error") continue } p(go_type(ret.type_info, type_return)) if i != len(fb.rets)-1 { p(", ") } } p(")") } p(" {\n") // --- body stage 1 (Go to C conversions) // var declarations if flags&gi.FUNCTION_IS_METHOD != 0 { p("\tvar this1 %s\n", cgo_type_for_interface(container, type_pointer)) } for _, arg := range fb.args { p("\tvar %s1 %s\n", arg.arg_info.Name(), cgo_type(arg.type_info, type_none)) if al := arg.type_info.ArrayLength(); al != -1 { arg := fb.orig_args[al] p("\tvar %s1 %s\n", arg.Name(), cgo_type(arg.Type(), type_none)) } } for _, ret := range fb.rets { if ret.index == -1 { continue } if ret.index == -2 { p("\tvar err1 *C.GError\n") continue } if ret.arg_info.Direction() == gi.DIRECTION_INOUT { continue } p("\tvar %s1 %s\n", ret.arg_info.Name(), cgo_type(ret.type_info, type_none)) if al := ret.type_info.ArrayLength(); al != -1 { arg := fb.orig_args[al] p("\tvar %s1 %s\n", arg.Name(), cgo_type(arg.Type(), type_none)) } } // conversions if flags&gi.FUNCTION_IS_METHOD != 0 { conv := go_to_cgo_for_interface(container, "this0", "this1", conv_pointer) p("%s", print_lines_with_indent(conv)) } for _, arg := range fb.args { nm := arg.arg_info.Name() conv := go_to_cgo(arg.type_info, nm+"0", nm+"1", conv_none) p("%s", print_lines_with_indent(conv)) // register callback in the global map if arg.type_info.Tag() == gi.TYPE_TAG_INTERFACE { bi := arg.type_info.Interface() if bi.Type() == gi.INFO_TYPE_CALLBACK { if arg.arg_info.Scope() != gi.SCOPE_TYPE_CALL { p("\t%sHolder.Grab(%s1)\n", config.gns, nm) } } } // array length if len := arg.type_info.ArrayLength(); len != -1 { lenarg := fb.orig_args[len] conv = go_to_cgo(lenarg.Type(), "len("+nm+"0)", lenarg.Name()+"1", conv_none) p("\t%s\n", conv) } } // --- body stage 2 (the function call) p("\t") if fb.has_return_value() { p("ret1 := ") } userdata, destroy, scope := fb.has_closure_argument() p("C.") if scope != gi.SCOPE_TYPE_INVALID { p("_") } p("%s(", fi.Symbol()) if flags&gi.FUNCTION_IS_METHOD != 0 { p("this1") if len(fb.orig_args) > 0 { p(", ") } } for i, ri, n := 0, 0, len(fb.orig_args); i < n; i++ { if i == userdata || i == destroy { continue } oarg := fb.orig_args[i] var arg string dir := oarg.Direction() if dir == gi.DIRECTION_INOUT || dir == gi.DIRECTION_OUT { arg = fmt.Sprintf("&%s1", oarg.Name()) } else { arg = fmt.Sprintf("%s1", oarg.Name()) } if ri != 0 { p(", ") } p("%s", arg) ri++ } if flags&gi.FUNCTION_THROWS != 0 { p(", &err1") } p(")\n") // --- body stage 3 (C to Go conversions) // var declarations for _, ret := range fb.rets { switch ret.index { case -1: if flags&gi.FUNCTION_IS_CONSTRUCTOR != 0 { p("\tvar ret2 %s\n", go_type_for_interface(container, type_pointer|type_return)) } else { p("\tvar ret2 %s\n", go_type(ret.type_info, type_return)) } case -2: p("\tvar err2 error\n") default: p("\tvar %s2 %s\n", ret.arg_info.Name(), go_type(ret.type_info, type_return)) } } // conversions for _, ret := range fb.rets { if ret.index == -2 { p("\tif err1 != nil {\n") p("\t\terr2 = ((*_GError)(unsafe.Pointer(err1))).ToGError()\n") p("\t\tC.g_error_free(err1)\n") p("\t}\n") continue } var nm string if ret.index == -1 { nm = "ret" } else { nm = ret.arg_info.Name() } // array length if len := ret.type_info.ArrayLength(); len != -1 { // TODO: move this to cgo_to_go lenarg := fb.orig_args[len] p("\t%s2 = make(%s, %s)\n", nm, go_type(ret.type_info, type_return), lenarg.Name()+"1") } else if ret.type_info.IsZeroTerminated() { //p("\t%s2 = make(%s, uint(C._array_length(unsafe.Pointer(%s1))))\n", nm, go_type(ret.type_info, type_return), nm) } var ownership gi.Transfer if ret.index == -1 { ownership = fi.CallerOwns() } else { ownership = ret.arg_info.OwnershipTransfer() if ret.arg_info.Direction() == gi.DIRECTION_INOUT { // not sure if it's true in all cases, but so far ownership = gi.TRANSFER_NOTHING } } p("\n//DEBUG: %s1(%s):flags = %q\n", nm, ret.type_info.Tag(), ownership_to_conv_flags(ownership)) var conv string if flags&gi.FUNCTION_IS_CONSTRUCTOR != 0 && ret.index == -1 { conv = cgo_to_go_for_interface(container, "ret1", "ret2", conv_pointer|ownership_to_conv_flags(ownership)) } else { conv = cgo_to_go(ret.type_info, nm+"1", nm+"2", ownership_to_conv_flags(ownership), 0) } p("%s", print_lines_with_indent(conv)) } // --- body stage 4 (return) if len(fb.rets) == 0 { p("}\n") return } p("\treturn ") for i, ret := range fb.rets { var nm string switch ret.index { case -1: nm = "ret2" case -2: nm = "err2" default: nm = ret.arg_info.Name() + "2" } if i != 0 { p(", ") } p(nm) } p("\n}\n") } func (this *binding_generator) process_interface_info(ii *gi.InterfaceInfo) { p := printer_to(&this.go_bindings) name := ii.Name() cprefix := gi.DefaultRepository().CPrefix(ii.Namespace()) cgotype := cgo_type_for_interface(gi.ToBaseInfo(ii), type_pointer) p("%s\n", execute_template(interface_template, map[string]string{ "name": name, "cprefix": cprefix, "cgotype": cgotype, "typeinit": ii.TypeInit(), "gobjectns": config.gns, })) for i, n := 0, ii.NumMethod(); i < n; i++ { meth := ii.Method(i) if config.is_method_blacklisted(name, meth.Name()) { p("// blacklisted: %s.%s (method)\n", name, meth.Name()) continue } this.process_function_info(meth) } } func (this *binding_generator) process_base_info(bi *gi.BaseInfo) { p := printer_to(&this.go_bindings) if config.is_object_blacklisted(bi) { p("// blacklisted: %s (%s)\n", bi.Name(), bi.Type()) return } switch bi.Type() { case gi.INFO_TYPE_UNION: this.process_union_info(gi.ToUnionInfo(bi)) case gi.INFO_TYPE_STRUCT: this.process_struct_info(gi.ToStructInfo(bi)) case gi.INFO_TYPE_ENUM, gi.INFO_TYPE_FLAGS: this.process_enum_info(gi.ToEnumInfo(bi)) case gi.INFO_TYPE_CONSTANT: this.process_constant_info(gi.ToConstantInfo(bi)) case gi.INFO_TYPE_CALLBACK: this.process_callback_info(gi.ToCallableInfo(bi)) case gi.INFO_TYPE_FUNCTION: this.process_function_info(gi.ToFunctionInfo(bi)) case gi.INFO_TYPE_INTERFACE: this.process_interface_info(gi.ToInterfaceInfo(bi)) case gi.INFO_TYPE_OBJECT: this.process_object_info(gi.ToObjectInfo(bi)) default: p("// TODO: %s (%s)\n", bi.Name(), bi.Type()) } } go-gir-generator-master/src/gir-generator/cairo.go000066400000000000000000000045561414263242200225110ustar00rootroot00000000000000/** * Copyright (C) 2015 Deepin 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 of the License, or * (at your option) any later version. **/ package main import ( "bytes" "gi" ) func cairo_go_type_for_interface(bi *gi.BaseInfo, flags type_flags) string { var out bytes.Buffer p := printer_to(&out) name := bi.Name() switch name { case "Surface", "Pattern": if flags&type_return == 0 { p("cairo.%sLike", name) break } fallthrough default: if flags&type_pointer != 0 { p("*") } p("cairo.%s", name) } return out.String() } func cairo_go_to_cgo_for_interface(bi *gi.BaseInfo, arg0, arg1 string, flags conv_flags) string { var out bytes.Buffer p := printer_to(&out) name := bi.Name() switch name { case "Surface", "Pattern": p("if %s != nil {\n", arg0) p("\t%s = (*C.cairo%s)(%s.InheritedFromCairo%s().C)\n", arg1, name, arg0, name) p("}") case "RectangleInt", "Rectangle", "TextCluster", "Matrix": ctype := cgo_type_for_interface(bi, type_none) if flags&conv_pointer != 0 { p("%s = (*%s)(unsafe.Pointer(%s))", arg1, ctype, arg0) } else { p("%s = *(*%s)(unsafe.Pointer(&%s))", arg1, ctype, arg0) } default: p("if %s != nil {\n", arg0) p("\t%s = (*C.cairo%s)(%s.C)\n", arg1, name, arg0) p("}") } return out.String() } func cairo_cgo_to_go_for_interface(bi *gi.BaseInfo, arg1, arg2 string, flags conv_flags) string { var out bytes.Buffer p := printer_to(&out) name := bi.Name() switch name { case "Path", "FontOptions": if flags&conv_pointer == 0 { panic("unexpected non-pointer type") } p("%s = (*cairo.%s)(cairo.%sWrap(unsafe.Pointer(%s)))", arg2, name, name, arg1) case "Surface", "Region", "Pattern", "Context", "FontFace", "ScaledFont": if flags&conv_pointer == 0 { panic("unexpected non-pointer type") } grab := "true" if flags&conv_own_everything != 0 { grab = "false" } p("%s = (*cairo.%s)(cairo.%sWrap(unsafe.Pointer(%s), %s))", arg2, name, name, arg1, grab) default: gotype := go_type_for_interface(bi, type_return) if flags&conv_pointer != 0 { p("%s = (*%s)(unsafe.Pointer(%s))", arg2, gotype, arg1) } else { p("%s = *(*%s)(unsafe.Pointer(&%s))", arg2, gotype, arg1) } } return out.String() } go-gir-generator-master/src/gir-generator/comment_skipper.go000066400000000000000000000043121414263242200246010ustar00rootroot00000000000000/** * Copyright (C) 2015 Deepin 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 of the License, or * (at your option) any later version. **/ package main import "io" import "bufio" type comment_skipper struct { r *bufio.Reader } func new_comment_skipper(r io.Reader) *comment_skipper { return &comment_skipper{bufio.NewReader(r)} } // advance to str and consume it or return error if it's not possible func (cs *comment_skipper) advance_to(str string) error { if len(str) == 0 { panic("zero-length string is not acceptable") } cur := 0 for { b, err := cs.r.ReadByte() if err != nil { return err } for { // check if we have match with cur if str[cur] != b { break } // got match, see if there are other // symbols to match with and continue if so if len(str)-1 > cur { cur++ b, err = cs.r.ReadByte() if err != nil { return err } continue } return nil } } panic("unreachable") return nil } // advance to str, consume it, read and return the next byte if possible func (cs *comment_skipper) advance_to_and_read_byte(str string) (byte, error) { err := cs.advance_to(str) if err != nil { return 0, err } b, err := cs.r.ReadByte() if err != nil { return 0, err } return b, nil } func (cs *comment_skipper) Read(data []byte) (int, error) { read := 0 for { // check if we're done here if read == len(data) { return read, nil } b, err := cs.r.ReadByte() if err != nil { return read, err } // skip possible comments if b == '/' { b, err = cs.r.ReadByte() if err != nil { return read, err } switch b { case '/': // C++ comment err = cs.advance_to("\n") if err != nil { return read, err } b = '\n' case '*': // C comment b, err = cs.advance_to_and_read_byte("*/") if err != nil { return read, err } default: err = cs.r.UnreadByte() if err != nil { panic("shouldn't ever happen") } b = '/' } } data[read] = b read++ } panic("unreachable") return 0, nil } go-gir-generator-master/src/gir-generator/function_builder.go000066400000000000000000000054631414263242200247450ustar00rootroot00000000000000/** * Copyright (C) 2015 Deepin 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 of the License, or * (at your option) any later version. **/ package main import ( "gi" ) type function_builder struct { function *gi.FunctionInfo args []function_builder_arg rets []function_builder_arg orig_args []*gi.ArgInfo } type function_builder_arg struct { index int arg_info *gi.ArgInfo type_info *gi.TypeInfo } func int_slice_contains(haystack []int, needle int) bool { for _, val := range haystack { if val == needle { return true } } return false } func new_function_builder(fi *gi.FunctionInfo) *function_builder { fb := new(function_builder) fb.function = fi // prepare an array of ArgInfos for i, n := 0, fi.NumArg(); i < n; i++ { arg := fi.Arg(i) fb.orig_args = append(fb.orig_args, arg) } // build skip list var skiplist []int for _, arg := range fb.orig_args { ti := arg.Type() len := ti.ArrayLength() if len != -1 { skiplist = append(skiplist, len) } clo := arg.Closure() if clo != -1 { skiplist = append(skiplist, clo) } des := arg.Destroy() if des != -1 { skiplist = append(skiplist, des) } } // then walk over arguments for i, ai := range fb.orig_args { if int_slice_contains(skiplist, i) { continue } ti := ai.Type() switch ai.Direction() { case gi.DIRECTION_IN: fb.args = append(fb.args, function_builder_arg{i, ai, ti}) case gi.DIRECTION_INOUT: fb.args = append(fb.args, function_builder_arg{i, ai, ti}) fb.rets = append(fb.rets, function_builder_arg{i, ai, ti}) case gi.DIRECTION_OUT: fb.rets = append(fb.rets, function_builder_arg{i, ai, ti}) } } // add return value if it exists to 'rets' if ret := fi.ReturnType(); ret != nil && ret.Tag() != gi.TYPE_TAG_VOID { fb.rets = append(fb.rets, function_builder_arg{-1, nil, ret}) } // add GError special argument (if any) if fi.Flags()&gi.FUNCTION_THROWS != 0 { fb.rets = append(fb.rets, function_builder_arg{-2, nil, nil}) } return fb } func (fb *function_builder) has_return_value() bool { return (len(fb.rets) > 0 && fb.rets[len(fb.rets)-1].index == -1) || (len(fb.rets) > 1 && fb.rets[len(fb.rets)-2].index == -1) } func (fb *function_builder) has_closure_argument() (int, int, gi.ScopeType) { for _, arg := range fb.args { userdata := arg.arg_info.Closure() if userdata == -1 { continue } if arg.type_info.Tag() != gi.TYPE_TAG_INTERFACE { continue } if arg.type_info.Interface().Type() != gi.INFO_TYPE_CALLBACK { continue } destroy := arg.arg_info.Destroy() scope := arg.arg_info.Scope() return userdata, destroy, scope } return -1, -1, gi.SCOPE_TYPE_INVALID } go-gir-generator-master/src/gir-generator/main.go000066400000000000000000000131421414263242200223270ustar00rootroot00000000000000/** * Copyright (C) 2015 Deepin 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 of the License, or * (at your option) any later version. **/ package main import ( "bufio" "encoding/json" "flag" "fmt" "gi" "io/ioutil" "os" "path/filepath" "strings" ) var config config_type type config_type struct { out_go *bufio.Writer out_c *bufio.Writer out_h *bufio.Writer namespace string version string pkg string gns string renames map[string]string blacklist map[string]map[string]bool whitelist map[string]map[string]bool method_blacklist map[string]map[string]bool method_whitelist map[string]map[string]bool disguised_types map[string]bool word_subst map[string]string } func (this *config_type) load(path string) { var tmp struct { Namespace string `json:"namespace"` Version string `json:"version"` Blacklist map[string][]string `json:"blacklist"` Whitelist map[string][]string `json:"whitelist"` MethodBlacklist map[string][]string `json:"method-blacklist"` MethodWhitelist map[string][]string `json:"method-whitelist"` Renames map[string]string `json:"renames"` } err := parse_json_with_comments(path, &tmp) if err != nil { panic(err) } this.namespace = tmp.Namespace this.version = tmp.Version this.blacklist = map_list_to_map_map(tmp.Blacklist) this.whitelist = map_list_to_map_map(tmp.Whitelist) this.method_blacklist = map_list_to_map_map(tmp.MethodBlacklist) this.method_whitelist = map_list_to_map_map(tmp.MethodWhitelist) this.renames = tmp.Renames this.pkg = strings.ToLower(tmp.Namespace) if this.namespace != "GObject" { this.gns = "gobject." } } func (this *config_type) load_sys(path string) { var tmp struct { DisguisedTypes []string `json:"disguised-types"` WordSubst map[string]string `json:"word-subst"` } err := parse_json_with_comments(path, &tmp) if err != nil { panic(err) } this.disguised_types = list_to_map(tmp.DisguisedTypes) this.word_subst = tmp.WordSubst } func (this *config_type) rename(path, oldname string) string { if newname, ok := this.renames[path]; ok { return newname } return oldname } func (this *config_type) is_disguised(name string) bool { _, ok := this.disguised_types[name] return ok } func (this *config_type) is_object_blacklisted(bi *gi.BaseInfo) bool { switch bi.Type() { case gi.INFO_TYPE_UNION: return config.is_blacklisted("unions", bi.Name()) case gi.INFO_TYPE_STRUCT: return config.is_blacklisted("structs", bi.Name()) case gi.INFO_TYPE_ENUM, gi.INFO_TYPE_FLAGS: return config.is_blacklisted("enums", bi.Name()) case gi.INFO_TYPE_CONSTANT: return config.is_blacklisted("constants", bi.Name()) case gi.INFO_TYPE_CALLBACK: return config.is_blacklisted("callbacks", bi.Name()) case gi.INFO_TYPE_FUNCTION: c := bi.Container() if c != nil { return config.is_method_blacklisted(c.Name(), bi.Name()) } return config.is_blacklisted("functions", bi.Name()) case gi.INFO_TYPE_INTERFACE: return config.is_blacklisted("interfaces", bi.Name()) case gi.INFO_TYPE_OBJECT: return config.is_blacklisted("objects", bi.Name()) default: println("TODO: %s (%s)\n", bi.Name(), bi.Type()) return true } panic("unreachable") } func (this *config_type) is_blacklisted(section, entry string) bool { // check if the entry is in the blacklist if section_map, ok := this.blacklist[section]; ok { if _, ok := section_map[entry]; ok { return true } } // check if the entry is missing from the whitelist if section_map, ok := this.whitelist[section]; ok { if _, ok := section_map[entry]; !ok { return true } } return false } func (this *config_type) is_method_blacklisted(class, method string) bool { // don't want to see these if method == "ref" || method == "unref" { return true } if class_map, ok := this.method_blacklist[class]; ok { if _, ok := class_map[method]; ok { return true } } if class_map, ok := this.method_whitelist[class]; ok { if _, ok := class_map[method]; !ok { return true } } return false } func parse_json_with_comments(filename string, data interface{}) error { f, err := os.Open(filename) if err != nil { return err } defer f.Close() d := json.NewDecoder(new_comment_skipper(f)) err = d.Decode(data) if err != nil { return err } return nil } func main() { sysconfig_path := flag.String("config", "", "specify global config file") output_dir := flag.String("o", "", "override output directory") flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: %s [flags] \n", os.Args[0]) flag.PrintDefaults() } flag.Parse() if flag.NArg() != 1 { flag.Usage() return } // figure in/out paths in_dir, in_base := filepath.Split(flag.Arg(0)) in_path := flag.Arg(0) out_dir := in_dir if *output_dir != "" { out_dir = *output_dir os.MkdirAll(out_dir, 0755) } out_base := filepath.Join(out_dir, in_base[:len(in_base)-6]) // parse system config file if *sysconfig_path != "" { config.load_sys(*sysconfig_path) } // parse local config config.load(filepath.Join(in_dir, "config.json")) // load namespace _, err := gi.DefaultRepository().Require(config.namespace, config.version, 0) panic_if_error(err) // load go template go_template, err := ioutil.ReadFile(in_path) panic_if_error(err) // generate bindings bg := new_binding_generator(out_base) defer bg.release() bg.generate(string(go_template)) } go-gir-generator-master/src/gir-generator/templates.go000066400000000000000000000076451414263242200234140ustar00rootroot00000000000000/** * Copyright (C) 2015 Deepin 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 of the License, or * (at your option) any later version. **/ package main const g_object_ref_unref = `extern GObject *g_object_ref_sink(GObject*); extern void g_object_unref(GObject*);` const g_error_free = `extern void g_error_free(GError*);` const g_free = `extern void g_free(void*);` const g_list_funcs = ` GList* g_list_append(GList*, void*); void g_list_free(GList*); ` var go_utils_template = must_template(` const alot = 999999 type _GSList struct { data unsafe.Pointer next *_GSList } type _GList struct { data unsafe.Pointer next *_GList prev *_GList } type _GError struct { domain uint32 code int32 message *C.char } func (e _GError) ToGError() GError { return GError{e.domain, e.code, C.GoString(e.message)} } type GError struct { Domain uint32 Code int32 Message string } func (e GError) Error() string { return e.Message } func _GoStringToGString(x string) *C.char { if x == "\x00" { return nil } return C.CString(x) } func _GoBoolToCBool(x bool) C.int { if x { return 1 } return 0 } func _CInterfaceToGoInterface(iface [2]unsafe.Pointer) interface{} { return *(*interface{})(unsafe.Pointer(&iface)) } func _GoInterfaceToCInterface(iface interface{}) *unsafe.Pointer { return (*unsafe.Pointer)(unsafe.Pointer(&iface)) } [] //export _[<.namespace>]_go_callback_cleanup func _[<.namespace>]_go_callback_cleanup(gofunc unsafe.Pointer) { [<.gobjectns>]Holder.Release(gofunc) } [] `) var object_template = must_template(` type [<.name>]Like interface { [<.parentlike>] InheritedFrom[<.cprefix>][<.name>]() [<.cgotype>] } type [<.name>] struct { [<.parent>] [<.interfaces>] } func To[<.name>](objlike [<.gobjectns>]ObjectLike) *[<.name>] { c := objlike.InheritedFromGObject() if c == nil { return nil } t := (*[<.name>])(nil).GetStaticType() obj := [<.gobjectns>]ObjectGrabIfType(unsafe.Pointer(c), t) if obj != nil { return (*[<.name>])(obj) } panic("cannot cast to [<.name>]") } func (this0 *[<.name>]) InheritedFrom[<.cprefix>][<.name>]() [<.cgotype>] { if this0 == nil { return nil } return ([<.cgotype>])(this0.C) } func (this0 *[<.name>]) GetStaticType() [<.gobjectns>]Type { return [<.gobjectns>]Type(C.[<.typeinit>]()) } func [<.name>]GetType() [<.gobjectns>]Type { return (*[<.name>])(nil).GetStaticType() } `) // XXX: uses gc specific hack, expect problems on gccgo and/or ask developers // about the address of an empty embedded struct var interface_template = must_template(` type [<.name>]Like interface { Implements[<.cprefix>][<.name>]() [<.cgotype>] } type [<.name>] struct { [<.gobjectns>]Object [<.name>]Impl } func (*[<.name>]) GetStaticType() [<.gobjectns>]Type { return [<.gobjectns>]Type(C.[<.typeinit>]()) } type [<.name>]Impl struct {} func To[<.name>](objlike [<.gobjectns>]ObjectLike) *[<.name>] { c := objlike.InheritedFromGObject() obj := [<.gobjectns>]ObjectGrabIfType(unsafe.Pointer(c), [<.gobjectns>]Type(C.[<.typeinit>]())) if obj != nil { return (*[<.name>])(obj) } panic("cannot cast to [<.name>]") } func (this0 *[<.name>]Impl) Implements[<.cprefix>][<.name>]() [<.cgotype>] { base := unsafe.Pointer(uintptr(unsafe.Pointer(this0)) - unsafe.Sizeof(uintptr(0))) return ([<.cgotype>])((*[<.gobjectns>]Object)(base).C) } `) const c_header = `#pragma once #include #include typedef size_t GType; typedef void *GVaClosureMarshal; static unsigned int _array_length(void* _array) { void** array = (void**)_array; unsigned int i=0; while (array && array[i] != 0) i++; return i; } ` var c_template = must_template(` #include "[<.package>].gen.h" #include "_cgo_export.h" static void _c_callback_cleanup(void *userdata) { _[<.namespace>]_go_callback_cleanup(userdata); } `) go-gir-generator-master/src/gir-generator/type.go000066400000000000000000000343131414263242200223670ustar00rootroot00000000000000/** * Copyright (C) 2015 Deepin 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 of the License, or * (at your option) any later version. **/ // Converting GIR type to Go/C representation package main import ( "bytes" "fmt" "gi" "strings" "unsafe" ) func force_pointer(x string) string { if x == "unsafe.Pointer" { return x } if !strings.HasPrefix(x, "*") { return "*" + x } return x } type type_flags int const ( type_none type_flags = 0 type_pointer type_flags = 1 << iota type_return type_list_member type_receiver type_exact ) //------------------------------------------------------------------ // Cgo Type (C type in Go) //------------------------------------------------------------------ func cgo_type(ti *gi.TypeInfo, flags type_flags) string { var out bytes.Buffer switch tag := ti.Tag(); tag { case gi.TYPE_TAG_VOID: if ti.IsPointer() { out.WriteString("unsafe.Pointer") break } panic("Non-pointer void type is not supported in cgo") case gi.TYPE_TAG_UTF8, gi.TYPE_TAG_FILENAME: out.WriteString("*C.char") case gi.TYPE_TAG_ARRAY: switch ti.ArrayType() { case gi.ARRAY_TYPE_C: out.WriteString("*") out.WriteString(cgo_type(ti.ParamType(0), flags)) case gi.ARRAY_TYPE_ARRAY: out.WriteString("*C.GArray") case gi.ARRAY_TYPE_PTR_ARRAY: out.WriteString("*C.GPtrArray") case gi.ARRAY_TYPE_BYTE_ARRAY: out.WriteString("*C.GByteArray") } case gi.TYPE_TAG_GLIST: out.WriteString("*C.GList") case gi.TYPE_TAG_GSLIST: out.WriteString("*C.GSList") case gi.TYPE_TAG_GHASH: out.WriteString("*C.GHashTable") case gi.TYPE_TAG_ERROR: out.WriteString("*C.GError") case gi.TYPE_TAG_INTERFACE: if ti.IsPointer() { flags |= type_pointer } out.WriteString(cgo_type_for_interface(ti.Interface(), flags)) default: if ti.IsPointer() { out.WriteString("*") } out.WriteString(cgo_type_for_tag(tag, flags)) } return out.String() } func cgo_type_for_interface(bi *gi.BaseInfo, flags type_flags) string { var out bytes.Buffer switch bi.Type() { case gi.INFO_TYPE_CALLBACK: out.WriteString("unsafe.Pointer") default: ns := bi.Namespace() nm := bi.Name() fullnm := strings.ToLower(ns) + "." + nm if flags&type_pointer != 0 && !config.is_disguised(fullnm) { out.WriteString("*") } out.WriteString("C.") out.WriteString(gi.DefaultRepository().CPrefix(ns)) out.WriteString(bi.Name()) } return out.String() } func cgo_type_for_tag(tag gi.TypeTag, flags type_flags) string { var out bytes.Buffer p := printer_to(&out) if flags&type_pointer != 0 { p("*") } switch tag { case gi.TYPE_TAG_BOOLEAN: p("C.int") case gi.TYPE_TAG_INT8: p("C.int8_t") case gi.TYPE_TAG_UINT8: p("C.uint8_t") case gi.TYPE_TAG_INT16: p("C.int16_t") case gi.TYPE_TAG_UINT16: p("C.uint16_t") case gi.TYPE_TAG_INT32: p("C.int32_t") case gi.TYPE_TAG_UINT32: p("C.uint32_t") case gi.TYPE_TAG_INT64: p("C.int64_t") case gi.TYPE_TAG_UINT64: p("C.uint64_t") case gi.TYPE_TAG_FLOAT: p("C.float") case gi.TYPE_TAG_DOUBLE: p("C.double") case gi.TYPE_TAG_GTYPE: p("C.GType") case gi.TYPE_TAG_UNICHAR: p("C.uint32_t") default: panic("unreachable") } return out.String() } //------------------------------------------------------------------ // C Type //------------------------------------------------------------------ func c_type_for_tag(tag gi.TypeTag, flags type_flags) string { return cgo_type_for_tag(tag, flags)[2:] } func c_type(ti *gi.TypeInfo, flags type_flags) string { var out bytes.Buffer switch tag := ti.Tag(); tag { case gi.TYPE_TAG_VOID: if ti.IsPointer() { out.WriteString("void*") break } out.WriteString("void") case gi.TYPE_TAG_UTF8, gi.TYPE_TAG_FILENAME: out.WriteString("char*") case gi.TYPE_TAG_ARRAY: switch ti.ArrayType() { case gi.ARRAY_TYPE_C: out.WriteString(c_type(ti.ParamType(0), flags)) out.WriteString("*") case gi.ARRAY_TYPE_ARRAY: out.WriteString("GArray*") case gi.ARRAY_TYPE_PTR_ARRAY: out.WriteString("GPtrArray*") case gi.ARRAY_TYPE_BYTE_ARRAY: out.WriteString("GByteArray*") } case gi.TYPE_TAG_GLIST: out.WriteString("GList*") case gi.TYPE_TAG_GSLIST: out.WriteString("GSList*") case gi.TYPE_TAG_GHASH: out.WriteString("GHashTable*") case gi.TYPE_TAG_ERROR: out.WriteString("GError*") case gi.TYPE_TAG_INTERFACE: if ti.IsPointer() { flags |= type_pointer } out.WriteString(c_type_for_interface(ti.Interface(), flags)) default: out.WriteString(c_type_for_tag(tag, flags)) if ti.IsPointer() { out.WriteString("*") } } return out.String() } func c_type_for_interface(bi *gi.BaseInfo, flags type_flags) string { var out bytes.Buffer ns := bi.Namespace() nm := bi.Name() fullnm := strings.ToLower(ns) + "." + nm out.WriteString(gi.DefaultRepository().CPrefix(ns)) out.WriteString(bi.Name()) if flags&type_pointer != 0 && !config.is_disguised(fullnm) { out.WriteString("*") } return out.String() } //------------------------------------------------------------------ // Go Type //------------------------------------------------------------------ func go_type_for_interface(bi *gi.BaseInfo, flags type_flags) string { var out bytes.Buffer printf := printer_to(&out) ns := bi.Namespace() fullnm := strings.ToLower(ns) + "." + bi.Name() if flags&type_list_member != 0 { switch bi.Type() { case gi.INFO_TYPE_OBJECT, gi.INFO_TYPE_INTERFACE: return go_type_for_interface(bi, type_pointer|type_return) default: return go_type_for_interface(bi, type_return) } } switch t := bi.Type(); t { case gi.INFO_TYPE_OBJECT, gi.INFO_TYPE_INTERFACE: if flags&type_exact != 0 { // exact type for object/interface is always an unsafe.Pointer printf("unsafe.Pointer") break } if flags&(type_return|type_receiver) != 0 && flags&type_pointer != 0 { // receivers and return values are actual types, // and a pointer most likely printf("*") } if ns != config.namespace { // prepend foreign types with appropriate namespace printf("%s.", strings.ToLower(ns)) } printf(bi.Name()) if flags&(type_return|type_receiver) == 0 { // ordinary function arguments are substituted by their *Like // counterparts printf("Like") } if flags&type_receiver != 0 && t == gi.INFO_TYPE_INTERFACE { // special case for interfaces, we use *Impl structures // as receivers printf("Impl") } case gi.INFO_TYPE_CALLBACK: if flags&type_exact != 0 { printf("unsafe.Pointer") break } goto handle_default case gi.INFO_TYPE_STRUCT: if ns == "cairo" { printf(cairo_go_type_for_interface(bi, flags)) break } goto handle_default default: goto handle_default } return out.String() handle_default: if flags&type_pointer != 0 && !config.is_disguised(fullnm) { printf("*") } if ns != config.namespace { printf("%s.", strings.ToLower(ns)) } printf(bi.Name()) return out.String() } func go_type(ti *gi.TypeInfo, flags type_flags) string { var out bytes.Buffer switch tag := ti.Tag(); tag { case gi.TYPE_TAG_VOID: if ti.IsPointer() { out.WriteString("unsafe.Pointer") break } panic("Non-pointer void type is not supported") case gi.TYPE_TAG_UTF8, gi.TYPE_TAG_FILENAME: if flags&type_exact != 0 { out.WriteString("unsafe.Pointer") } else { out.WriteString("string") } case gi.TYPE_TAG_ARRAY: size := ti.ArrayFixedSize() if size != -1 { fmt.Fprintf(&out, "[%d]", size) } else { if flags&type_exact != 0 { out.WriteString("unsafe.Pointer") } else { out.WriteString("[]") } } out.WriteString(go_type(ti.ParamType(0), flags)) case gi.TYPE_TAG_GLIST: if flags&type_exact != 0 { out.WriteString("unsafe.Pointer") } else { out.WriteString("[]") out.WriteString(go_type(ti.ParamType(0), flags|type_list_member)) } case gi.TYPE_TAG_GSLIST: if flags&type_exact != 0 { out.WriteString("unsafe.Pointer") } else { out.WriteString("[]") out.WriteString(go_type(ti.ParamType(0), flags|type_list_member)) } case gi.TYPE_TAG_GHASH: if flags&type_exact != 0 { out.WriteString("unsafe.Pointer") } else { out.WriteString("map[") out.WriteString(go_type(ti.ParamType(0), flags)) out.WriteString("]") out.WriteString(go_type(ti.ParamType(1), flags)) } case gi.TYPE_TAG_ERROR: // not used? out.WriteString("error") case gi.TYPE_TAG_INTERFACE: if ti.IsPointer() { flags |= type_pointer } out.WriteString(go_type_for_interface(ti.Interface(), flags)) default: if ti.IsPointer() { flags |= type_pointer } out.WriteString(go_type_for_tag(tag, flags)) } return out.String() } func go_type_for_tag(tag gi.TypeTag, flags type_flags) string { var out bytes.Buffer p := printer_to(&out) if flags&type_pointer != 0 { p("*") } if flags&type_exact != 0 { switch tag { case gi.TYPE_TAG_BOOLEAN: p("int32") // sadly case gi.TYPE_TAG_INT8: p("int8") case gi.TYPE_TAG_UINT8: p("uint8") case gi.TYPE_TAG_INT16: p("int16") case gi.TYPE_TAG_UINT16: p("uint16") case gi.TYPE_TAG_INT32: p("int32") case gi.TYPE_TAG_UINT32: p("uint32") case gi.TYPE_TAG_INT64: p("int64") case gi.TYPE_TAG_UINT64: p("uint64") case gi.TYPE_TAG_FLOAT: p("float32") case gi.TYPE_TAG_DOUBLE: p("float64") case gi.TYPE_TAG_GTYPE: if config.namespace != "GObject" { p("gobject.Type") } else { p("Type") } case gi.TYPE_TAG_UNICHAR: p("rune") default: panic("unreachable") } } else { switch tag { case gi.TYPE_TAG_BOOLEAN: p("bool") case gi.TYPE_TAG_INT8: p("int8") case gi.TYPE_TAG_UINT8: p("uint8") case gi.TYPE_TAG_INT16: p("int16") case gi.TYPE_TAG_UINT16: p("uint16") case gi.TYPE_TAG_INT32: p("int32") case gi.TYPE_TAG_UINT32: p("uint32") case gi.TYPE_TAG_INT64: p("int64") case gi.TYPE_TAG_UINT64: p("uint64") case gi.TYPE_TAG_FLOAT: p("float32") case gi.TYPE_TAG_DOUBLE: p("float64") case gi.TYPE_TAG_GTYPE: if config.namespace != "GObject" { p("gobject.Type") } else { p("Type") } case gi.TYPE_TAG_UNICHAR: p("rune") default: panic("unreachable") } } return out.String() } //------------------------------------------------------------------ // Simple Cgo Type (for exported functions) //------------------------------------------------------------------ func simple_cgo_type(ti *gi.TypeInfo, flags type_flags) string { tag := ti.Tag() switch tag { case gi.TYPE_TAG_VOID: if ti.IsPointer() { return "unsafe.Pointer" } panic("Non-pointer void type is not supported") case gi.TYPE_TAG_INTERFACE: bi := ti.Interface() switch bi.Type() { case gi.INFO_TYPE_ENUM, gi.INFO_TYPE_FLAGS: ei := gi.ToEnumInfo(bi) return go_type_for_tag(ei.StorageType(), flags|type_exact) case gi.INFO_TYPE_STRUCT: ns := bi.Namespace() nm := bi.Name() fullnm := strings.ToLower(ns) + "." + nm if config.is_disguised(fullnm) { return "unsafe.Pointer" } } } if !strings.HasPrefix(cgo_type(ti, flags), "*") { return go_type_for_tag(tag, flags|type_exact) } return "unsafe.Pointer" } //------------------------------------------------------------------ // Type sizes //------------------------------------------------------------------ func type_size_for_interface(bi *gi.BaseInfo, flags type_flags) int { ptrsize := int(unsafe.Sizeof(unsafe.Pointer(nil))) if flags&type_pointer != 0 { return ptrsize } switch t := bi.Type(); t { case gi.INFO_TYPE_OBJECT, gi.INFO_TYPE_INTERFACE: return ptrsize case gi.INFO_TYPE_STRUCT: si := gi.ToStructInfo(bi) return si.Size() case gi.INFO_TYPE_UNION: ui := gi.ToUnionInfo(bi) return ui.Size() case gi.INFO_TYPE_ENUM, gi.INFO_TYPE_FLAGS: ei := gi.ToEnumInfo(bi) return type_size_for_tag(ei.StorageType(), flags) case gi.INFO_TYPE_CALLBACK: return ptrsize } panic("unreachable: " + bi.Type().String()) } // returns the size of a type, works only for TypeExact func type_size(ti *gi.TypeInfo, flags type_flags) int { ptrsize := int(unsafe.Sizeof(unsafe.Pointer(nil))) switch tag := ti.Tag(); tag { case gi.TYPE_TAG_VOID: if ti.IsPointer() { return ptrsize } panic("Non-pointer void type is not supported") case gi.TYPE_TAG_UTF8, gi.TYPE_TAG_FILENAME, gi.TYPE_TAG_GLIST, gi.TYPE_TAG_GSLIST, gi.TYPE_TAG_GHASH: return ptrsize case gi.TYPE_TAG_ARRAY: size := ti.ArrayFixedSize() if size != -1 { return size * type_size(ti.ParamType(0), flags) } return ptrsize case gi.TYPE_TAG_INTERFACE: if ti.IsPointer() { flags |= type_pointer } return type_size_for_interface(ti.Interface(), flags) default: if ti.IsPointer() { flags |= type_pointer } return type_size_for_tag(tag, flags) } panic("unreachable: " + ti.Tag().String()) } func type_size_for_tag(tag gi.TypeTag, flags type_flags) int { ptrsize := int(unsafe.Sizeof(unsafe.Pointer(nil))) if flags&type_pointer != 0 { return ptrsize } switch tag { case gi.TYPE_TAG_BOOLEAN: return 4 case gi.TYPE_TAG_INT8: return 1 case gi.TYPE_TAG_UINT8: return 1 case gi.TYPE_TAG_INT16: return 2 case gi.TYPE_TAG_UINT16: return 2 case gi.TYPE_TAG_INT32: return 4 case gi.TYPE_TAG_UINT32: return 4 case gi.TYPE_TAG_INT64: return 8 case gi.TYPE_TAG_UINT64: return 8 case gi.TYPE_TAG_FLOAT: return 4 case gi.TYPE_TAG_DOUBLE: return 8 case gi.TYPE_TAG_GTYPE: return ptrsize case gi.TYPE_TAG_UNICHAR: return 4 } panic("unreachable: " + tag.String()) } //------------------------------------------------------------------ // Type needs wrapper? //------------------------------------------------------------------ func type_needs_wrapper(ti *gi.TypeInfo) bool { switch tag := ti.Tag(); tag { case gi.TYPE_TAG_VOID: if ti.IsPointer() { return false } panic("Non-pointer void type is not supported") case gi.TYPE_TAG_UTF8, gi.TYPE_TAG_FILENAME, gi.TYPE_TAG_GLIST, gi.TYPE_TAG_GSLIST, gi.TYPE_TAG_GHASH: return true case gi.TYPE_TAG_ARRAY: size := ti.ArrayFixedSize() if size != -1 { return type_needs_wrapper(ti.ParamType(0)) } return true case gi.TYPE_TAG_ERROR: panic("not implemented") case gi.TYPE_TAG_INTERFACE: switch ti.Interface().Type() { case gi.INFO_TYPE_CALLBACK, gi.INFO_TYPE_ENUM, gi.INFO_TYPE_FLAGS, gi.INFO_TYPE_STRUCT, gi.INFO_TYPE_UNION: return false } return true } return false } go-gir-generator-master/src/gir-generator/typeconv.go000066400000000000000000000272721414263242200232630ustar00rootroot00000000000000/** * Copyright (C) 2015 Deepin 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 of the License, or * (at your option) any later version. **/ package main import ( "bytes" "fmt" "gi" "strings" ) func cgo_array_to_go_array(elem *gi.TypeInfo, name string) string { return fmt.Sprintf("(*(*[999999]%s)(unsafe.Pointer(%s)))", cgo_type(elem, type_none), name) } type conv_flags int const ( conv_none conv_flags = 0 conv_pointer conv_flags = 1 << iota conv_list_member conv_own_none conv_own_container conv_own_everything ) func (v conv_flags) String() string { var r = "" if v&conv_pointer != 0 { r += " conv_pointer" } if v&conv_list_member != 0 { r += " conv_list_member" } if v&conv_own_none != 0 { r += " conv_own_none" } if v&conv_own_container != 0 { r += " conv_own_container" } if v&conv_own_everything != 0 { r += " conv_own_everything" } if r == "" { return "conv_none" } return r } func ownership_to_conv_flags(t gi.Transfer) conv_flags { switch t { case gi.TRANSFER_NOTHING: return conv_own_none case gi.TRANSFER_CONTAINER: return conv_own_container case gi.TRANSFER_EVERYTHING: return conv_own_everything } return 0 } //------------------------------------------------------------------ // Go to Cgo Converter //------------------------------------------------------------------ func go_to_cgo_for_interface(bi *gi.BaseInfo, arg0, arg1 string, flags conv_flags) string { var out bytes.Buffer printf := printer_to(&out) switch bi.Type() { case gi.INFO_TYPE_OBJECT: prefix := gi.DefaultRepository().CPrefix(bi.Namespace()) ctypeName := prefix + bi.Name() printf("if %s != nil {\n", arg0) printf("\t%s = (*C.%s)(%s.InheritedFrom%s())\n", arg1, ctypeName, arg0, ctypeName) printf("}") case gi.INFO_TYPE_ENUM, gi.INFO_TYPE_FLAGS: ctype := cgo_type_for_interface(bi, type_none) printf("%s = %s(%s)", arg1, ctype, arg0) case gi.INFO_TYPE_INTERFACE: prefix := gi.DefaultRepository().CPrefix(bi.Namespace()) printf("if %s != nil {\n", arg0) printf("\t%s = %s.Implements%s%s()\n", arg1, arg0, prefix, bi.Name()) printf("}") case gi.INFO_TYPE_STRUCT: ns := bi.Namespace() if ns == "cairo" { printf(cairo_go_to_cgo_for_interface(bi, arg0, arg1, flags)) break } fullnm := strings.ToLower(ns) + "." + bi.Name() if config.is_disguised(fullnm) { flags &^= conv_pointer } ctype := cgo_type_for_interface(bi, type_none) if flags&conv_pointer != 0 { printf("%s = (*%s)(unsafe.Pointer(%s))", arg1, ctype, arg0) } else { printf("%s = *(*%s)(unsafe.Pointer(&%s))", arg1, ctype, arg0) } case gi.INFO_TYPE_CALLBACK: printf("if %s != nil {\n", arg0) printf("\t%s = unsafe.Pointer(&%s)", arg1, arg0) printf("}") } return out.String() } func go_to_cgo(ti *gi.TypeInfo, arg0, arg1 string, flags conv_flags) string { var out bytes.Buffer printf := printer_to(&out) switch tag := ti.Tag(); tag { case gi.TYPE_TAG_VOID: if ti.IsPointer() { printf("%s = unsafe.Pointer(%s)", arg1, arg0) break } printf("") case gi.TYPE_TAG_UTF8, gi.TYPE_TAG_FILENAME: printf("%s = _GoStringToGString(%s)", arg1, arg0) if flags&conv_own_everything == 0 { printf("\ndefer C.free(unsafe.Pointer(%s))", arg1) } case gi.TYPE_TAG_ARRAY: switch ti.ArrayType() { case gi.ARRAY_TYPE_C: var nelem string if ti.IsZeroTerminated() { nelem = fmt.Sprintf("(len(%s) + 1)", arg0) } else { nelem = fmt.Sprintf("len(%s)", arg0) } // alloc memory printf("%s = (%s)(C.malloc(C.size_t(int(unsafe.Sizeof(*%s)) * %s)))\n", arg1, cgo_type(ti, type_none), arg1, nelem) printf("defer C.free(unsafe.Pointer(%s))\n", arg1) // convert elements printf("for i, e := range %s {\n", arg0) array := cgo_array_to_go_array(ti.ParamType(0), arg1) conv := go_to_cgo(ti.ParamType(0), "e", array+"[i]", flags) printf(print_lines_with_indent(conv)) printf("}") // write a trailing zero if necessary (TODO: buggy) if ti.IsZeroTerminated() { printf("\n%s[len(%s)] = nil", array, arg0) } case gi.ARRAY_TYPE_ARRAY, gi.ARRAY_TYPE_PTR_ARRAY, gi.ARRAY_TYPE_BYTE_ARRAY: panic("Not implement") } case gi.TYPE_TAG_GLIST: // convert elements printf("for _, e := range %s {\n", arg0) var conv string if ti.ParamType(0).Tag() == gi.TYPE_TAG_INTERFACE { conv += fmt.Sprintf("var s %s\n", cgo_type(ti.ParamType(0), type_pointer)) } else { conv += fmt.Sprintf("var s %s\n", cgo_type(ti.ParamType(0), type_none)) } conv += fmt.Sprintln(go_to_cgo(ti.ParamType(0), "e", "s", flags)) conv += fmt.Sprintf("%s = C.g_list_append(%s, unsafe.Pointer(%s))", arg1, arg1, "s") printf(print_lines_with_indent(conv)) printf("}\n") printf("defer C.g_list_free(%s)", arg1) case gi.TYPE_TAG_GSLIST, gi.TYPE_TAG_GHASH, gi.TYPE_TAG_ERROR: //printf("//NOTE: Converting type of %v from go to cgo was not implemented.\n", tag) panic(fmt.Sprintf("Converting type of %v from go to cgo was not implemented.", tag)) case gi.TYPE_TAG_INTERFACE: if ti.IsPointer() { flags |= conv_pointer } printf(go_to_cgo_for_interface(ti.Interface(), arg0, arg1, flags)) default: if ti.IsPointer() { flags |= conv_pointer } printf(go_to_cgo_for_tag(tag, arg0, arg1, flags)) } return out.String() } func go_to_cgo_for_tag(tag gi.TypeTag, arg0, arg1 string, flags conv_flags) string { switch tag { case gi.TYPE_TAG_BOOLEAN: return fmt.Sprintf("%s = _GoBoolToCBool(%s)", arg1, arg0) default: if flags&conv_pointer == 0 { return fmt.Sprintf("%s = %s(%s)", arg1, cgo_type_for_tag(tag, type_none), arg0) } else { return fmt.Sprintf("%s = (%s)(unsafe.Pointer(%s))", arg1, cgo_type_for_tag(tag, type_pointer), arg0) } } panic("unreachable") return "" } //------------------------------------------------------------------ // Cgo to Go Converter //------------------------------------------------------------------ func cgo_to_go_for_interface(bi *gi.BaseInfo, arg1, arg2 string, flags conv_flags) string { var out bytes.Buffer printf := printer_to(&out) switch bi.Type() { case gi.INFO_TYPE_OBJECT, gi.INFO_TYPE_INTERFACE: gotype := go_type_for_interface(bi, type_return) if flags&conv_own_everything != 0 { printf("%s = (*%s)(%sObjectWrap(unsafe.Pointer(%s), false))", arg2, gotype, config.gns, arg1) } else { printf("%s = (*%s)(%sObjectWrap(unsafe.Pointer(%s), true))", arg2, gotype, config.gns, arg1) } case gi.INFO_TYPE_ENUM, gi.INFO_TYPE_FLAGS: gotype := go_type_for_interface(bi, type_return) printf("%s = %s(%s)", arg2, gotype, arg1) case gi.INFO_TYPE_STRUCT, gi.INFO_TYPE_UNION: ns := bi.Namespace() if ns == "cairo" { printf(cairo_cgo_to_go_for_interface(bi, arg1, arg2, flags)) break } fullnm := strings.ToLower(ns) + "." + bi.Name() gotype := go_type_for_interface(bi, type_return) if flags&conv_list_member != 0 { printf("%s = *(*%s)(unsafe.Pointer(%s))", arg2, gotype, arg1) break } if config.is_disguised(fullnm) { printf("%s = %s{unsafe.Pointer(%s)}", arg2, gotype, arg1) break } if flags&conv_pointer != 0 { printf("%s = (*%s)(unsafe.Pointer(%s))", arg2, gotype, arg1) } else { printf("%s = *(*%s)(unsafe.Pointer(&%s))", arg2, gotype, arg1) } } return out.String() } func cgo_to_go(ti *gi.TypeInfo, arg1, arg2 string, flags conv_flags, depth int) string { var out bytes.Buffer printf := printer_to(&out) switch tag := ti.Tag(); tag { case gi.TYPE_TAG_VOID: if ti.IsPointer() { printf("%s = %s", arg2, arg1) break } printf("") case gi.TYPE_TAG_UTF8, gi.TYPE_TAG_FILENAME: printf("%s = C.GoString(%s)", arg2, arg1) if flags&conv_own_everything != 0 { printf("\nC.g_free(unsafe.Pointer(%s))", arg1) } case gi.TYPE_TAG_ARRAY: switch ti.ArrayType() { case gi.ARRAY_TYPE_C: index := fmt.Sprintf("[i%d]", depth) if ti.IsZeroTerminated() { printf("%s = make(%s, C._array_length(unsafe.Pointer(%s)))\n", arg2, go_type(ti, type_return), arg1) } elementTi := ti.ParamType(0) // array was allocated already at this point printf("for i%d := range %s {\n", depth, arg2) array := cgo_array_to_go_array(elementTi, arg1) conv := cgo_to_go(ti.ParamType(0), array+index, arg2+index, flags, depth+1) printf(print_lines_with_indent(conv)) printf("}") if flags&conv_own_container != 0 || flags&conv_own_everything != 0 { printf("\nC.g_free(unsafe.Pointer(%s))", arg1) } case gi.ARRAY_TYPE_ARRAY, gi.ARRAY_TYPE_PTR_ARRAY, gi.ARRAY_TYPE_BYTE_ARRAY: panic("Not implement") } case gi.TYPE_TAG_GLIST: ptype := ti.ParamType(0) printf("for iter := (*_GList)(unsafe.Pointer(%s)); iter != nil; iter = iter.next {\n", arg1) elt := fmt.Sprintf("(%s)(iter.data)", force_pointer(cgo_type(ptype, type_return|type_list_member))) printf("\tvar elt %s\n", go_type(ptype, type_return|type_list_member)) conv := cgo_to_go(ptype, elt, "elt", flags|conv_list_member, depth+1) printf(print_lines_with_indent(conv)) printf("\t%s = append(%s, elt)\n", arg2, arg2) printf("}") if flags&conv_own_container != 0 || flags&conv_own_everything != 0 { printf("\nC.g_list_free(%s)", arg1) } case gi.TYPE_TAG_GSLIST: ptype := ti.ParamType(0) printf("for iter := (*_GSList)(unsafe.Pointer(%s)); iter != nil; iter = iter.next {\n", arg1) elt := fmt.Sprintf("(%s)(iter.data)", force_pointer(cgo_type(ptype, type_return|type_list_member))) printf("\tvar elt %s\n", go_type(ptype, type_return|type_list_member)) conv := cgo_to_go(ptype, elt, "elt", flags|conv_list_member, depth+1) printf(print_lines_with_indent(conv)) printf("\t%s = append(%s, elt)\n", arg2, arg2) printf("}") if flags&conv_own_container != 0 || flags&conv_own_everything != 0 { printf("\nC.g_slist_free(%s)", arg1) } case gi.TYPE_TAG_GHASH: panic("NotImplement") case gi.TYPE_TAG_INTERFACE: if ti.IsPointer() { flags |= conv_pointer } printf(cgo_to_go_for_interface(ti.Interface(), arg1, arg2, flags)) default: if ti.IsPointer() { flags |= conv_pointer } printf(cgo_to_go_for_tag(tag, arg1, arg2, flags)) } return out.String() } func cgo_to_go_for_tag(tag gi.TypeTag, arg1, arg2 string, flags conv_flags) string { switch tag { case gi.TYPE_TAG_BOOLEAN: return fmt.Sprintf("%s = %s != 0", arg2, arg1) case gi.TYPE_TAG_INT8: return fmt.Sprintf("%s = int8(%s)", arg2, arg1) case gi.TYPE_TAG_UINT8: return fmt.Sprintf("%s = uint8(%s)", arg2, arg1) case gi.TYPE_TAG_INT16: return fmt.Sprintf("%s = int16(%s)", arg2, arg1) case gi.TYPE_TAG_UINT16: return fmt.Sprintf("%s = uint16(%s)", arg2, arg1) case gi.TYPE_TAG_INT32: return fmt.Sprintf("%s = int32(%s)", arg2, arg1) case gi.TYPE_TAG_UINT32: return fmt.Sprintf("%s = uint32(%s)", arg2, arg1) case gi.TYPE_TAG_INT64: return fmt.Sprintf("%s = int64(%s)", arg2, arg1) case gi.TYPE_TAG_UINT64: return fmt.Sprintf("%s = uint64(%s)", arg2, arg1) case gi.TYPE_TAG_FLOAT: return fmt.Sprintf("%s = float32(%s)", arg2, arg1) case gi.TYPE_TAG_DOUBLE: return fmt.Sprintf("%s = float64(%s)", arg2, arg1) case gi.TYPE_TAG_GTYPE: if config.namespace != "GObject" { return fmt.Sprintf("%s = gobject.Type(%s)", arg2, arg1) } return fmt.Sprintf("%s = Type(%s)", arg2, arg1) case gi.TYPE_TAG_UNICHAR: return fmt.Sprintf("%s = rune(%s)", arg2, arg1) } panic("unreachable") return "" } //------------------------------------------------------------------ // Simple Cgo to Go Converter //------------------------------------------------------------------ func simple_cgo_to_go(ti *gi.TypeInfo, arg0, arg1 string, flags conv_flags) string { cgotype := cgo_type(ti, type_none) arg0 = fmt.Sprintf("(%s)(%s)", cgotype, arg0) return cgo_to_go(ti, arg0, arg1, flags, 0) } go-gir-generator-master/src/gir-generator/util.go000066400000000000000000000037431414263242200223660ustar00rootroot00000000000000/** * Copyright (C) 2015 Deepin 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 of the License, or * (at your option) any later version. **/ package main import ( "bytes" "fmt" "io" "strings" "text/template" ) func panic_if_error(err error) { if err != nil { panic(err) } } func printer_to(w io.Writer) func(string, ...interface{}) { return func(format string, args ...interface{}) { fmt.Fprintf(w, format, args...) } } func lower_case_to_camel_case(name string) string { var out bytes.Buffer for _, word := range strings.Split(name, "_") { word = strings.ToLower(word) if subst, ok := config.word_subst[word]; ok { out.WriteString(subst) continue } if word == "" { out.WriteString("_") continue } out.WriteString(strings.ToUpper(word[0:1])) out.WriteString(word[1:]) } return out.String() } func must_template(tpl string) *template.Template { tpl = strings.TrimSpace(tpl) return template.Must( template.New(""). Delims("[<", ">]"). Parse(tpl), ) } func execute_template(tpl *template.Template, args interface{}) string { var out bytes.Buffer tpl.Execute(&out, args) return out.String() } func ctor_suffix(name string) string { if len(name) > 4 { return lower_case_to_camel_case(name[4:]) } return "" } func print_lines_with_indent(str string) string { var out bytes.Buffer if str == "" { return "" } for _, line := range strings.Split(str, "\n") { fmt.Fprintf(&out, "\t%s\n", line) } return out.String() } func map_list_to_map_map(maplist map[string][]string) map[string]map[string]bool { out := make(map[string]map[string]bool) for section, list := range maplist { out[section] = list_to_map(list) } return out } func list_to_map(list []string) map[string]bool { m := make(map[string]bool) for _, entry := range list { m[entry] = true } return m } go-gir-generator-master/test/000077500000000000000000000000001414263242200164765ustar00rootroot00000000000000go-gir-generator-master/test/memory.go000066400000000000000000000017621414263242200203430ustar00rootroot00000000000000package main import ( "pkg.deepin.io/gir/gio-2.0" "runtime" "strings" ) import "time" import "syscall" import "fmt" import "os" func RSSinMB() int { var r syscall.Rusage err := syscall.Getrusage(syscall.RUSAGE_SELF, &r) if err != nil { panic(err) } return int(r.Maxrss) / 1024 } func TestFunc() { gio.AppInfoGetAll() gio.DesktopAppInfoSearch("d") runtime.GC() } func main() { var limit = 30 if strings.HasPrefix(runtime.GOARCH, "arm") { // GOARCH is arm or arm64 limit = 200 } fmt.Printf("limit: %dMB\n", limit) TestFunc() baseRSSinMB := RSSinMB() fmt.Printf("base: %dMB\n", baseRSSinMB) getIncreased := func() int { return RSSinMB() - baseRSSinMB } time.AfterFunc(time.Second*60, func() { fmt.Printf("increased: %dMB\n", getIncreased()) os.Exit(0) }) for { TestFunc() increasedInMB := getIncreased() if increasedInMB > limit { fmt.Printf("increased: %dMB\n", increasedInMB) panic(fmt.Errorf("increased beyond %dMB, detect a memory leak", limit)) } } } go-gir-generator-master/vendor/000077500000000000000000000000001414263242200170145ustar00rootroot00000000000000go-gir-generator-master/vendor/src/000077500000000000000000000000001414263242200176035ustar00rootroot00000000000000go-gir-generator-master/vendor/src/gopkg.in/000077500000000000000000000000001414263242200213175ustar00rootroot00000000000000go-gir-generator-master/vendor/src/gopkg.in/check.v1/000077500000000000000000000000001414263242200227215ustar00rootroot00000000000000go-gir-generator-master/vendor/src/gopkg.in/check.v1/LICENSE000066400000000000000000000025411414263242200237300ustar00rootroot00000000000000Gocheck - A rich testing framework for Go Copyright (c) 2010-2013 Gustavo Niemeyer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. go-gir-generator-master/vendor/src/gopkg.in/check.v1/README.md000066400000000000000000000004761414263242200242070ustar00rootroot00000000000000Instructions ============ Install the package with: go get gopkg.in/check.v1 Import it with: import "gopkg.in/check.v1" and use _check_ as the package name inside the code. For more details, visit the project page: * http://labix.org/gocheck and the API documentation: * https://gopkg.in/check.v1 go-gir-generator-master/vendor/src/gopkg.in/check.v1/TODO000066400000000000000000000000701414263242200234060ustar00rootroot00000000000000- Assert(slice, Contains, item) - Parallel test support go-gir-generator-master/vendor/src/gopkg.in/check.v1/benchmark.go000066400000000000000000000122021414263242200251770ustar00rootroot00000000000000// Copyright (c) 2012 The Go Authors. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package check import ( "fmt" "runtime" "time" ) var memStats runtime.MemStats // testingB is a type passed to Benchmark functions to manage benchmark // timing and to specify the number of iterations to run. type timer struct { start time.Time // Time test or benchmark started duration time.Duration N int bytes int64 timerOn bool benchTime time.Duration // The initial states of memStats.Mallocs and memStats.TotalAlloc. startAllocs uint64 startBytes uint64 // The net total of this test after being run. netAllocs uint64 netBytes uint64 } // StartTimer starts timing a test. This function is called automatically // before a benchmark starts, but it can also used to resume timing after // a call to StopTimer. func (c *C) StartTimer() { if !c.timerOn { c.start = time.Now() c.timerOn = true runtime.ReadMemStats(&memStats) c.startAllocs = memStats.Mallocs c.startBytes = memStats.TotalAlloc } } // StopTimer stops timing a test. This can be used to pause the timer // while performing complex initialization that you don't // want to measure. func (c *C) StopTimer() { if c.timerOn { c.duration += time.Now().Sub(c.start) c.timerOn = false runtime.ReadMemStats(&memStats) c.netAllocs += memStats.Mallocs - c.startAllocs c.netBytes += memStats.TotalAlloc - c.startBytes } } // ResetTimer sets the elapsed benchmark time to zero. // It does not affect whether the timer is running. func (c *C) ResetTimer() { if c.timerOn { c.start = time.Now() runtime.ReadMemStats(&memStats) c.startAllocs = memStats.Mallocs c.startBytes = memStats.TotalAlloc } c.duration = 0 c.netAllocs = 0 c.netBytes = 0 } // SetBytes informs the number of bytes that the benchmark processes // on each iteration. If this is called in a benchmark it will also // report MB/s. func (c *C) SetBytes(n int64) { c.bytes = n } func (c *C) nsPerOp() int64 { if c.N <= 0 { return 0 } return c.duration.Nanoseconds() / int64(c.N) } func (c *C) mbPerSec() float64 { if c.bytes <= 0 || c.duration <= 0 || c.N <= 0 { return 0 } return (float64(c.bytes) * float64(c.N) / 1e6) / c.duration.Seconds() } func (c *C) timerString() string { if c.N <= 0 { return fmt.Sprintf("%3.3fs", float64(c.duration.Nanoseconds())/1e9) } mbs := c.mbPerSec() mb := "" if mbs != 0 { mb = fmt.Sprintf("\t%7.2f MB/s", mbs) } nsop := c.nsPerOp() ns := fmt.Sprintf("%10d ns/op", nsop) if c.N > 0 && nsop < 100 { // The format specifiers here make sure that // the ones digits line up for all three possible formats. if nsop < 10 { ns = fmt.Sprintf("%13.2f ns/op", float64(c.duration.Nanoseconds())/float64(c.N)) } else { ns = fmt.Sprintf("%12.1f ns/op", float64(c.duration.Nanoseconds())/float64(c.N)) } } memStats := "" if c.benchMem { allocedBytes := fmt.Sprintf("%8d B/op", int64(c.netBytes)/int64(c.N)) allocs := fmt.Sprintf("%8d allocs/op", int64(c.netAllocs)/int64(c.N)) memStats = fmt.Sprintf("\t%s\t%s", allocedBytes, allocs) } return fmt.Sprintf("%8d\t%s%s%s", c.N, ns, mb, memStats) } func min(x, y int) int { if x > y { return y } return x } func max(x, y int) int { if x < y { return y } return x } // roundDown10 rounds a number down to the nearest power of 10. func roundDown10(n int) int { var tens = 0 // tens = floor(log_10(n)) for n > 10 { n = n / 10 tens++ } // result = 10^tens result := 1 for i := 0; i < tens; i++ { result *= 10 } return result } // roundUp rounds x up to a number of the form [1eX, 2eX, 5eX]. func roundUp(n int) int { base := roundDown10(n) if n < (2 * base) { return 2 * base } if n < (5 * base) { return 5 * base } return 10 * base } go-gir-generator-master/vendor/src/gopkg.in/check.v1/benchmark_test.go000066400000000000000000000052071414263242200262450ustar00rootroot00000000000000// These tests verify the test running logic. package check_test import ( "time" . "gopkg.in/check.v1" ) var benchmarkS = Suite(&BenchmarkS{}) type BenchmarkS struct{} func (s *BenchmarkS) TestCountSuite(c *C) { suitesRun += 1 } func (s *BenchmarkS) TestBasicTestTiming(c *C) { helper := FixtureHelper{sleepOn: "Test1", sleep: 1000000 * time.Nanosecond} output := String{} runConf := RunConf{Output: &output, Verbose: true} Run(&helper, &runConf) expected := "PASS: check_test\\.go:[0-9]+: FixtureHelper\\.Test1\t0\\.001s\n" + "PASS: check_test\\.go:[0-9]+: FixtureHelper\\.Test2\t0\\.000s\n" c.Assert(output.value, Matches, expected) } func (s *BenchmarkS) TestStreamTestTiming(c *C) { helper := FixtureHelper{sleepOn: "SetUpSuite", sleep: 1000000 * time.Nanosecond} output := String{} runConf := RunConf{Output: &output, Stream: true} Run(&helper, &runConf) expected := "(?s).*\nPASS: check_test\\.go:[0-9]+: FixtureHelper\\.SetUpSuite\t *0\\.001s\n.*" c.Assert(output.value, Matches, expected) } func (s *BenchmarkS) TestBenchmark(c *C) { helper := FixtureHelper{sleep: 100000} output := String{} runConf := RunConf{ Output: &output, Benchmark: true, BenchmarkTime: 10000000, Filter: "Benchmark1", } Run(&helper, &runConf) c.Check(helper.calls[0], Equals, "SetUpSuite") c.Check(helper.calls[1], Equals, "SetUpTest") c.Check(helper.calls[2], Equals, "Benchmark1") c.Check(helper.calls[3], Equals, "TearDownTest") c.Check(helper.calls[4], Equals, "SetUpTest") c.Check(helper.calls[5], Equals, "Benchmark1") c.Check(helper.calls[6], Equals, "TearDownTest") // ... and more. expected := "PASS: check_test\\.go:[0-9]+: FixtureHelper\\.Benchmark1\t *100\t *[12][0-9]{5} ns/op\n" c.Assert(output.value, Matches, expected) } func (s *BenchmarkS) TestBenchmarkBytes(c *C) { helper := FixtureHelper{sleep: 100000} output := String{} runConf := RunConf{ Output: &output, Benchmark: true, BenchmarkTime: 10000000, Filter: "Benchmark2", } Run(&helper, &runConf) expected := "PASS: check_test\\.go:[0-9]+: FixtureHelper\\.Benchmark2\t *100\t *[12][0-9]{5} ns/op\t *[4-9]\\.[0-9]{2} MB/s\n" c.Assert(output.value, Matches, expected) } func (s *BenchmarkS) TestBenchmarkMem(c *C) { helper := FixtureHelper{sleep: 100000} output := String{} runConf := RunConf{ Output: &output, Benchmark: true, BenchmarkMem: true, BenchmarkTime: 10000000, Filter: "Benchmark3", } Run(&helper, &runConf) expected := "PASS: check_test\\.go:[0-9]+: FixtureHelper\\.Benchmark3\t *100\t *[12][0-9]{5} ns/op\t *[0-9]+ B/op\t *[1-9] allocs/op\n" c.Assert(output.value, Matches, expected) } go-gir-generator-master/vendor/src/gopkg.in/check.v1/bootstrap_test.go000066400000000000000000000042431414263242200263270ustar00rootroot00000000000000// These initial tests are for bootstrapping. They verify that we can // basically use the testing infrastructure itself to check if the test // system is working. // // These tests use will break down the test runner badly in case of // errors because if they simply fail, we can't be sure the developer // will ever see anything (because failing means the failing system // somehow isn't working! :-) // // Do not assume *any* internal functionality works as expected besides // what's actually tested here. package check_test import ( "fmt" "gopkg.in/check.v1" "strings" ) type BootstrapS struct{} var boostrapS = check.Suite(&BootstrapS{}) func (s *BootstrapS) TestCountSuite(c *check.C) { suitesRun += 1 } func (s *BootstrapS) TestFailedAndFail(c *check.C) { if c.Failed() { critical("c.Failed() must be false first!") } c.Fail() if !c.Failed() { critical("c.Fail() didn't put the test in a failed state!") } c.Succeed() } func (s *BootstrapS) TestFailedAndSucceed(c *check.C) { c.Fail() c.Succeed() if c.Failed() { critical("c.Succeed() didn't put the test back in a non-failed state") } } func (s *BootstrapS) TestLogAndGetTestLog(c *check.C) { c.Log("Hello there!") log := c.GetTestLog() if log != "Hello there!\n" { critical(fmt.Sprintf("Log() or GetTestLog() is not working! Got: %#v", log)) } } func (s *BootstrapS) TestLogfAndGetTestLog(c *check.C) { c.Logf("Hello %v", "there!") log := c.GetTestLog() if log != "Hello there!\n" { critical(fmt.Sprintf("Logf() or GetTestLog() is not working! Got: %#v", log)) } } func (s *BootstrapS) TestRunShowsErrors(c *check.C) { output := String{} check.Run(&FailHelper{}, &check.RunConf{Output: &output}) if strings.Index(output.value, "Expected failure!") == -1 { critical(fmt.Sprintf("RunWithWriter() output did not contain the "+ "expected failure! Got: %#v", output.value)) } } func (s *BootstrapS) TestRunDoesntShowSuccesses(c *check.C) { output := String{} check.Run(&SuccessHelper{}, &check.RunConf{Output: &output}) if strings.Index(output.value, "Expected success!") != -1 { critical(fmt.Sprintf("RunWithWriter() output contained a successful "+ "test! Got: %#v", output.value)) } } go-gir-generator-master/vendor/src/gopkg.in/check.v1/check.go000066400000000000000000000561651414263242200243420ustar00rootroot00000000000000// Package check is a rich testing extension for Go's testing package. // // For details about the project, see: // // http://labix.org/gocheck // package check import ( "bytes" "errors" "fmt" "io" "math/rand" "os" "path" "path/filepath" "reflect" "regexp" "runtime" "strconv" "strings" "sync" "sync/atomic" "time" ) // ----------------------------------------------------------------------- // Internal type which deals with suite method calling. const ( fixtureKd = iota testKd ) type funcKind int const ( succeededSt = iota failedSt skippedSt panickedSt fixturePanickedSt missedSt ) type funcStatus uint32 // A method value can't reach its own Method structure. type methodType struct { reflect.Value Info reflect.Method } func newMethod(receiver reflect.Value, i int) *methodType { return &methodType{receiver.Method(i), receiver.Type().Method(i)} } func (method *methodType) PC() uintptr { return method.Info.Func.Pointer() } func (method *methodType) suiteName() string { t := method.Info.Type.In(0) if t.Kind() == reflect.Ptr { t = t.Elem() } return t.Name() } func (method *methodType) String() string { return method.suiteName() + "." + method.Info.Name } func (method *methodType) matches(re *regexp.Regexp) bool { return (re.MatchString(method.Info.Name) || re.MatchString(method.suiteName()) || re.MatchString(method.String())) } type C struct { method *methodType kind funcKind testName string _status funcStatus logb *logger logw io.Writer done chan *C reason string mustFail bool tempDir *tempDir benchMem bool startTime time.Time timer } func (c *C) status() funcStatus { return funcStatus(atomic.LoadUint32((*uint32)(&c._status))) } func (c *C) setStatus(s funcStatus) { atomic.StoreUint32((*uint32)(&c._status), uint32(s)) } func (c *C) stopNow() { runtime.Goexit() } // logger is a concurrency safe byte.Buffer type logger struct { sync.Mutex writer bytes.Buffer } func (l *logger) Write(buf []byte) (int, error) { l.Lock() defer l.Unlock() return l.writer.Write(buf) } func (l *logger) WriteTo(w io.Writer) (int64, error) { l.Lock() defer l.Unlock() return l.writer.WriteTo(w) } func (l *logger) String() string { l.Lock() defer l.Unlock() return l.writer.String() } // ----------------------------------------------------------------------- // Handling of temporary files and directories. type tempDir struct { sync.Mutex path string counter int } func (td *tempDir) newPath() string { td.Lock() defer td.Unlock() if td.path == "" { var err error for i := 0; i != 100; i++ { path := fmt.Sprintf("%s%ccheck-%d", os.TempDir(), os.PathSeparator, rand.Int()) if err = os.Mkdir(path, 0700); err == nil { td.path = path break } } if td.path == "" { panic("Couldn't create temporary directory: " + err.Error()) } } result := filepath.Join(td.path, strconv.Itoa(td.counter)) td.counter += 1 return result } func (td *tempDir) removeAll() { td.Lock() defer td.Unlock() if td.path != "" { err := os.RemoveAll(td.path) if err != nil { fmt.Fprintf(os.Stderr, "WARNING: Error cleaning up temporaries: "+err.Error()) } } } // Create a new temporary directory which is automatically removed after // the suite finishes running. func (c *C) MkDir() string { path := c.tempDir.newPath() if err := os.Mkdir(path, 0700); err != nil { panic(fmt.Sprintf("Couldn't create temporary directory %s: %s", path, err.Error())) } return path } // ----------------------------------------------------------------------- // Low-level logging functions. func (c *C) log(args ...interface{}) { c.writeLog([]byte(fmt.Sprint(args...) + "\n")) } func (c *C) logf(format string, args ...interface{}) { c.writeLog([]byte(fmt.Sprintf(format+"\n", args...))) } func (c *C) logNewLine() { c.writeLog([]byte{'\n'}) } func (c *C) writeLog(buf []byte) { c.logb.Write(buf) if c.logw != nil { c.logw.Write(buf) } } func hasStringOrError(x interface{}) (ok bool) { _, ok = x.(fmt.Stringer) if ok { return } _, ok = x.(error) return } func (c *C) logValue(label string, value interface{}) { if label == "" { if hasStringOrError(value) { c.logf("... %#v (%q)", value, value) } else { c.logf("... %#v", value) } } else if value == nil { c.logf("... %s = nil", label) } else { if hasStringOrError(value) { fv := fmt.Sprintf("%#v", value) qv := fmt.Sprintf("%q", value) if fv != qv { c.logf("... %s %s = %s (%s)", label, reflect.TypeOf(value), fv, qv) return } } if s, ok := value.(string); ok && isMultiLine(s) { c.logf(`... %s %s = "" +`, label, reflect.TypeOf(value)) c.logMultiLine(s) } else { c.logf("... %s %s = %#v", label, reflect.TypeOf(value), value) } } } func (c *C) logMultiLine(s string) { b := make([]byte, 0, len(s)*2) i := 0 n := len(s) for i < n { j := i + 1 for j < n && s[j-1] != '\n' { j++ } b = append(b, "... "...) b = strconv.AppendQuote(b, s[i:j]) if j < n { b = append(b, " +"...) } b = append(b, '\n') i = j } c.writeLog(b) } func isMultiLine(s string) bool { for i := 0; i+1 < len(s); i++ { if s[i] == '\n' { return true } } return false } func (c *C) logString(issue string) { c.log("... ", issue) } func (c *C) logCaller(skip int) { // This is a bit heavier than it ought to be. skip += 1 // Our own frame. pc, callerFile, callerLine, ok := runtime.Caller(skip) if !ok { return } var testFile string var testLine int testFunc := runtime.FuncForPC(c.method.PC()) if runtime.FuncForPC(pc) != testFunc { for { skip += 1 if pc, file, line, ok := runtime.Caller(skip); ok { // Note that the test line may be different on // distinct calls for the same test. Showing // the "internal" line is helpful when debugging. if runtime.FuncForPC(pc) == testFunc { testFile, testLine = file, line break } } else { break } } } if testFile != "" && (testFile != callerFile || testLine != callerLine) { c.logCode(testFile, testLine) } c.logCode(callerFile, callerLine) } func (c *C) logCode(path string, line int) { c.logf("%s:%d:", nicePath(path), line) code, err := printLine(path, line) if code == "" { code = "..." // XXX Open the file and take the raw line. if err != nil { code += err.Error() } } c.log(indent(code, " ")) } var valueGo = filepath.Join("reflect", "value.go") var asmGo = filepath.Join("runtime", "asm_") func (c *C) logPanic(skip int, value interface{}) { skip++ // Our own frame. initialSkip := skip for ; ; skip++ { if pc, file, line, ok := runtime.Caller(skip); ok { if skip == initialSkip { c.logf("... Panic: %s (PC=0x%X)\n", value, pc) } name := niceFuncName(pc) path := nicePath(file) if strings.Contains(path, "/gopkg.in/check.v") { continue } if name == "Value.call" && strings.HasSuffix(path, valueGo) { continue } if (name == "call16" || name == "call32") && strings.Contains(path, asmGo) { continue } c.logf("%s:%d\n in %s", nicePath(file), line, name) } else { break } } } func (c *C) logSoftPanic(issue string) { c.log("... Panic: ", issue) } func (c *C) logArgPanic(method *methodType, expectedType string) { c.logf("... Panic: %s argument should be %s", niceFuncName(method.PC()), expectedType) } // ----------------------------------------------------------------------- // Some simple formatting helpers. var initWD, initWDErr = os.Getwd() func init() { if initWDErr == nil { initWD = strings.Replace(initWD, "\\", "/", -1) + "/" } } func nicePath(path string) string { if initWDErr == nil { if strings.HasPrefix(path, initWD) { return path[len(initWD):] } } return path } func niceFuncPath(pc uintptr) string { function := runtime.FuncForPC(pc) if function != nil { filename, line := function.FileLine(pc) return fmt.Sprintf("%s:%d", nicePath(filename), line) } return "" } func niceFuncName(pc uintptr) string { function := runtime.FuncForPC(pc) if function != nil { name := path.Base(function.Name()) if i := strings.Index(name, "."); i > 0 { name = name[i+1:] } if strings.HasPrefix(name, "(*") { if i := strings.Index(name, ")"); i > 0 { name = name[2:i] + name[i+1:] } } if i := strings.LastIndex(name, ".*"); i != -1 { name = name[:i] + "." + name[i+2:] } if i := strings.LastIndex(name, "·"); i != -1 { name = name[:i] + "." + name[i+2:] } return name } return "" } // ----------------------------------------------------------------------- // Result tracker to aggregate call results. type Result struct { Succeeded int Failed int Skipped int Panicked int FixturePanicked int ExpectedFailures int Missed int // Not even tried to run, related to a panic in the fixture. RunError error // Houston, we've got a problem. WorkDir string // If KeepWorkDir is true } type resultTracker struct { result Result _lastWasProblem bool _waiting int _missed int _expectChan chan *C _doneChan chan *C _stopChan chan bool } func newResultTracker() *resultTracker { return &resultTracker{_expectChan: make(chan *C), // Synchronous _doneChan: make(chan *C, 32), // Asynchronous _stopChan: make(chan bool)} // Synchronous } func (tracker *resultTracker) start() { go tracker._loopRoutine() } func (tracker *resultTracker) waitAndStop() { <-tracker._stopChan } func (tracker *resultTracker) expectCall(c *C) { tracker._expectChan <- c } func (tracker *resultTracker) callDone(c *C) { tracker._doneChan <- c } func (tracker *resultTracker) _loopRoutine() { for { var c *C if tracker._waiting > 0 { // Calls still running. Can't stop. select { // XXX Reindent this (not now to make diff clear) case c = <-tracker._expectChan: tracker._waiting += 1 case c = <-tracker._doneChan: tracker._waiting -= 1 switch c.status() { case succeededSt: if c.kind == testKd { if c.mustFail { tracker.result.ExpectedFailures++ } else { tracker.result.Succeeded++ } } case failedSt: tracker.result.Failed++ case panickedSt: if c.kind == fixtureKd { tracker.result.FixturePanicked++ } else { tracker.result.Panicked++ } case fixturePanickedSt: // Track it as missed, since the panic // was on the fixture, not on the test. tracker.result.Missed++ case missedSt: tracker.result.Missed++ case skippedSt: if c.kind == testKd { tracker.result.Skipped++ } } } } else { // No calls. Can stop, but no done calls here. select { case tracker._stopChan <- true: return case c = <-tracker._expectChan: tracker._waiting += 1 case c = <-tracker._doneChan: panic("Tracker got an unexpected done call.") } } } } // ----------------------------------------------------------------------- // The underlying suite runner. type suiteRunner struct { suite interface{} setUpSuite, tearDownSuite *methodType setUpTest, tearDownTest *methodType tests []*methodType tracker *resultTracker tempDir *tempDir keepDir bool output *outputWriter reportedProblemLast bool benchTime time.Duration benchMem bool } type RunConf struct { Output io.Writer Stream bool Verbose bool Filter string Benchmark bool BenchmarkTime time.Duration // Defaults to 1 second BenchmarkMem bool KeepWorkDir bool } // Create a new suiteRunner able to run all methods in the given suite. func newSuiteRunner(suite interface{}, runConf *RunConf) *suiteRunner { var conf RunConf if runConf != nil { conf = *runConf } if conf.Output == nil { conf.Output = os.Stdout } if conf.Benchmark { conf.Verbose = true } suiteType := reflect.TypeOf(suite) suiteNumMethods := suiteType.NumMethod() suiteValue := reflect.ValueOf(suite) runner := &suiteRunner{ suite: suite, output: newOutputWriter(conf.Output, conf.Stream, conf.Verbose), tracker: newResultTracker(), benchTime: conf.BenchmarkTime, benchMem: conf.BenchmarkMem, tempDir: &tempDir{}, keepDir: conf.KeepWorkDir, tests: make([]*methodType, 0, suiteNumMethods), } if runner.benchTime == 0 { runner.benchTime = 1 * time.Second } var filterRegexp *regexp.Regexp if conf.Filter != "" { if regexp, err := regexp.Compile(conf.Filter); err != nil { msg := "Bad filter expression: " + err.Error() runner.tracker.result.RunError = errors.New(msg) return runner } else { filterRegexp = regexp } } for i := 0; i != suiteNumMethods; i++ { method := newMethod(suiteValue, i) switch method.Info.Name { case "SetUpSuite": runner.setUpSuite = method case "TearDownSuite": runner.tearDownSuite = method case "SetUpTest": runner.setUpTest = method case "TearDownTest": runner.tearDownTest = method default: prefix := "Test" if conf.Benchmark { prefix = "Benchmark" } if !strings.HasPrefix(method.Info.Name, prefix) { continue } if filterRegexp == nil || method.matches(filterRegexp) { runner.tests = append(runner.tests, method) } } } return runner } // Run all methods in the given suite. func (runner *suiteRunner) run() *Result { if runner.tracker.result.RunError == nil && len(runner.tests) > 0 { runner.tracker.start() if runner.checkFixtureArgs() { c := runner.runFixture(runner.setUpSuite, "", nil) if c == nil || c.status() == succeededSt { for i := 0; i != len(runner.tests); i++ { c := runner.runTest(runner.tests[i]) if c.status() == fixturePanickedSt { runner.skipTests(missedSt, runner.tests[i+1:]) break } } } else if c != nil && c.status() == skippedSt { runner.skipTests(skippedSt, runner.tests) } else { runner.skipTests(missedSt, runner.tests) } runner.runFixture(runner.tearDownSuite, "", nil) } else { runner.skipTests(missedSt, runner.tests) } runner.tracker.waitAndStop() if runner.keepDir { runner.tracker.result.WorkDir = runner.tempDir.path } else { runner.tempDir.removeAll() } } return &runner.tracker.result } // Create a call object with the given suite method, and fork a // goroutine with the provided dispatcher for running it. func (runner *suiteRunner) forkCall(method *methodType, kind funcKind, testName string, logb *logger, dispatcher func(c *C)) *C { var logw io.Writer if runner.output.Stream { logw = runner.output } if logb == nil { logb = new(logger) } c := &C{ method: method, kind: kind, testName: testName, logb: logb, logw: logw, tempDir: runner.tempDir, done: make(chan *C, 1), timer: timer{benchTime: runner.benchTime}, startTime: time.Now(), benchMem: runner.benchMem, } runner.tracker.expectCall(c) go (func() { runner.reportCallStarted(c) defer runner.callDone(c) dispatcher(c) })() return c } // Same as forkCall(), but wait for call to finish before returning. func (runner *suiteRunner) runFunc(method *methodType, kind funcKind, testName string, logb *logger, dispatcher func(c *C)) *C { c := runner.forkCall(method, kind, testName, logb, dispatcher) <-c.done return c } // Handle a finished call. If there were any panics, update the call status // accordingly. Then, mark the call as done and report to the tracker. func (runner *suiteRunner) callDone(c *C) { value := recover() if value != nil { switch v := value.(type) { case *fixturePanic: if v.status == skippedSt { c.setStatus(skippedSt) } else { c.logSoftPanic("Fixture has panicked (see related PANIC)") c.setStatus(fixturePanickedSt) } default: c.logPanic(1, value) c.setStatus(panickedSt) } } if c.mustFail { switch c.status() { case failedSt: c.setStatus(succeededSt) case succeededSt: c.setStatus(failedSt) c.logString("Error: Test succeeded, but was expected to fail") c.logString("Reason: " + c.reason) } } runner.reportCallDone(c) c.done <- c } // Runs a fixture call synchronously. The fixture will still be run in a // goroutine like all suite methods, but this method will not return // while the fixture goroutine is not done, because the fixture must be // run in a desired order. func (runner *suiteRunner) runFixture(method *methodType, testName string, logb *logger) *C { if method != nil { c := runner.runFunc(method, fixtureKd, testName, logb, func(c *C) { c.ResetTimer() c.StartTimer() defer c.StopTimer() c.method.Call([]reflect.Value{reflect.ValueOf(c)}) }) return c } return nil } // Run the fixture method with runFixture(), but panic with a fixturePanic{} // in case the fixture method panics. This makes it easier to track the // fixture panic together with other call panics within forkTest(). func (runner *suiteRunner) runFixtureWithPanic(method *methodType, testName string, logb *logger, skipped *bool) *C { if skipped != nil && *skipped { return nil } c := runner.runFixture(method, testName, logb) if c != nil && c.status() != succeededSt { if skipped != nil { *skipped = c.status() == skippedSt } panic(&fixturePanic{c.status(), method}) } return c } type fixturePanic struct { status funcStatus method *methodType } // Run the suite test method, together with the test-specific fixture, // asynchronously. func (runner *suiteRunner) forkTest(method *methodType) *C { testName := method.String() return runner.forkCall(method, testKd, testName, nil, func(c *C) { var skipped bool defer runner.runFixtureWithPanic(runner.tearDownTest, testName, nil, &skipped) defer c.StopTimer() benchN := 1 for { runner.runFixtureWithPanic(runner.setUpTest, testName, c.logb, &skipped) mt := c.method.Type() if mt.NumIn() != 1 || mt.In(0) != reflect.TypeOf(c) { // Rather than a plain panic, provide a more helpful message when // the argument type is incorrect. c.setStatus(panickedSt) c.logArgPanic(c.method, "*check.C") return } if strings.HasPrefix(c.method.Info.Name, "Test") { c.ResetTimer() c.StartTimer() c.method.Call([]reflect.Value{reflect.ValueOf(c)}) return } if !strings.HasPrefix(c.method.Info.Name, "Benchmark") { panic("unexpected method prefix: " + c.method.Info.Name) } runtime.GC() c.N = benchN c.ResetTimer() c.StartTimer() c.method.Call([]reflect.Value{reflect.ValueOf(c)}) c.StopTimer() if c.status() != succeededSt || c.duration >= c.benchTime || benchN >= 1e9 { return } perOpN := int(1e9) if c.nsPerOp() != 0 { perOpN = int(c.benchTime.Nanoseconds() / c.nsPerOp()) } // Logic taken from the stock testing package: // - Run more iterations than we think we'll need for a second (1.5x). // - Don't grow too fast in case we had timing errors previously. // - Be sure to run at least one more than last time. benchN = max(min(perOpN+perOpN/2, 100*benchN), benchN+1) benchN = roundUp(benchN) skipped = true // Don't run the deferred one if this panics. runner.runFixtureWithPanic(runner.tearDownTest, testName, nil, nil) skipped = false } }) } // Same as forkTest(), but wait for the test to finish before returning. func (runner *suiteRunner) runTest(method *methodType) *C { c := runner.forkTest(method) <-c.done return c } // Helper to mark tests as skipped or missed. A bit heavy for what // it does, but it enables homogeneous handling of tracking, including // nice verbose output. func (runner *suiteRunner) skipTests(status funcStatus, methods []*methodType) { for _, method := range methods { runner.runFunc(method, testKd, "", nil, func(c *C) { c.setStatus(status) }) } } // Verify if the fixture arguments are *check.C. In case of errors, // log the error as a panic in the fixture method call, and return false. func (runner *suiteRunner) checkFixtureArgs() bool { succeeded := true argType := reflect.TypeOf(&C{}) for _, method := range []*methodType{runner.setUpSuite, runner.tearDownSuite, runner.setUpTest, runner.tearDownTest} { if method != nil { mt := method.Type() if mt.NumIn() != 1 || mt.In(0) != argType { succeeded = false runner.runFunc(method, fixtureKd, "", nil, func(c *C) { c.logArgPanic(method, "*check.C") c.setStatus(panickedSt) }) } } } return succeeded } func (runner *suiteRunner) reportCallStarted(c *C) { runner.output.WriteCallStarted("START", c) } func (runner *suiteRunner) reportCallDone(c *C) { runner.tracker.callDone(c) switch c.status() { case succeededSt: if c.mustFail { runner.output.WriteCallSuccess("FAIL EXPECTED", c) } else { runner.output.WriteCallSuccess("PASS", c) } case skippedSt: runner.output.WriteCallSuccess("SKIP", c) case failedSt: runner.output.WriteCallProblem("FAIL", c) case panickedSt: runner.output.WriteCallProblem("PANIC", c) case fixturePanickedSt: // That's a testKd call reporting that its fixture // has panicked. The fixture call which caused the // panic itself was tracked above. We'll report to // aid debugging. runner.output.WriteCallProblem("PANIC", c) case missedSt: runner.output.WriteCallSuccess("MISS", c) } } // ----------------------------------------------------------------------- // Output writer manages atomic output writing according to settings. type outputWriter struct { m sync.Mutex writer io.Writer wroteCallProblemLast bool Stream bool Verbose bool } func newOutputWriter(writer io.Writer, stream, verbose bool) *outputWriter { return &outputWriter{writer: writer, Stream: stream, Verbose: verbose} } func (ow *outputWriter) Write(content []byte) (n int, err error) { ow.m.Lock() n, err = ow.writer.Write(content) ow.m.Unlock() return } func (ow *outputWriter) WriteCallStarted(label string, c *C) { if ow.Stream { header := renderCallHeader(label, c, "", "\n") ow.m.Lock() ow.writer.Write([]byte(header)) ow.m.Unlock() } } func (ow *outputWriter) WriteCallProblem(label string, c *C) { var prefix string if !ow.Stream { prefix = "\n-----------------------------------" + "-----------------------------------\n" } header := renderCallHeader(label, c, prefix, "\n\n") ow.m.Lock() ow.wroteCallProblemLast = true ow.writer.Write([]byte(header)) if !ow.Stream { c.logb.WriteTo(ow.writer) } ow.m.Unlock() } func (ow *outputWriter) WriteCallSuccess(label string, c *C) { if ow.Stream || (ow.Verbose && c.kind == testKd) { // TODO Use a buffer here. var suffix string if c.reason != "" { suffix = " (" + c.reason + ")" } if c.status() == succeededSt { suffix += "\t" + c.timerString() } suffix += "\n" if ow.Stream { suffix += "\n" } header := renderCallHeader(label, c, "", suffix) ow.m.Lock() // Resist temptation of using line as prefix above due to race. if !ow.Stream && ow.wroteCallProblemLast { header = "\n-----------------------------------" + "-----------------------------------\n" + header } ow.wroteCallProblemLast = false ow.writer.Write([]byte(header)) ow.m.Unlock() } } func renderCallHeader(label string, c *C, prefix, suffix string) string { pc := c.method.PC() return fmt.Sprintf("%s%s: %s: %s%s", prefix, label, niceFuncPath(pc), niceFuncName(pc), suffix) } go-gir-generator-master/vendor/src/gopkg.in/check.v1/check_test.go000066400000000000000000000120601414263242200253630ustar00rootroot00000000000000// This file contains just a few generic helpers which are used by the // other test files. package check_test import ( "flag" "fmt" "os" "regexp" "runtime" "testing" "time" "gopkg.in/check.v1" ) // We count the number of suites run at least to get a vague hint that the // test suite is behaving as it should. Otherwise a bug introduced at the // very core of the system could go unperceived. const suitesRunExpected = 8 var suitesRun int = 0 func Test(t *testing.T) { check.TestingT(t) if suitesRun != suitesRunExpected && flag.Lookup("check.f").Value.String() == "" { critical(fmt.Sprintf("Expected %d suites to run rather than %d", suitesRunExpected, suitesRun)) } } // ----------------------------------------------------------------------- // Helper functions. // Break down badly. This is used in test cases which can't yet assume // that the fundamental bits are working. func critical(error string) { fmt.Fprintln(os.Stderr, "CRITICAL: "+error) os.Exit(1) } // Return the file line where it's called. func getMyLine() int { if _, _, line, ok := runtime.Caller(1); ok { return line } return -1 } // ----------------------------------------------------------------------- // Helper type implementing a basic io.Writer for testing output. // Type implementing the io.Writer interface for analyzing output. type String struct { value string } // The only function required by the io.Writer interface. Will append // written data to the String.value string. func (s *String) Write(p []byte) (n int, err error) { s.value += string(p) return len(p), nil } // Trivial wrapper to test errors happening on a different file // than the test itself. func checkEqualWrapper(c *check.C, obtained, expected interface{}) (result bool, line int) { return c.Check(obtained, check.Equals, expected), getMyLine() } // ----------------------------------------------------------------------- // Helper suite for testing basic fail behavior. type FailHelper struct { testLine int } func (s *FailHelper) TestLogAndFail(c *check.C) { s.testLine = getMyLine() - 1 c.Log("Expected failure!") c.Fail() } // ----------------------------------------------------------------------- // Helper suite for testing basic success behavior. type SuccessHelper struct{} func (s *SuccessHelper) TestLogAndSucceed(c *check.C) { c.Log("Expected success!") } // ----------------------------------------------------------------------- // Helper suite for testing ordering and behavior of fixture. type FixtureHelper struct { calls []string panicOn string skip bool skipOnN int sleepOn string sleep time.Duration bytes int64 } func (s *FixtureHelper) trace(name string, c *check.C) { s.calls = append(s.calls, name) if name == s.panicOn { panic(name) } if s.sleep > 0 && s.sleepOn == name { time.Sleep(s.sleep) } if s.skip && s.skipOnN == len(s.calls)-1 { c.Skip("skipOnN == n") } } func (s *FixtureHelper) SetUpSuite(c *check.C) { s.trace("SetUpSuite", c) } func (s *FixtureHelper) TearDownSuite(c *check.C) { s.trace("TearDownSuite", c) } func (s *FixtureHelper) SetUpTest(c *check.C) { s.trace("SetUpTest", c) } func (s *FixtureHelper) TearDownTest(c *check.C) { s.trace("TearDownTest", c) } func (s *FixtureHelper) Test1(c *check.C) { s.trace("Test1", c) } func (s *FixtureHelper) Test2(c *check.C) { s.trace("Test2", c) } func (s *FixtureHelper) Benchmark1(c *check.C) { s.trace("Benchmark1", c) for i := 0; i < c.N; i++ { time.Sleep(s.sleep) } } func (s *FixtureHelper) Benchmark2(c *check.C) { s.trace("Benchmark2", c) c.SetBytes(1024) for i := 0; i < c.N; i++ { time.Sleep(s.sleep) } } func (s *FixtureHelper) Benchmark3(c *check.C) { var x []int64 s.trace("Benchmark3", c) for i := 0; i < c.N; i++ { time.Sleep(s.sleep) x = make([]int64, 5) _ = x } } // ----------------------------------------------------------------------- // Helper which checks the state of the test and ensures that it matches // the given expectations. Depends on c.Errorf() working, so shouldn't // be used to test this one function. type expectedState struct { name string result interface{} failed bool log string } // Verify the state of the test. Note that since this also verifies if // the test is supposed to be in a failed state, no other checks should // be done in addition to what is being tested. func checkState(c *check.C, result interface{}, expected *expectedState) { failed := c.Failed() c.Succeed() log := c.GetTestLog() matched, matchError := regexp.MatchString("^"+expected.log+"$", log) if matchError != nil { c.Errorf("Error in matching expression used in testing %s", expected.name) } else if !matched { c.Errorf("%s logged:\n----------\n%s----------\n\nExpected:\n----------\n%s\n----------", expected.name, log, expected.log) } if result != expected.result { c.Errorf("%s returned %#v rather than %#v", expected.name, result, expected.result) } if failed != expected.failed { if failed { c.Errorf("%s has failed when it shouldn't", expected.name) } else { c.Errorf("%s has not failed when it should", expected.name) } } } go-gir-generator-master/vendor/src/gopkg.in/check.v1/checkers.go000066400000000000000000000303371414263242200250450ustar00rootroot00000000000000package check import ( "fmt" "reflect" "regexp" ) // ----------------------------------------------------------------------- // CommentInterface and Commentf helper, to attach extra information to checks. type comment struct { format string args []interface{} } // Commentf returns an infomational value to use with Assert or Check calls. // If the checker test fails, the provided arguments will be passed to // fmt.Sprintf, and will be presented next to the logged failure. // // For example: // // c.Assert(v, Equals, 42, Commentf("Iteration #%d failed.", i)) // // Note that if the comment is constant, a better option is to // simply use a normal comment right above or next to the line, as // it will also get printed with any errors: // // c.Assert(l, Equals, 8192) // Ensure buffer size is correct (bug #123) // func Commentf(format string, args ...interface{}) CommentInterface { return &comment{format, args} } // CommentInterface must be implemented by types that attach extra // information to failed checks. See the Commentf function for details. type CommentInterface interface { CheckCommentString() string } func (c *comment) CheckCommentString() string { return fmt.Sprintf(c.format, c.args...) } // ----------------------------------------------------------------------- // The Checker interface. // The Checker interface must be provided by checkers used with // the Assert and Check verification methods. type Checker interface { Info() *CheckerInfo Check(params []interface{}, names []string) (result bool, error string) } // See the Checker interface. type CheckerInfo struct { Name string Params []string } func (info *CheckerInfo) Info() *CheckerInfo { return info } // ----------------------------------------------------------------------- // Not checker logic inverter. // The Not checker inverts the logic of the provided checker. The // resulting checker will succeed where the original one failed, and // vice-versa. // // For example: // // c.Assert(a, Not(Equals), b) // func Not(checker Checker) Checker { return ¬Checker{checker} } type notChecker struct { sub Checker } func (checker *notChecker) Info() *CheckerInfo { info := *checker.sub.Info() info.Name = "Not(" + info.Name + ")" return &info } func (checker *notChecker) Check(params []interface{}, names []string) (result bool, error string) { result, error = checker.sub.Check(params, names) result = !result return } // ----------------------------------------------------------------------- // IsNil checker. type isNilChecker struct { *CheckerInfo } // The IsNil checker tests whether the obtained value is nil. // // For example: // // c.Assert(err, IsNil) // var IsNil Checker = &isNilChecker{ &CheckerInfo{Name: "IsNil", Params: []string{"value"}}, } func (checker *isNilChecker) Check(params []interface{}, names []string) (result bool, error string) { return isNil(params[0]), "" } func isNil(obtained interface{}) (result bool) { if obtained == nil { result = true } else { switch v := reflect.ValueOf(obtained); v.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return v.IsNil() } } return } // ----------------------------------------------------------------------- // NotNil checker. Alias for Not(IsNil), since it's so common. type notNilChecker struct { *CheckerInfo } // The NotNil checker verifies that the obtained value is not nil. // // For example: // // c.Assert(iface, NotNil) // // This is an alias for Not(IsNil), made available since it's a // fairly common check. // var NotNil Checker = ¬NilChecker{ &CheckerInfo{Name: "NotNil", Params: []string{"value"}}, } func (checker *notNilChecker) Check(params []interface{}, names []string) (result bool, error string) { return !isNil(params[0]), "" } // ----------------------------------------------------------------------- // Equals checker. type equalsChecker struct { *CheckerInfo } // The Equals checker verifies that the obtained value is equal to // the expected value, according to usual Go semantics for ==. // // For example: // // c.Assert(value, Equals, 42) // var Equals Checker = &equalsChecker{ &CheckerInfo{Name: "Equals", Params: []string{"obtained", "expected"}}, } func (checker *equalsChecker) Check(params []interface{}, names []string) (result bool, error string) { defer func() { if v := recover(); v != nil { result = false error = fmt.Sprint(v) } }() return params[0] == params[1], "" } // ----------------------------------------------------------------------- // DeepEquals checker. type deepEqualsChecker struct { *CheckerInfo } // The DeepEquals checker verifies that the obtained value is deep-equal to // the expected value. The check will work correctly even when facing // slices, interfaces, and values of different types (which always fail // the test). // // For example: // // c.Assert(value, DeepEquals, 42) // c.Assert(array, DeepEquals, []string{"hi", "there"}) // var DeepEquals Checker = &deepEqualsChecker{ &CheckerInfo{Name: "DeepEquals", Params: []string{"obtained", "expected"}}, } func (checker *deepEqualsChecker) Check(params []interface{}, names []string) (result bool, error string) { return reflect.DeepEqual(params[0], params[1]), "" } // ----------------------------------------------------------------------- // HasLen checker. type hasLenChecker struct { *CheckerInfo } // The HasLen checker verifies that the obtained value has the // provided length. In many cases this is superior to using Equals // in conjuction with the len function because in case the check // fails the value itself will be printed, instead of its length, // providing more details for figuring the problem. // // For example: // // c.Assert(list, HasLen, 5) // var HasLen Checker = &hasLenChecker{ &CheckerInfo{Name: "HasLen", Params: []string{"obtained", "n"}}, } func (checker *hasLenChecker) Check(params []interface{}, names []string) (result bool, error string) { n, ok := params[1].(int) if !ok { return false, "n must be an int" } value := reflect.ValueOf(params[0]) switch value.Kind() { case reflect.Map, reflect.Array, reflect.Slice, reflect.Chan, reflect.String: default: return false, "obtained value type has no length" } return value.Len() == n, "" } // ----------------------------------------------------------------------- // ErrorMatches checker. type errorMatchesChecker struct { *CheckerInfo } // The ErrorMatches checker verifies that the error value // is non nil and matches the regular expression provided. // // For example: // // c.Assert(err, ErrorMatches, "perm.*denied") // var ErrorMatches Checker = errorMatchesChecker{ &CheckerInfo{Name: "ErrorMatches", Params: []string{"value", "regex"}}, } func (checker errorMatchesChecker) Check(params []interface{}, names []string) (result bool, errStr string) { if params[0] == nil { return false, "Error value is nil" } err, ok := params[0].(error) if !ok { return false, "Value is not an error" } params[0] = err.Error() names[0] = "error" return matches(params[0], params[1]) } // ----------------------------------------------------------------------- // Matches checker. type matchesChecker struct { *CheckerInfo } // The Matches checker verifies that the string provided as the obtained // value (or the string resulting from obtained.String()) matches the // regular expression provided. // // For example: // // c.Assert(err, Matches, "perm.*denied") // var Matches Checker = &matchesChecker{ &CheckerInfo{Name: "Matches", Params: []string{"value", "regex"}}, } func (checker *matchesChecker) Check(params []interface{}, names []string) (result bool, error string) { return matches(params[0], params[1]) } func matches(value, regex interface{}) (result bool, error string) { reStr, ok := regex.(string) if !ok { return false, "Regex must be a string" } valueStr, valueIsStr := value.(string) if !valueIsStr { if valueWithStr, valueHasStr := value.(fmt.Stringer); valueHasStr { valueStr, valueIsStr = valueWithStr.String(), true } } if valueIsStr { matches, err := regexp.MatchString("^"+reStr+"$", valueStr) if err != nil { return false, "Can't compile regex: " + err.Error() } return matches, "" } return false, "Obtained value is not a string and has no .String()" } // ----------------------------------------------------------------------- // Panics checker. type panicsChecker struct { *CheckerInfo } // The Panics checker verifies that calling the provided zero-argument // function will cause a panic which is deep-equal to the provided value. // // For example: // // c.Assert(func() { f(1, 2) }, Panics, &SomeErrorType{"BOOM"}). // // var Panics Checker = &panicsChecker{ &CheckerInfo{Name: "Panics", Params: []string{"function", "expected"}}, } func (checker *panicsChecker) Check(params []interface{}, names []string) (result bool, error string) { f := reflect.ValueOf(params[0]) if f.Kind() != reflect.Func || f.Type().NumIn() != 0 { return false, "Function must take zero arguments" } defer func() { // If the function has not panicked, then don't do the check. if error != "" { return } params[0] = recover() names[0] = "panic" result = reflect.DeepEqual(params[0], params[1]) }() f.Call(nil) return false, "Function has not panicked" } type panicMatchesChecker struct { *CheckerInfo } // The PanicMatches checker verifies that calling the provided zero-argument // function will cause a panic with an error value matching // the regular expression provided. // // For example: // // c.Assert(func() { f(1, 2) }, PanicMatches, `open.*: no such file or directory`). // // var PanicMatches Checker = &panicMatchesChecker{ &CheckerInfo{Name: "PanicMatches", Params: []string{"function", "expected"}}, } func (checker *panicMatchesChecker) Check(params []interface{}, names []string) (result bool, errmsg string) { f := reflect.ValueOf(params[0]) if f.Kind() != reflect.Func || f.Type().NumIn() != 0 { return false, "Function must take zero arguments" } defer func() { // If the function has not panicked, then don't do the check. if errmsg != "" { return } obtained := recover() names[0] = "panic" if e, ok := obtained.(error); ok { params[0] = e.Error() } else if _, ok := obtained.(string); ok { params[0] = obtained } else { errmsg = "Panic value is not a string or an error" return } result, errmsg = matches(params[0], params[1]) }() f.Call(nil) return false, "Function has not panicked" } // ----------------------------------------------------------------------- // FitsTypeOf checker. type fitsTypeChecker struct { *CheckerInfo } // The FitsTypeOf checker verifies that the obtained value is // assignable to a variable with the same type as the provided // sample value. // // For example: // // c.Assert(value, FitsTypeOf, int64(0)) // c.Assert(value, FitsTypeOf, os.Error(nil)) // var FitsTypeOf Checker = &fitsTypeChecker{ &CheckerInfo{Name: "FitsTypeOf", Params: []string{"obtained", "sample"}}, } func (checker *fitsTypeChecker) Check(params []interface{}, names []string) (result bool, error string) { obtained := reflect.ValueOf(params[0]) sample := reflect.ValueOf(params[1]) if !obtained.IsValid() { return false, "" } if !sample.IsValid() { return false, "Invalid sample value" } return obtained.Type().AssignableTo(sample.Type()), "" } // ----------------------------------------------------------------------- // Implements checker. type implementsChecker struct { *CheckerInfo } // The Implements checker verifies that the obtained value // implements the interface specified via a pointer to an interface // variable. // // For example: // // var e os.Error // c.Assert(err, Implements, &e) // var Implements Checker = &implementsChecker{ &CheckerInfo{Name: "Implements", Params: []string{"obtained", "ifaceptr"}}, } func (checker *implementsChecker) Check(params []interface{}, names []string) (result bool, error string) { obtained := reflect.ValueOf(params[0]) ifaceptr := reflect.ValueOf(params[1]) if !obtained.IsValid() { return false, "" } if !ifaceptr.IsValid() || ifaceptr.Kind() != reflect.Ptr || ifaceptr.Elem().Kind() != reflect.Interface { return false, "ifaceptr should be a pointer to an interface variable" } return obtained.Type().Implements(ifaceptr.Elem().Type()), "" } go-gir-generator-master/vendor/src/gopkg.in/check.v1/checkers_test.go000066400000000000000000000240701414263242200261010ustar00rootroot00000000000000package check_test import ( "errors" "gopkg.in/check.v1" "reflect" "runtime" ) type CheckersS struct{} var _ = check.Suite(&CheckersS{}) func testInfo(c *check.C, checker check.Checker, name string, paramNames []string) { info := checker.Info() if info.Name != name { c.Fatalf("Got name %s, expected %s", info.Name, name) } if !reflect.DeepEqual(info.Params, paramNames) { c.Fatalf("Got param names %#v, expected %#v", info.Params, paramNames) } } func testCheck(c *check.C, checker check.Checker, result bool, error string, params ...interface{}) ([]interface{}, []string) { info := checker.Info() if len(params) != len(info.Params) { c.Fatalf("unexpected param count in test; expected %d got %d", len(info.Params), len(params)) } names := append([]string{}, info.Params...) result_, error_ := checker.Check(params, names) if result_ != result || error_ != error { c.Fatalf("%s.Check(%#v) returned (%#v, %#v) rather than (%#v, %#v)", info.Name, params, result_, error_, result, error) } return params, names } func (s *CheckersS) TestComment(c *check.C) { bug := check.Commentf("a %d bc", 42) comment := bug.CheckCommentString() if comment != "a 42 bc" { c.Fatalf("Commentf returned %#v", comment) } } func (s *CheckersS) TestIsNil(c *check.C) { testInfo(c, check.IsNil, "IsNil", []string{"value"}) testCheck(c, check.IsNil, true, "", nil) testCheck(c, check.IsNil, false, "", "a") testCheck(c, check.IsNil, true, "", (chan int)(nil)) testCheck(c, check.IsNil, false, "", make(chan int)) testCheck(c, check.IsNil, true, "", (error)(nil)) testCheck(c, check.IsNil, false, "", errors.New("")) testCheck(c, check.IsNil, true, "", ([]int)(nil)) testCheck(c, check.IsNil, false, "", make([]int, 1)) testCheck(c, check.IsNil, false, "", int(0)) } func (s *CheckersS) TestNotNil(c *check.C) { testInfo(c, check.NotNil, "NotNil", []string{"value"}) testCheck(c, check.NotNil, false, "", nil) testCheck(c, check.NotNil, true, "", "a") testCheck(c, check.NotNil, false, "", (chan int)(nil)) testCheck(c, check.NotNil, true, "", make(chan int)) testCheck(c, check.NotNil, false, "", (error)(nil)) testCheck(c, check.NotNil, true, "", errors.New("")) testCheck(c, check.NotNil, false, "", ([]int)(nil)) testCheck(c, check.NotNil, true, "", make([]int, 1)) } func (s *CheckersS) TestNot(c *check.C) { testInfo(c, check.Not(check.IsNil), "Not(IsNil)", []string{"value"}) testCheck(c, check.Not(check.IsNil), false, "", nil) testCheck(c, check.Not(check.IsNil), true, "", "a") } type simpleStruct struct { i int } func (s *CheckersS) TestEquals(c *check.C) { testInfo(c, check.Equals, "Equals", []string{"obtained", "expected"}) // The simplest. testCheck(c, check.Equals, true, "", 42, 42) testCheck(c, check.Equals, false, "", 42, 43) // Different native types. testCheck(c, check.Equals, false, "", int32(42), int64(42)) // With nil. testCheck(c, check.Equals, false, "", 42, nil) // Slices testCheck(c, check.Equals, false, "runtime error: comparing uncomparable type []uint8", []byte{1, 2}, []byte{1, 2}) // Struct values testCheck(c, check.Equals, true, "", simpleStruct{1}, simpleStruct{1}) testCheck(c, check.Equals, false, "", simpleStruct{1}, simpleStruct{2}) // Struct pointers testCheck(c, check.Equals, false, "", &simpleStruct{1}, &simpleStruct{1}) testCheck(c, check.Equals, false, "", &simpleStruct{1}, &simpleStruct{2}) } func (s *CheckersS) TestDeepEquals(c *check.C) { testInfo(c, check.DeepEquals, "DeepEquals", []string{"obtained", "expected"}) // The simplest. testCheck(c, check.DeepEquals, true, "", 42, 42) testCheck(c, check.DeepEquals, false, "", 42, 43) // Different native types. testCheck(c, check.DeepEquals, false, "", int32(42), int64(42)) // With nil. testCheck(c, check.DeepEquals, false, "", 42, nil) // Slices testCheck(c, check.DeepEquals, true, "", []byte{1, 2}, []byte{1, 2}) testCheck(c, check.DeepEquals, false, "", []byte{1, 2}, []byte{1, 3}) // Struct values testCheck(c, check.DeepEquals, true, "", simpleStruct{1}, simpleStruct{1}) testCheck(c, check.DeepEquals, false, "", simpleStruct{1}, simpleStruct{2}) // Struct pointers testCheck(c, check.DeepEquals, true, "", &simpleStruct{1}, &simpleStruct{1}) testCheck(c, check.DeepEquals, false, "", &simpleStruct{1}, &simpleStruct{2}) } func (s *CheckersS) TestHasLen(c *check.C) { testInfo(c, check.HasLen, "HasLen", []string{"obtained", "n"}) testCheck(c, check.HasLen, true, "", "abcd", 4) testCheck(c, check.HasLen, true, "", []int{1, 2}, 2) testCheck(c, check.HasLen, false, "", []int{1, 2}, 3) testCheck(c, check.HasLen, false, "n must be an int", []int{1, 2}, "2") testCheck(c, check.HasLen, false, "obtained value type has no length", nil, 2) } func (s *CheckersS) TestErrorMatches(c *check.C) { testInfo(c, check.ErrorMatches, "ErrorMatches", []string{"value", "regex"}) testCheck(c, check.ErrorMatches, false, "Error value is nil", nil, "some error") testCheck(c, check.ErrorMatches, false, "Value is not an error", 1, "some error") testCheck(c, check.ErrorMatches, true, "", errors.New("some error"), "some error") testCheck(c, check.ErrorMatches, true, "", errors.New("some error"), "so.*or") // Verify params mutation params, names := testCheck(c, check.ErrorMatches, false, "", errors.New("some error"), "other error") c.Assert(params[0], check.Equals, "some error") c.Assert(names[0], check.Equals, "error") } func (s *CheckersS) TestMatches(c *check.C) { testInfo(c, check.Matches, "Matches", []string{"value", "regex"}) // Simple matching testCheck(c, check.Matches, true, "", "abc", "abc") testCheck(c, check.Matches, true, "", "abc", "a.c") // Must match fully testCheck(c, check.Matches, false, "", "abc", "ab") testCheck(c, check.Matches, false, "", "abc", "bc") // String()-enabled values accepted testCheck(c, check.Matches, true, "", reflect.ValueOf("abc"), "a.c") testCheck(c, check.Matches, false, "", reflect.ValueOf("abc"), "a.d") // Some error conditions. testCheck(c, check.Matches, false, "Obtained value is not a string and has no .String()", 1, "a.c") testCheck(c, check.Matches, false, "Can't compile regex: error parsing regexp: missing closing ]: `[c$`", "abc", "a[c") } func (s *CheckersS) TestPanics(c *check.C) { testInfo(c, check.Panics, "Panics", []string{"function", "expected"}) // Some errors. testCheck(c, check.Panics, false, "Function has not panicked", func() bool { return false }, "BOOM") testCheck(c, check.Panics, false, "Function must take zero arguments", 1, "BOOM") // Plain strings. testCheck(c, check.Panics, true, "", func() { panic("BOOM") }, "BOOM") testCheck(c, check.Panics, false, "", func() { panic("KABOOM") }, "BOOM") testCheck(c, check.Panics, true, "", func() bool { panic("BOOM") }, "BOOM") // Error values. testCheck(c, check.Panics, true, "", func() { panic(errors.New("BOOM")) }, errors.New("BOOM")) testCheck(c, check.Panics, false, "", func() { panic(errors.New("KABOOM")) }, errors.New("BOOM")) type deep struct{ i int } // Deep value testCheck(c, check.Panics, true, "", func() { panic(&deep{99}) }, &deep{99}) // Verify params/names mutation params, names := testCheck(c, check.Panics, false, "", func() { panic(errors.New("KABOOM")) }, errors.New("BOOM")) c.Assert(params[0], check.ErrorMatches, "KABOOM") c.Assert(names[0], check.Equals, "panic") // Verify a nil panic testCheck(c, check.Panics, true, "", func() { panic(nil) }, nil) testCheck(c, check.Panics, false, "", func() { panic(nil) }, "NOPE") } func (s *CheckersS) TestPanicMatches(c *check.C) { testInfo(c, check.PanicMatches, "PanicMatches", []string{"function", "expected"}) // Error matching. testCheck(c, check.PanicMatches, true, "", func() { panic(errors.New("BOOM")) }, "BO.M") testCheck(c, check.PanicMatches, false, "", func() { panic(errors.New("KABOOM")) }, "BO.M") // Some errors. testCheck(c, check.PanicMatches, false, "Function has not panicked", func() bool { return false }, "BOOM") testCheck(c, check.PanicMatches, false, "Function must take zero arguments", 1, "BOOM") // Plain strings. testCheck(c, check.PanicMatches, true, "", func() { panic("BOOM") }, "BO.M") testCheck(c, check.PanicMatches, false, "", func() { panic("KABOOM") }, "BOOM") testCheck(c, check.PanicMatches, true, "", func() bool { panic("BOOM") }, "BO.M") // Verify params/names mutation params, names := testCheck(c, check.PanicMatches, false, "", func() { panic(errors.New("KABOOM")) }, "BOOM") c.Assert(params[0], check.Equals, "KABOOM") c.Assert(names[0], check.Equals, "panic") // Verify a nil panic testCheck(c, check.PanicMatches, false, "Panic value is not a string or an error", func() { panic(nil) }, "") } func (s *CheckersS) TestFitsTypeOf(c *check.C) { testInfo(c, check.FitsTypeOf, "FitsTypeOf", []string{"obtained", "sample"}) // Basic types testCheck(c, check.FitsTypeOf, true, "", 1, 0) testCheck(c, check.FitsTypeOf, false, "", 1, int64(0)) // Aliases testCheck(c, check.FitsTypeOf, false, "", 1, errors.New("")) testCheck(c, check.FitsTypeOf, false, "", "error", errors.New("")) testCheck(c, check.FitsTypeOf, true, "", errors.New("error"), errors.New("")) // Structures testCheck(c, check.FitsTypeOf, false, "", 1, simpleStruct{}) testCheck(c, check.FitsTypeOf, false, "", simpleStruct{42}, &simpleStruct{}) testCheck(c, check.FitsTypeOf, true, "", simpleStruct{42}, simpleStruct{}) testCheck(c, check.FitsTypeOf, true, "", &simpleStruct{42}, &simpleStruct{}) // Some bad values testCheck(c, check.FitsTypeOf, false, "Invalid sample value", 1, interface{}(nil)) testCheck(c, check.FitsTypeOf, false, "", interface{}(nil), 0) } func (s *CheckersS) TestImplements(c *check.C) { testInfo(c, check.Implements, "Implements", []string{"obtained", "ifaceptr"}) var e error var re runtime.Error testCheck(c, check.Implements, true, "", errors.New(""), &e) testCheck(c, check.Implements, false, "", errors.New(""), &re) // Some bad values testCheck(c, check.Implements, false, "ifaceptr should be a pointer to an interface variable", 0, errors.New("")) testCheck(c, check.Implements, false, "ifaceptr should be a pointer to an interface variable", 0, interface{}(nil)) testCheck(c, check.Implements, false, "", interface{}(nil), &e) } go-gir-generator-master/vendor/src/gopkg.in/check.v1/export_test.go000066400000000000000000000002571414263242200256340ustar00rootroot00000000000000package check func PrintLine(filename string, line int) (string, error) { return printLine(filename, line) } func Indent(s, with string) string { return indent(s, with) } go-gir-generator-master/vendor/src/gopkg.in/check.v1/fixture_test.go000066400000000000000000000333051414263242200260010ustar00rootroot00000000000000// Tests for the behavior of the test fixture system. package check_test import ( . "gopkg.in/check.v1" ) // ----------------------------------------------------------------------- // Fixture test suite. type FixtureS struct{} var fixtureS = Suite(&FixtureS{}) func (s *FixtureS) TestCountSuite(c *C) { suitesRun += 1 } // ----------------------------------------------------------------------- // Basic fixture ordering verification. func (s *FixtureS) TestOrder(c *C) { helper := FixtureHelper{} Run(&helper, nil) c.Check(helper.calls[0], Equals, "SetUpSuite") c.Check(helper.calls[1], Equals, "SetUpTest") c.Check(helper.calls[2], Equals, "Test1") c.Check(helper.calls[3], Equals, "TearDownTest") c.Check(helper.calls[4], Equals, "SetUpTest") c.Check(helper.calls[5], Equals, "Test2") c.Check(helper.calls[6], Equals, "TearDownTest") c.Check(helper.calls[7], Equals, "TearDownSuite") c.Check(len(helper.calls), Equals, 8) } // ----------------------------------------------------------------------- // Check the behavior when panics occur within tests and fixtures. func (s *FixtureS) TestPanicOnTest(c *C) { helper := FixtureHelper{panicOn: "Test1"} output := String{} Run(&helper, &RunConf{Output: &output}) c.Check(helper.calls[0], Equals, "SetUpSuite") c.Check(helper.calls[1], Equals, "SetUpTest") c.Check(helper.calls[2], Equals, "Test1") c.Check(helper.calls[3], Equals, "TearDownTest") c.Check(helper.calls[4], Equals, "SetUpTest") c.Check(helper.calls[5], Equals, "Test2") c.Check(helper.calls[6], Equals, "TearDownTest") c.Check(helper.calls[7], Equals, "TearDownSuite") c.Check(len(helper.calls), Equals, 8) expected := "^\n-+\n" + "PANIC: check_test\\.go:[0-9]+: FixtureHelper.Test1\n\n" + "\\.\\.\\. Panic: Test1 \\(PC=[xA-F0-9]+\\)\n\n" + ".+:[0-9]+\n" + " in (go)?panic\n" + ".*check_test.go:[0-9]+\n" + " in FixtureHelper.trace\n" + ".*check_test.go:[0-9]+\n" + " in FixtureHelper.Test1\n" + "(.|\n)*$" c.Check(output.value, Matches, expected) } func (s *FixtureS) TestPanicOnSetUpTest(c *C) { helper := FixtureHelper{panicOn: "SetUpTest"} output := String{} Run(&helper, &RunConf{Output: &output}) c.Check(helper.calls[0], Equals, "SetUpSuite") c.Check(helper.calls[1], Equals, "SetUpTest") c.Check(helper.calls[2], Equals, "TearDownTest") c.Check(helper.calls[3], Equals, "TearDownSuite") c.Check(len(helper.calls), Equals, 4) expected := "^\n-+\n" + "PANIC: check_test\\.go:[0-9]+: " + "FixtureHelper\\.SetUpTest\n\n" + "\\.\\.\\. Panic: SetUpTest \\(PC=[xA-F0-9]+\\)\n\n" + ".+:[0-9]+\n" + " in (go)?panic\n" + ".*check_test.go:[0-9]+\n" + " in FixtureHelper.trace\n" + ".*check_test.go:[0-9]+\n" + " in FixtureHelper.SetUpTest\n" + "(.|\n)*" + "\n-+\n" + "PANIC: check_test\\.go:[0-9]+: " + "FixtureHelper\\.Test1\n\n" + "\\.\\.\\. Panic: Fixture has panicked " + "\\(see related PANIC\\)\n$" c.Check(output.value, Matches, expected) } func (s *FixtureS) TestPanicOnTearDownTest(c *C) { helper := FixtureHelper{panicOn: "TearDownTest"} output := String{} Run(&helper, &RunConf{Output: &output}) c.Check(helper.calls[0], Equals, "SetUpSuite") c.Check(helper.calls[1], Equals, "SetUpTest") c.Check(helper.calls[2], Equals, "Test1") c.Check(helper.calls[3], Equals, "TearDownTest") c.Check(helper.calls[4], Equals, "TearDownSuite") c.Check(len(helper.calls), Equals, 5) expected := "^\n-+\n" + "PANIC: check_test\\.go:[0-9]+: " + "FixtureHelper.TearDownTest\n\n" + "\\.\\.\\. Panic: TearDownTest \\(PC=[xA-F0-9]+\\)\n\n" + ".+:[0-9]+\n" + " in (go)?panic\n" + ".*check_test.go:[0-9]+\n" + " in FixtureHelper.trace\n" + ".*check_test.go:[0-9]+\n" + " in FixtureHelper.TearDownTest\n" + "(.|\n)*" + "\n-+\n" + "PANIC: check_test\\.go:[0-9]+: " + "FixtureHelper\\.Test1\n\n" + "\\.\\.\\. Panic: Fixture has panicked " + "\\(see related PANIC\\)\n$" c.Check(output.value, Matches, expected) } func (s *FixtureS) TestPanicOnSetUpSuite(c *C) { helper := FixtureHelper{panicOn: "SetUpSuite"} output := String{} Run(&helper, &RunConf{Output: &output}) c.Check(helper.calls[0], Equals, "SetUpSuite") c.Check(helper.calls[1], Equals, "TearDownSuite") c.Check(len(helper.calls), Equals, 2) expected := "^\n-+\n" + "PANIC: check_test\\.go:[0-9]+: " + "FixtureHelper.SetUpSuite\n\n" + "\\.\\.\\. Panic: SetUpSuite \\(PC=[xA-F0-9]+\\)\n\n" + ".+:[0-9]+\n" + " in (go)?panic\n" + ".*check_test.go:[0-9]+\n" + " in FixtureHelper.trace\n" + ".*check_test.go:[0-9]+\n" + " in FixtureHelper.SetUpSuite\n" + "(.|\n)*$" c.Check(output.value, Matches, expected) } func (s *FixtureS) TestPanicOnTearDownSuite(c *C) { helper := FixtureHelper{panicOn: "TearDownSuite"} output := String{} Run(&helper, &RunConf{Output: &output}) c.Check(helper.calls[0], Equals, "SetUpSuite") c.Check(helper.calls[1], Equals, "SetUpTest") c.Check(helper.calls[2], Equals, "Test1") c.Check(helper.calls[3], Equals, "TearDownTest") c.Check(helper.calls[4], Equals, "SetUpTest") c.Check(helper.calls[5], Equals, "Test2") c.Check(helper.calls[6], Equals, "TearDownTest") c.Check(helper.calls[7], Equals, "TearDownSuite") c.Check(len(helper.calls), Equals, 8) expected := "^\n-+\n" + "PANIC: check_test\\.go:[0-9]+: " + "FixtureHelper.TearDownSuite\n\n" + "\\.\\.\\. Panic: TearDownSuite \\(PC=[xA-F0-9]+\\)\n\n" + ".+:[0-9]+\n" + " in (go)?panic\n" + ".*check_test.go:[0-9]+\n" + " in FixtureHelper.trace\n" + ".*check_test.go:[0-9]+\n" + " in FixtureHelper.TearDownSuite\n" + "(.|\n)*$" c.Check(output.value, Matches, expected) } // ----------------------------------------------------------------------- // A wrong argument on a test or fixture will produce a nice error. func (s *FixtureS) TestPanicOnWrongTestArg(c *C) { helper := WrongTestArgHelper{} output := String{} Run(&helper, &RunConf{Output: &output}) c.Check(helper.calls[0], Equals, "SetUpSuite") c.Check(helper.calls[1], Equals, "SetUpTest") c.Check(helper.calls[2], Equals, "TearDownTest") c.Check(helper.calls[3], Equals, "SetUpTest") c.Check(helper.calls[4], Equals, "Test2") c.Check(helper.calls[5], Equals, "TearDownTest") c.Check(helper.calls[6], Equals, "TearDownSuite") c.Check(len(helper.calls), Equals, 7) expected := "^\n-+\n" + "PANIC: fixture_test\\.go:[0-9]+: " + "WrongTestArgHelper\\.Test1\n\n" + "\\.\\.\\. Panic: WrongTestArgHelper\\.Test1 argument " + "should be \\*check\\.C\n" c.Check(output.value, Matches, expected) } func (s *FixtureS) TestPanicOnWrongSetUpTestArg(c *C) { helper := WrongSetUpTestArgHelper{} output := String{} Run(&helper, &RunConf{Output: &output}) c.Check(len(helper.calls), Equals, 0) expected := "^\n-+\n" + "PANIC: fixture_test\\.go:[0-9]+: " + "WrongSetUpTestArgHelper\\.SetUpTest\n\n" + "\\.\\.\\. Panic: WrongSetUpTestArgHelper\\.SetUpTest argument " + "should be \\*check\\.C\n" c.Check(output.value, Matches, expected) } func (s *FixtureS) TestPanicOnWrongSetUpSuiteArg(c *C) { helper := WrongSetUpSuiteArgHelper{} output := String{} Run(&helper, &RunConf{Output: &output}) c.Check(len(helper.calls), Equals, 0) expected := "^\n-+\n" + "PANIC: fixture_test\\.go:[0-9]+: " + "WrongSetUpSuiteArgHelper\\.SetUpSuite\n\n" + "\\.\\.\\. Panic: WrongSetUpSuiteArgHelper\\.SetUpSuite argument " + "should be \\*check\\.C\n" c.Check(output.value, Matches, expected) } // ----------------------------------------------------------------------- // Nice errors also when tests or fixture have wrong arg count. func (s *FixtureS) TestPanicOnWrongTestArgCount(c *C) { helper := WrongTestArgCountHelper{} output := String{} Run(&helper, &RunConf{Output: &output}) c.Check(helper.calls[0], Equals, "SetUpSuite") c.Check(helper.calls[1], Equals, "SetUpTest") c.Check(helper.calls[2], Equals, "TearDownTest") c.Check(helper.calls[3], Equals, "SetUpTest") c.Check(helper.calls[4], Equals, "Test2") c.Check(helper.calls[5], Equals, "TearDownTest") c.Check(helper.calls[6], Equals, "TearDownSuite") c.Check(len(helper.calls), Equals, 7) expected := "^\n-+\n" + "PANIC: fixture_test\\.go:[0-9]+: " + "WrongTestArgCountHelper\\.Test1\n\n" + "\\.\\.\\. Panic: WrongTestArgCountHelper\\.Test1 argument " + "should be \\*check\\.C\n" c.Check(output.value, Matches, expected) } func (s *FixtureS) TestPanicOnWrongSetUpTestArgCount(c *C) { helper := WrongSetUpTestArgCountHelper{} output := String{} Run(&helper, &RunConf{Output: &output}) c.Check(len(helper.calls), Equals, 0) expected := "^\n-+\n" + "PANIC: fixture_test\\.go:[0-9]+: " + "WrongSetUpTestArgCountHelper\\.SetUpTest\n\n" + "\\.\\.\\. Panic: WrongSetUpTestArgCountHelper\\.SetUpTest argument " + "should be \\*check\\.C\n" c.Check(output.value, Matches, expected) } func (s *FixtureS) TestPanicOnWrongSetUpSuiteArgCount(c *C) { helper := WrongSetUpSuiteArgCountHelper{} output := String{} Run(&helper, &RunConf{Output: &output}) c.Check(len(helper.calls), Equals, 0) expected := "^\n-+\n" + "PANIC: fixture_test\\.go:[0-9]+: " + "WrongSetUpSuiteArgCountHelper\\.SetUpSuite\n\n" + "\\.\\.\\. Panic: WrongSetUpSuiteArgCountHelper" + "\\.SetUpSuite argument should be \\*check\\.C\n" c.Check(output.value, Matches, expected) } // ----------------------------------------------------------------------- // Helper test suites with wrong function arguments. type WrongTestArgHelper struct { FixtureHelper } func (s *WrongTestArgHelper) Test1(t int) { } type WrongSetUpTestArgHelper struct { FixtureHelper } func (s *WrongSetUpTestArgHelper) SetUpTest(t int) { } type WrongSetUpSuiteArgHelper struct { FixtureHelper } func (s *WrongSetUpSuiteArgHelper) SetUpSuite(t int) { } type WrongTestArgCountHelper struct { FixtureHelper } func (s *WrongTestArgCountHelper) Test1(c *C, i int) { } type WrongSetUpTestArgCountHelper struct { FixtureHelper } func (s *WrongSetUpTestArgCountHelper) SetUpTest(c *C, i int) { } type WrongSetUpSuiteArgCountHelper struct { FixtureHelper } func (s *WrongSetUpSuiteArgCountHelper) SetUpSuite(c *C, i int) { } // ----------------------------------------------------------------------- // Ensure fixture doesn't run without tests. type NoTestsHelper struct { hasRun bool } func (s *NoTestsHelper) SetUpSuite(c *C) { s.hasRun = true } func (s *NoTestsHelper) TearDownSuite(c *C) { s.hasRun = true } func (s *FixtureS) TestFixtureDoesntRunWithoutTests(c *C) { helper := NoTestsHelper{} output := String{} Run(&helper, &RunConf{Output: &output}) c.Check(helper.hasRun, Equals, false) } // ----------------------------------------------------------------------- // Verify that checks and assertions work correctly inside the fixture. type FixtureCheckHelper struct { fail string completed bool } func (s *FixtureCheckHelper) SetUpSuite(c *C) { switch s.fail { case "SetUpSuiteAssert": c.Assert(false, Equals, true) case "SetUpSuiteCheck": c.Check(false, Equals, true) } s.completed = true } func (s *FixtureCheckHelper) SetUpTest(c *C) { switch s.fail { case "SetUpTestAssert": c.Assert(false, Equals, true) case "SetUpTestCheck": c.Check(false, Equals, true) } s.completed = true } func (s *FixtureCheckHelper) Test(c *C) { // Do nothing. } func (s *FixtureS) TestSetUpSuiteCheck(c *C) { helper := FixtureCheckHelper{fail: "SetUpSuiteCheck"} output := String{} Run(&helper, &RunConf{Output: &output}) c.Assert(output.value, Matches, "\n---+\n"+ "FAIL: fixture_test\\.go:[0-9]+: "+ "FixtureCheckHelper\\.SetUpSuite\n\n"+ "fixture_test\\.go:[0-9]+:\n"+ " c\\.Check\\(false, Equals, true\\)\n"+ "\\.+ obtained bool = false\n"+ "\\.+ expected bool = true\n\n") c.Assert(helper.completed, Equals, true) } func (s *FixtureS) TestSetUpSuiteAssert(c *C) { helper := FixtureCheckHelper{fail: "SetUpSuiteAssert"} output := String{} Run(&helper, &RunConf{Output: &output}) c.Assert(output.value, Matches, "\n---+\n"+ "FAIL: fixture_test\\.go:[0-9]+: "+ "FixtureCheckHelper\\.SetUpSuite\n\n"+ "fixture_test\\.go:[0-9]+:\n"+ " c\\.Assert\\(false, Equals, true\\)\n"+ "\\.+ obtained bool = false\n"+ "\\.+ expected bool = true\n\n") c.Assert(helper.completed, Equals, false) } // ----------------------------------------------------------------------- // Verify that logging within SetUpTest() persists within the test log itself. type FixtureLogHelper struct { c *C } func (s *FixtureLogHelper) SetUpTest(c *C) { s.c = c c.Log("1") } func (s *FixtureLogHelper) Test(c *C) { c.Log("2") s.c.Log("3") c.Log("4") c.Fail() } func (s *FixtureLogHelper) TearDownTest(c *C) { s.c.Log("5") } func (s *FixtureS) TestFixtureLogging(c *C) { helper := FixtureLogHelper{} output := String{} Run(&helper, &RunConf{Output: &output}) c.Assert(output.value, Matches, "\n---+\n"+ "FAIL: fixture_test\\.go:[0-9]+: "+ "FixtureLogHelper\\.Test\n\n"+ "1\n2\n3\n4\n5\n") } // ----------------------------------------------------------------------- // Skip() within fixture methods. func (s *FixtureS) TestSkipSuite(c *C) { helper := FixtureHelper{skip: true, skipOnN: 0} output := String{} result := Run(&helper, &RunConf{Output: &output}) c.Assert(output.value, Equals, "") c.Assert(helper.calls[0], Equals, "SetUpSuite") c.Assert(helper.calls[1], Equals, "TearDownSuite") c.Assert(len(helper.calls), Equals, 2) c.Assert(result.Skipped, Equals, 2) } func (s *FixtureS) TestSkipTest(c *C) { helper := FixtureHelper{skip: true, skipOnN: 1} output := String{} result := Run(&helper, &RunConf{Output: &output}) c.Assert(helper.calls[0], Equals, "SetUpSuite") c.Assert(helper.calls[1], Equals, "SetUpTest") c.Assert(helper.calls[2], Equals, "SetUpTest") c.Assert(helper.calls[3], Equals, "Test2") c.Assert(helper.calls[4], Equals, "TearDownTest") c.Assert(helper.calls[5], Equals, "TearDownSuite") c.Assert(len(helper.calls), Equals, 6) c.Assert(result.Skipped, Equals, 1) } go-gir-generator-master/vendor/src/gopkg.in/check.v1/foundation_test.go000066400000000000000000000214211414263242200264550ustar00rootroot00000000000000// These tests check that the foundations of gocheck are working properly. // They already assume that fundamental failing is working already, though, // since this was tested in bootstrap_test.go. Even then, some care may // still have to be taken when using external functions, since they should // of course not rely on functionality tested here. package check_test import ( "fmt" "gopkg.in/check.v1" "log" "os" "regexp" "strings" ) // ----------------------------------------------------------------------- // Foundation test suite. type FoundationS struct{} var foundationS = check.Suite(&FoundationS{}) func (s *FoundationS) TestCountSuite(c *check.C) { suitesRun += 1 } func (s *FoundationS) TestErrorf(c *check.C) { // Do not use checkState() here. It depends on Errorf() working. expectedLog := fmt.Sprintf("foundation_test.go:%d:\n"+ " c.Errorf(\"Error %%v!\", \"message\")\n"+ "... Error: Error message!\n\n", getMyLine()+1) c.Errorf("Error %v!", "message") failed := c.Failed() c.Succeed() if log := c.GetTestLog(); log != expectedLog { c.Logf("Errorf() logged %#v rather than %#v", log, expectedLog) c.Fail() } if !failed { c.Logf("Errorf() didn't put the test in a failed state") c.Fail() } } func (s *FoundationS) TestError(c *check.C) { expectedLog := fmt.Sprintf("foundation_test.go:%d:\n"+ " c\\.Error\\(\"Error \", \"message!\"\\)\n"+ "\\.\\.\\. Error: Error message!\n\n", getMyLine()+1) c.Error("Error ", "message!") checkState(c, nil, &expectedState{ name: "Error(`Error `, `message!`)", failed: true, log: expectedLog, }) } func (s *FoundationS) TestFailNow(c *check.C) { defer (func() { if !c.Failed() { c.Error("FailNow() didn't fail the test") } else { c.Succeed() if c.GetTestLog() != "" { c.Error("Something got logged:\n" + c.GetTestLog()) } } })() c.FailNow() c.Log("FailNow() didn't stop the test") } func (s *FoundationS) TestSucceedNow(c *check.C) { defer (func() { if c.Failed() { c.Error("SucceedNow() didn't succeed the test") } if c.GetTestLog() != "" { c.Error("Something got logged:\n" + c.GetTestLog()) } })() c.Fail() c.SucceedNow() c.Log("SucceedNow() didn't stop the test") } func (s *FoundationS) TestFailureHeader(c *check.C) { output := String{} failHelper := FailHelper{} check.Run(&failHelper, &check.RunConf{Output: &output}) header := fmt.Sprintf(""+ "\n-----------------------------------"+ "-----------------------------------\n"+ "FAIL: check_test.go:%d: FailHelper.TestLogAndFail\n", failHelper.testLine) if strings.Index(output.value, header) == -1 { c.Errorf(""+ "Failure didn't print a proper header.\n"+ "... Got:\n%s... Expected something with:\n%s", output.value, header) } } func (s *FoundationS) TestFatal(c *check.C) { var line int defer (func() { if !c.Failed() { c.Error("Fatal() didn't fail the test") } else { c.Succeed() expected := fmt.Sprintf("foundation_test.go:%d:\n"+ " c.Fatal(\"Die \", \"now!\")\n"+ "... Error: Die now!\n\n", line) if c.GetTestLog() != expected { c.Error("Incorrect log:", c.GetTestLog()) } } })() line = getMyLine() + 1 c.Fatal("Die ", "now!") c.Log("Fatal() didn't stop the test") } func (s *FoundationS) TestFatalf(c *check.C) { var line int defer (func() { if !c.Failed() { c.Error("Fatalf() didn't fail the test") } else { c.Succeed() expected := fmt.Sprintf("foundation_test.go:%d:\n"+ " c.Fatalf(\"Die %%s!\", \"now\")\n"+ "... Error: Die now!\n\n", line) if c.GetTestLog() != expected { c.Error("Incorrect log:", c.GetTestLog()) } } })() line = getMyLine() + 1 c.Fatalf("Die %s!", "now") c.Log("Fatalf() didn't stop the test") } func (s *FoundationS) TestCallerLoggingInsideTest(c *check.C) { log := fmt.Sprintf(""+ "foundation_test.go:%d:\n"+ " result := c.Check\\(10, check.Equals, 20\\)\n"+ "\\.\\.\\. obtained int = 10\n"+ "\\.\\.\\. expected int = 20\n\n", getMyLine()+1) result := c.Check(10, check.Equals, 20) checkState(c, result, &expectedState{ name: "Check(10, Equals, 20)", result: false, failed: true, log: log, }) } func (s *FoundationS) TestCallerLoggingInDifferentFile(c *check.C) { result, line := checkEqualWrapper(c, 10, 20) testLine := getMyLine() - 1 log := fmt.Sprintf(""+ "foundation_test.go:%d:\n"+ " result, line := checkEqualWrapper\\(c, 10, 20\\)\n"+ "check_test.go:%d:\n"+ " return c.Check\\(obtained, check.Equals, expected\\), getMyLine\\(\\)\n"+ "\\.\\.\\. obtained int = 10\n"+ "\\.\\.\\. expected int = 20\n\n", testLine, line) checkState(c, result, &expectedState{ name: "Check(10, Equals, 20)", result: false, failed: true, log: log, }) } // ----------------------------------------------------------------------- // ExpectFailure() inverts the logic of failure. type ExpectFailureSucceedHelper struct{} func (s *ExpectFailureSucceedHelper) TestSucceed(c *check.C) { c.ExpectFailure("It booms!") c.Error("Boom!") } type ExpectFailureFailHelper struct{} func (s *ExpectFailureFailHelper) TestFail(c *check.C) { c.ExpectFailure("Bug #XYZ") } func (s *FoundationS) TestExpectFailureFail(c *check.C) { helper := ExpectFailureFailHelper{} output := String{} result := check.Run(&helper, &check.RunConf{Output: &output}) expected := "" + "^\n-+\n" + "FAIL: foundation_test\\.go:[0-9]+:" + " ExpectFailureFailHelper\\.TestFail\n\n" + "\\.\\.\\. Error: Test succeeded, but was expected to fail\n" + "\\.\\.\\. Reason: Bug #XYZ\n$" matched, err := regexp.MatchString(expected, output.value) if err != nil { c.Error("Bad expression: ", expected) } else if !matched { c.Error("ExpectFailure() didn't log properly:\n", output.value) } c.Assert(result.ExpectedFailures, check.Equals, 0) } func (s *FoundationS) TestExpectFailureSucceed(c *check.C) { helper := ExpectFailureSucceedHelper{} output := String{} result := check.Run(&helper, &check.RunConf{Output: &output}) c.Assert(output.value, check.Equals, "") c.Assert(result.ExpectedFailures, check.Equals, 1) } func (s *FoundationS) TestExpectFailureSucceedVerbose(c *check.C) { helper := ExpectFailureSucceedHelper{} output := String{} result := check.Run(&helper, &check.RunConf{Output: &output, Verbose: true}) expected := "" + "FAIL EXPECTED: foundation_test\\.go:[0-9]+:" + " ExpectFailureSucceedHelper\\.TestSucceed \\(It booms!\\)\t *[.0-9]+s\n" matched, err := regexp.MatchString(expected, output.value) if err != nil { c.Error("Bad expression: ", expected) } else if !matched { c.Error("ExpectFailure() didn't log properly:\n", output.value) } c.Assert(result.ExpectedFailures, check.Equals, 1) } // ----------------------------------------------------------------------- // Skip() allows stopping a test without positive/negative results. type SkipTestHelper struct{} func (s *SkipTestHelper) TestFail(c *check.C) { c.Skip("Wrong platform or whatever") c.Error("Boom!") } func (s *FoundationS) TestSkip(c *check.C) { helper := SkipTestHelper{} output := String{} check.Run(&helper, &check.RunConf{Output: &output}) if output.value != "" { c.Error("Skip() logged something:\n", output.value) } } func (s *FoundationS) TestSkipVerbose(c *check.C) { helper := SkipTestHelper{} output := String{} check.Run(&helper, &check.RunConf{Output: &output, Verbose: true}) expected := "SKIP: foundation_test\\.go:[0-9]+: SkipTestHelper\\.TestFail" + " \\(Wrong platform or whatever\\)" matched, err := regexp.MatchString(expected, output.value) if err != nil { c.Error("Bad expression: ", expected) } else if !matched { c.Error("Skip() didn't log properly:\n", output.value) } } // ----------------------------------------------------------------------- // Check minimum *log.Logger interface provided by *check.C. type minLogger interface { Output(calldepth int, s string) error } func (s *BootstrapS) TestMinLogger(c *check.C) { var logger minLogger logger = log.New(os.Stderr, "", 0) logger = c logger.Output(0, "Hello there") expected := `\[LOG\] [0-9]+:[0-9][0-9]\.[0-9][0-9][0-9] +Hello there\n` output := c.GetTestLog() c.Assert(output, check.Matches, expected) } // ----------------------------------------------------------------------- // Ensure that suites with embedded types are working fine, including the // the workaround for issue 906. type EmbeddedInternalS struct { called bool } type EmbeddedS struct { EmbeddedInternalS } var embeddedS = check.Suite(&EmbeddedS{}) func (s *EmbeddedS) TestCountSuite(c *check.C) { suitesRun += 1 } func (s *EmbeddedInternalS) TestMethod(c *check.C) { c.Error("TestMethod() of the embedded type was called!?") } func (s *EmbeddedS) TestMethod(c *check.C) { // http://code.google.com/p/go/issues/detail?id=906 c.Check(s.called, check.Equals, false) // Go issue 906 is affecting the runner? s.called = true } go-gir-generator-master/vendor/src/gopkg.in/check.v1/helpers.go000066400000000000000000000161051414263242200247150ustar00rootroot00000000000000package check import ( "fmt" "strings" "time" ) // TestName returns the current test name in the form "SuiteName.TestName" func (c *C) TestName() string { return c.testName } // ----------------------------------------------------------------------- // Basic succeeding/failing logic. // Failed returns whether the currently running test has already failed. func (c *C) Failed() bool { return c.status() == failedSt } // Fail marks the currently running test as failed. // // Something ought to have been previously logged so the developer can tell // what went wrong. The higher level helper functions will fail the test // and do the logging properly. func (c *C) Fail() { c.setStatus(failedSt) } // FailNow marks the currently running test as failed and stops running it. // Something ought to have been previously logged so the developer can tell // what went wrong. The higher level helper functions will fail the test // and do the logging properly. func (c *C) FailNow() { c.Fail() c.stopNow() } // Succeed marks the currently running test as succeeded, undoing any // previous failures. func (c *C) Succeed() { c.setStatus(succeededSt) } // SucceedNow marks the currently running test as succeeded, undoing any // previous failures, and stops running the test. func (c *C) SucceedNow() { c.Succeed() c.stopNow() } // ExpectFailure informs that the running test is knowingly broken for // the provided reason. If the test does not fail, an error will be reported // to raise attention to this fact. This method is useful to temporarily // disable tests which cover well known problems until a better time to // fix the problem is found, without forgetting about the fact that a // failure still exists. func (c *C) ExpectFailure(reason string) { if reason == "" { panic("Missing reason why the test is expected to fail") } c.mustFail = true c.reason = reason } // Skip skips the running test for the provided reason. If run from within // SetUpTest, the individual test being set up will be skipped, and if run // from within SetUpSuite, the whole suite is skipped. func (c *C) Skip(reason string) { if reason == "" { panic("Missing reason why the test is being skipped") } c.reason = reason c.setStatus(skippedSt) c.stopNow() } // ----------------------------------------------------------------------- // Basic logging. // GetTestLog returns the current test error output. func (c *C) GetTestLog() string { return c.logb.String() } // Log logs some information into the test error output. // The provided arguments are assembled together into a string with fmt.Sprint. func (c *C) Log(args ...interface{}) { c.log(args...) } // Log logs some information into the test error output. // The provided arguments are assembled together into a string with fmt.Sprintf. func (c *C) Logf(format string, args ...interface{}) { c.logf(format, args...) } // Output enables *C to be used as a logger in functions that require only // the minimum interface of *log.Logger. func (c *C) Output(calldepth int, s string) error { d := time.Now().Sub(c.startTime) msec := d / time.Millisecond sec := d / time.Second min := d / time.Minute c.Logf("[LOG] %d:%02d.%03d %s", min, sec%60, msec%1000, s) return nil } // Error logs an error into the test error output and marks the test as failed. // The provided arguments are assembled together into a string with fmt.Sprint. func (c *C) Error(args ...interface{}) { c.logCaller(1) c.logString(fmt.Sprint("Error: ", fmt.Sprint(args...))) c.logNewLine() c.Fail() } // Errorf logs an error into the test error output and marks the test as failed. // The provided arguments are assembled together into a string with fmt.Sprintf. func (c *C) Errorf(format string, args ...interface{}) { c.logCaller(1) c.logString(fmt.Sprintf("Error: "+format, args...)) c.logNewLine() c.Fail() } // Fatal logs an error into the test error output, marks the test as failed, and // stops the test execution. The provided arguments are assembled together into // a string with fmt.Sprint. func (c *C) Fatal(args ...interface{}) { c.logCaller(1) c.logString(fmt.Sprint("Error: ", fmt.Sprint(args...))) c.logNewLine() c.FailNow() } // Fatlaf logs an error into the test error output, marks the test as failed, and // stops the test execution. The provided arguments are assembled together into // a string with fmt.Sprintf. func (c *C) Fatalf(format string, args ...interface{}) { c.logCaller(1) c.logString(fmt.Sprint("Error: ", fmt.Sprintf(format, args...))) c.logNewLine() c.FailNow() } // ----------------------------------------------------------------------- // Generic checks and assertions based on checkers. // Check verifies if the first value matches the expected value according // to the provided checker. If they do not match, an error is logged, the // test is marked as failed, and the test execution continues. // // Some checkers may not need the expected argument (e.g. IsNil). // // Extra arguments provided to the function are logged next to the reported // problem when the matching fails. func (c *C) Check(obtained interface{}, checker Checker, args ...interface{}) bool { return c.internalCheck("Check", obtained, checker, args...) } // Assert ensures that the first value matches the expected value according // to the provided checker. If they do not match, an error is logged, the // test is marked as failed, and the test execution stops. // // Some checkers may not need the expected argument (e.g. IsNil). // // Extra arguments provided to the function are logged next to the reported // problem when the matching fails. func (c *C) Assert(obtained interface{}, checker Checker, args ...interface{}) { if !c.internalCheck("Assert", obtained, checker, args...) { c.stopNow() } } func (c *C) internalCheck(funcName string, obtained interface{}, checker Checker, args ...interface{}) bool { if checker == nil { c.logCaller(2) c.logString(fmt.Sprintf("%s(obtained, nil!?, ...):", funcName)) c.logString("Oops.. you've provided a nil checker!") c.logNewLine() c.Fail() return false } // If the last argument is a bug info, extract it out. var comment CommentInterface if len(args) > 0 { if c, ok := args[len(args)-1].(CommentInterface); ok { comment = c args = args[:len(args)-1] } } params := append([]interface{}{obtained}, args...) info := checker.Info() if len(params) != len(info.Params) { names := append([]string{info.Params[0], info.Name}, info.Params[1:]...) c.logCaller(2) c.logString(fmt.Sprintf("%s(%s):", funcName, strings.Join(names, ", "))) c.logString(fmt.Sprintf("Wrong number of parameters for %s: want %d, got %d", info.Name, len(names), len(params)+1)) c.logNewLine() c.Fail() return false } // Copy since it may be mutated by Check. names := append([]string{}, info.Params...) // Do the actual check. result, error := checker.Check(params, names) if !result || error != "" { c.logCaller(2) for i := 0; i != len(params); i++ { c.logValue(names[i], params[i]) } if comment != nil { c.logString(comment.CheckCommentString()) } if error != "" { c.logString(error) } c.logNewLine() c.Fail() return false } return true } go-gir-generator-master/vendor/src/gopkg.in/check.v1/helpers_test.go000066400000000000000000000410341414263242200257530ustar00rootroot00000000000000// These tests verify the inner workings of the helper methods associated // with check.T. package check_test import ( "gopkg.in/check.v1" "os" "reflect" "runtime" "sync" ) var helpersS = check.Suite(&HelpersS{}) type HelpersS struct{} func (s *HelpersS) TestCountSuite(c *check.C) { suitesRun += 1 } // ----------------------------------------------------------------------- // Fake checker and bug info to verify the behavior of Assert() and Check(). type MyChecker struct { info *check.CheckerInfo params []interface{} names []string result bool error string } func (checker *MyChecker) Info() *check.CheckerInfo { if checker.info == nil { return &check.CheckerInfo{Name: "MyChecker", Params: []string{"myobtained", "myexpected"}} } return checker.info } func (checker *MyChecker) Check(params []interface{}, names []string) (bool, string) { rparams := checker.params rnames := checker.names checker.params = append([]interface{}{}, params...) checker.names = append([]string{}, names...) if rparams != nil { copy(params, rparams) } if rnames != nil { copy(names, rnames) } return checker.result, checker.error } type myCommentType string func (c myCommentType) CheckCommentString() string { return string(c) } func myComment(s string) myCommentType { return myCommentType(s) } // ----------------------------------------------------------------------- // Ensure a real checker actually works fine. func (s *HelpersS) TestCheckerInterface(c *check.C) { testHelperSuccess(c, "Check(1, Equals, 1)", true, func() interface{} { return c.Check(1, check.Equals, 1) }) } // ----------------------------------------------------------------------- // Tests for Check(), mostly the same as for Assert() following these. func (s *HelpersS) TestCheckSucceedWithExpected(c *check.C) { checker := &MyChecker{result: true} testHelperSuccess(c, "Check(1, checker, 2)", true, func() interface{} { return c.Check(1, checker, 2) }) if !reflect.DeepEqual(checker.params, []interface{}{1, 2}) { c.Fatalf("Bad params for check: %#v", checker.params) } } func (s *HelpersS) TestCheckSucceedWithoutExpected(c *check.C) { checker := &MyChecker{result: true, info: &check.CheckerInfo{Params: []string{"myvalue"}}} testHelperSuccess(c, "Check(1, checker)", true, func() interface{} { return c.Check(1, checker) }) if !reflect.DeepEqual(checker.params, []interface{}{1}) { c.Fatalf("Bad params for check: %#v", checker.params) } } func (s *HelpersS) TestCheckFailWithExpected(c *check.C) { checker := &MyChecker{result: false} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " return c\\.Check\\(1, checker, 2\\)\n" + "\\.+ myobtained int = 1\n" + "\\.+ myexpected int = 2\n\n" testHelperFailure(c, "Check(1, checker, 2)", false, false, log, func() interface{} { return c.Check(1, checker, 2) }) } func (s *HelpersS) TestCheckFailWithExpectedAndComment(c *check.C) { checker := &MyChecker{result: false} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " return c\\.Check\\(1, checker, 2, myComment\\(\"Hello world!\"\\)\\)\n" + "\\.+ myobtained int = 1\n" + "\\.+ myexpected int = 2\n" + "\\.+ Hello world!\n\n" testHelperFailure(c, "Check(1, checker, 2, msg)", false, false, log, func() interface{} { return c.Check(1, checker, 2, myComment("Hello world!")) }) } func (s *HelpersS) TestCheckFailWithExpectedAndStaticComment(c *check.C) { checker := &MyChecker{result: false} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " // Nice leading comment\\.\n" + " return c\\.Check\\(1, checker, 2\\) // Hello there\n" + "\\.+ myobtained int = 1\n" + "\\.+ myexpected int = 2\n\n" testHelperFailure(c, "Check(1, checker, 2, msg)", false, false, log, func() interface{} { // Nice leading comment. return c.Check(1, checker, 2) // Hello there }) } func (s *HelpersS) TestCheckFailWithoutExpected(c *check.C) { checker := &MyChecker{result: false, info: &check.CheckerInfo{Params: []string{"myvalue"}}} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " return c\\.Check\\(1, checker\\)\n" + "\\.+ myvalue int = 1\n\n" testHelperFailure(c, "Check(1, checker)", false, false, log, func() interface{} { return c.Check(1, checker) }) } func (s *HelpersS) TestCheckFailWithoutExpectedAndMessage(c *check.C) { checker := &MyChecker{result: false, info: &check.CheckerInfo{Params: []string{"myvalue"}}} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " return c\\.Check\\(1, checker, myComment\\(\"Hello world!\"\\)\\)\n" + "\\.+ myvalue int = 1\n" + "\\.+ Hello world!\n\n" testHelperFailure(c, "Check(1, checker, msg)", false, false, log, func() interface{} { return c.Check(1, checker, myComment("Hello world!")) }) } func (s *HelpersS) TestCheckWithMissingExpected(c *check.C) { checker := &MyChecker{result: true} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " return c\\.Check\\(1, checker\\)\n" + "\\.+ Check\\(myobtained, MyChecker, myexpected\\):\n" + "\\.+ Wrong number of parameters for MyChecker: " + "want 3, got 2\n\n" testHelperFailure(c, "Check(1, checker, !?)", false, false, log, func() interface{} { return c.Check(1, checker) }) } func (s *HelpersS) TestCheckWithTooManyExpected(c *check.C) { checker := &MyChecker{result: true} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " return c\\.Check\\(1, checker, 2, 3\\)\n" + "\\.+ Check\\(myobtained, MyChecker, myexpected\\):\n" + "\\.+ Wrong number of parameters for MyChecker: " + "want 3, got 4\n\n" testHelperFailure(c, "Check(1, checker, 2, 3)", false, false, log, func() interface{} { return c.Check(1, checker, 2, 3) }) } func (s *HelpersS) TestCheckWithError(c *check.C) { checker := &MyChecker{result: false, error: "Some not so cool data provided!"} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " return c\\.Check\\(1, checker, 2\\)\n" + "\\.+ myobtained int = 1\n" + "\\.+ myexpected int = 2\n" + "\\.+ Some not so cool data provided!\n\n" testHelperFailure(c, "Check(1, checker, 2)", false, false, log, func() interface{} { return c.Check(1, checker, 2) }) } func (s *HelpersS) TestCheckWithNilChecker(c *check.C) { log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " return c\\.Check\\(1, nil\\)\n" + "\\.+ Check\\(obtained, nil!\\?, \\.\\.\\.\\):\n" + "\\.+ Oops\\.\\. you've provided a nil checker!\n\n" testHelperFailure(c, "Check(obtained, nil)", false, false, log, func() interface{} { return c.Check(1, nil) }) } func (s *HelpersS) TestCheckWithParamsAndNamesMutation(c *check.C) { checker := &MyChecker{result: false, params: []interface{}{3, 4}, names: []string{"newobtained", "newexpected"}} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " return c\\.Check\\(1, checker, 2\\)\n" + "\\.+ newobtained int = 3\n" + "\\.+ newexpected int = 4\n\n" testHelperFailure(c, "Check(1, checker, 2) with mutation", false, false, log, func() interface{} { return c.Check(1, checker, 2) }) } // ----------------------------------------------------------------------- // Tests for Assert(), mostly the same as for Check() above. func (s *HelpersS) TestAssertSucceedWithExpected(c *check.C) { checker := &MyChecker{result: true} testHelperSuccess(c, "Assert(1, checker, 2)", nil, func() interface{} { c.Assert(1, checker, 2) return nil }) if !reflect.DeepEqual(checker.params, []interface{}{1, 2}) { c.Fatalf("Bad params for check: %#v", checker.params) } } func (s *HelpersS) TestAssertSucceedWithoutExpected(c *check.C) { checker := &MyChecker{result: true, info: &check.CheckerInfo{Params: []string{"myvalue"}}} testHelperSuccess(c, "Assert(1, checker)", nil, func() interface{} { c.Assert(1, checker) return nil }) if !reflect.DeepEqual(checker.params, []interface{}{1}) { c.Fatalf("Bad params for check: %#v", checker.params) } } func (s *HelpersS) TestAssertFailWithExpected(c *check.C) { checker := &MyChecker{result: false} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " c\\.Assert\\(1, checker, 2\\)\n" + "\\.+ myobtained int = 1\n" + "\\.+ myexpected int = 2\n\n" testHelperFailure(c, "Assert(1, checker, 2)", nil, true, log, func() interface{} { c.Assert(1, checker, 2) return nil }) } func (s *HelpersS) TestAssertFailWithExpectedAndMessage(c *check.C) { checker := &MyChecker{result: false} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " c\\.Assert\\(1, checker, 2, myComment\\(\"Hello world!\"\\)\\)\n" + "\\.+ myobtained int = 1\n" + "\\.+ myexpected int = 2\n" + "\\.+ Hello world!\n\n" testHelperFailure(c, "Assert(1, checker, 2, msg)", nil, true, log, func() interface{} { c.Assert(1, checker, 2, myComment("Hello world!")) return nil }) } func (s *HelpersS) TestAssertFailWithoutExpected(c *check.C) { checker := &MyChecker{result: false, info: &check.CheckerInfo{Params: []string{"myvalue"}}} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " c\\.Assert\\(1, checker\\)\n" + "\\.+ myvalue int = 1\n\n" testHelperFailure(c, "Assert(1, checker)", nil, true, log, func() interface{} { c.Assert(1, checker) return nil }) } func (s *HelpersS) TestAssertFailWithoutExpectedAndMessage(c *check.C) { checker := &MyChecker{result: false, info: &check.CheckerInfo{Params: []string{"myvalue"}}} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " c\\.Assert\\(1, checker, myComment\\(\"Hello world!\"\\)\\)\n" + "\\.+ myvalue int = 1\n" + "\\.+ Hello world!\n\n" testHelperFailure(c, "Assert(1, checker, msg)", nil, true, log, func() interface{} { c.Assert(1, checker, myComment("Hello world!")) return nil }) } func (s *HelpersS) TestAssertWithMissingExpected(c *check.C) { checker := &MyChecker{result: true} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " c\\.Assert\\(1, checker\\)\n" + "\\.+ Assert\\(myobtained, MyChecker, myexpected\\):\n" + "\\.+ Wrong number of parameters for MyChecker: " + "want 3, got 2\n\n" testHelperFailure(c, "Assert(1, checker, !?)", nil, true, log, func() interface{} { c.Assert(1, checker) return nil }) } func (s *HelpersS) TestAssertWithError(c *check.C) { checker := &MyChecker{result: false, error: "Some not so cool data provided!"} log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " c\\.Assert\\(1, checker, 2\\)\n" + "\\.+ myobtained int = 1\n" + "\\.+ myexpected int = 2\n" + "\\.+ Some not so cool data provided!\n\n" testHelperFailure(c, "Assert(1, checker, 2)", nil, true, log, func() interface{} { c.Assert(1, checker, 2) return nil }) } func (s *HelpersS) TestAssertWithNilChecker(c *check.C) { log := "(?s)helpers_test\\.go:[0-9]+:.*\nhelpers_test\\.go:[0-9]+:\n" + " c\\.Assert\\(1, nil\\)\n" + "\\.+ Assert\\(obtained, nil!\\?, \\.\\.\\.\\):\n" + "\\.+ Oops\\.\\. you've provided a nil checker!\n\n" testHelperFailure(c, "Assert(obtained, nil)", nil, true, log, func() interface{} { c.Assert(1, nil) return nil }) } // ----------------------------------------------------------------------- // Ensure that values logged work properly in some interesting cases. func (s *HelpersS) TestValueLoggingWithArrays(c *check.C) { checker := &MyChecker{result: false} log := "(?s)helpers_test.go:[0-9]+:.*\nhelpers_test.go:[0-9]+:\n" + " return c\\.Check\\(\\[\\]byte{1, 2}, checker, \\[\\]byte{1, 3}\\)\n" + "\\.+ myobtained \\[\\]uint8 = \\[\\]byte{0x1, 0x2}\n" + "\\.+ myexpected \\[\\]uint8 = \\[\\]byte{0x1, 0x3}\n\n" testHelperFailure(c, "Check([]byte{1}, chk, []byte{3})", false, false, log, func() interface{} { return c.Check([]byte{1, 2}, checker, []byte{1, 3}) }) } func (s *HelpersS) TestValueLoggingWithMultiLine(c *check.C) { checker := &MyChecker{result: false} log := "(?s)helpers_test.go:[0-9]+:.*\nhelpers_test.go:[0-9]+:\n" + " return c\\.Check\\(\"a\\\\nb\\\\n\", checker, \"a\\\\nb\\\\nc\"\\)\n" + "\\.+ myobtained string = \"\" \\+\n" + "\\.+ \"a\\\\n\" \\+\n" + "\\.+ \"b\\\\n\"\n" + "\\.+ myexpected string = \"\" \\+\n" + "\\.+ \"a\\\\n\" \\+\n" + "\\.+ \"b\\\\n\" \\+\n" + "\\.+ \"c\"\n\n" testHelperFailure(c, `Check("a\nb\n", chk, "a\nb\nc")`, false, false, log, func() interface{} { return c.Check("a\nb\n", checker, "a\nb\nc") }) } func (s *HelpersS) TestValueLoggingWithMultiLineException(c *check.C) { // If the newline is at the end of the string, don't log as multi-line. checker := &MyChecker{result: false} log := "(?s)helpers_test.go:[0-9]+:.*\nhelpers_test.go:[0-9]+:\n" + " return c\\.Check\\(\"a b\\\\n\", checker, \"a\\\\nb\"\\)\n" + "\\.+ myobtained string = \"a b\\\\n\"\n" + "\\.+ myexpected string = \"\" \\+\n" + "\\.+ \"a\\\\n\" \\+\n" + "\\.+ \"b\"\n\n" testHelperFailure(c, `Check("a b\n", chk, "a\nb")`, false, false, log, func() interface{} { return c.Check("a b\n", checker, "a\nb") }) } // ----------------------------------------------------------------------- // MakeDir() tests. type MkDirHelper struct { path1 string path2 string isDir1 bool isDir2 bool isDir3 bool isDir4 bool } func (s *MkDirHelper) SetUpSuite(c *check.C) { s.path1 = c.MkDir() s.isDir1 = isDir(s.path1) } func (s *MkDirHelper) Test(c *check.C) { s.path2 = c.MkDir() s.isDir2 = isDir(s.path2) } func (s *MkDirHelper) TearDownSuite(c *check.C) { s.isDir3 = isDir(s.path1) s.isDir4 = isDir(s.path2) } func (s *HelpersS) TestMkDir(c *check.C) { helper := MkDirHelper{} output := String{} check.Run(&helper, &check.RunConf{Output: &output}) c.Assert(output.value, check.Equals, "") c.Check(helper.isDir1, check.Equals, true) c.Check(helper.isDir2, check.Equals, true) c.Check(helper.isDir3, check.Equals, true) c.Check(helper.isDir4, check.Equals, true) c.Check(helper.path1, check.Not(check.Equals), helper.path2) c.Check(isDir(helper.path1), check.Equals, false) c.Check(isDir(helper.path2), check.Equals, false) } func isDir(path string) bool { if stat, err := os.Stat(path); err == nil { return stat.IsDir() } return false } // Concurrent logging should not corrupt the underling buffer. // Use go test -race to detect the race in this test. func (s *HelpersS) TestConcurrentLogging(c *check.C) { defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(runtime.NumCPU())) var start, stop sync.WaitGroup start.Add(1) for i, n := 0, runtime.NumCPU()*2; i < n; i++ { stop.Add(1) go func(i int) { start.Wait() for j := 0; j < 30; j++ { c.Logf("Worker %d: line %d", i, j) } stop.Done() }(i) } start.Done() stop.Wait() } // ----------------------------------------------------------------------- // Test the TestName function type TestNameHelper struct { name1 string name2 string name3 string name4 string name5 string } func (s *TestNameHelper) SetUpSuite(c *check.C) { s.name1 = c.TestName() } func (s *TestNameHelper) SetUpTest(c *check.C) { s.name2 = c.TestName() } func (s *TestNameHelper) Test(c *check.C) { s.name3 = c.TestName() } func (s *TestNameHelper) TearDownTest(c *check.C) { s.name4 = c.TestName() } func (s *TestNameHelper) TearDownSuite(c *check.C) { s.name5 = c.TestName() } func (s *HelpersS) TestTestName(c *check.C) { helper := TestNameHelper{} output := String{} check.Run(&helper, &check.RunConf{Output: &output}) c.Check(helper.name1, check.Equals, "") c.Check(helper.name2, check.Equals, "TestNameHelper.Test") c.Check(helper.name3, check.Equals, "TestNameHelper.Test") c.Check(helper.name4, check.Equals, "TestNameHelper.Test") c.Check(helper.name5, check.Equals, "") } // ----------------------------------------------------------------------- // A couple of helper functions to test helper functions. :-) func testHelperSuccess(c *check.C, name string, expectedResult interface{}, closure func() interface{}) { var result interface{} defer (func() { if err := recover(); err != nil { panic(err) } checkState(c, result, &expectedState{ name: name, result: expectedResult, failed: false, log: "", }) })() result = closure() } func testHelperFailure(c *check.C, name string, expectedResult interface{}, shouldStop bool, log string, closure func() interface{}) { var result interface{} defer (func() { if err := recover(); err != nil { panic(err) } checkState(c, result, &expectedState{ name: name, result: expectedResult, failed: true, log: log, }) })() result = closure() if shouldStop { c.Logf("%s didn't stop when it should", name) } } go-gir-generator-master/vendor/src/gopkg.in/check.v1/printer.go000066400000000000000000000073651414263242200247460ustar00rootroot00000000000000package check import ( "bytes" "go/ast" "go/parser" "go/printer" "go/token" "os" ) func indent(s, with string) (r string) { eol := true for i := 0; i != len(s); i++ { c := s[i] switch { case eol && c == '\n' || c == '\r': case c == '\n' || c == '\r': eol = true case eol: eol = false s = s[:i] + with + s[i:] i += len(with) } } return s } func printLine(filename string, line int) (string, error) { fset := token.NewFileSet() file, err := os.Open(filename) if err != nil { return "", err } fnode, err := parser.ParseFile(fset, filename, file, parser.ParseComments) if err != nil { return "", err } config := &printer.Config{Mode: printer.UseSpaces, Tabwidth: 4} lp := &linePrinter{fset: fset, fnode: fnode, line: line, config: config} ast.Walk(lp, fnode) result := lp.output.Bytes() // Comments leave \n at the end. n := len(result) for n > 0 && result[n-1] == '\n' { n-- } return string(result[:n]), nil } type linePrinter struct { config *printer.Config fset *token.FileSet fnode *ast.File line int output bytes.Buffer stmt ast.Stmt } func (lp *linePrinter) emit() bool { if lp.stmt != nil { lp.trim(lp.stmt) lp.printWithComments(lp.stmt) lp.stmt = nil return true } return false } func (lp *linePrinter) printWithComments(n ast.Node) { nfirst := lp.fset.Position(n.Pos()).Line nlast := lp.fset.Position(n.End()).Line for _, g := range lp.fnode.Comments { cfirst := lp.fset.Position(g.Pos()).Line clast := lp.fset.Position(g.End()).Line if clast == nfirst-1 && lp.fset.Position(n.Pos()).Column == lp.fset.Position(g.Pos()).Column { for _, c := range g.List { lp.output.WriteString(c.Text) lp.output.WriteByte('\n') } } if cfirst >= nfirst && cfirst <= nlast && n.End() <= g.List[0].Slash { // The printer will not include the comment if it starts past // the node itself. Trick it into printing by overlapping the // slash with the end of the statement. g.List[0].Slash = n.End() - 1 } } node := &printer.CommentedNode{n, lp.fnode.Comments} lp.config.Fprint(&lp.output, lp.fset, node) } func (lp *linePrinter) Visit(n ast.Node) (w ast.Visitor) { if n == nil { if lp.output.Len() == 0 { lp.emit() } return nil } first := lp.fset.Position(n.Pos()).Line last := lp.fset.Position(n.End()).Line if first <= lp.line && last >= lp.line { // Print the innermost statement containing the line. if stmt, ok := n.(ast.Stmt); ok { if _, ok := n.(*ast.BlockStmt); !ok { lp.stmt = stmt } } if first == lp.line && lp.emit() { return nil } return lp } return nil } func (lp *linePrinter) trim(n ast.Node) bool { stmt, ok := n.(ast.Stmt) if !ok { return true } line := lp.fset.Position(n.Pos()).Line if line != lp.line { return false } switch stmt := stmt.(type) { case *ast.IfStmt: stmt.Body = lp.trimBlock(stmt.Body) case *ast.SwitchStmt: stmt.Body = lp.trimBlock(stmt.Body) case *ast.TypeSwitchStmt: stmt.Body = lp.trimBlock(stmt.Body) case *ast.CaseClause: stmt.Body = lp.trimList(stmt.Body) case *ast.CommClause: stmt.Body = lp.trimList(stmt.Body) case *ast.BlockStmt: stmt.List = lp.trimList(stmt.List) } return true } func (lp *linePrinter) trimBlock(stmt *ast.BlockStmt) *ast.BlockStmt { if !lp.trim(stmt) { return lp.emptyBlock(stmt) } stmt.Rbrace = stmt.Lbrace return stmt } func (lp *linePrinter) trimList(stmts []ast.Stmt) []ast.Stmt { for i := 0; i != len(stmts); i++ { if !lp.trim(stmts[i]) { stmts[i] = lp.emptyStmt(stmts[i]) break } } return stmts } func (lp *linePrinter) emptyStmt(n ast.Node) *ast.ExprStmt { return &ast.ExprStmt{&ast.Ellipsis{n.Pos(), nil}} } func (lp *linePrinter) emptyBlock(n ast.Node) *ast.BlockStmt { p := n.Pos() return &ast.BlockStmt{p, []ast.Stmt{lp.emptyStmt(n)}, p} } go-gir-generator-master/vendor/src/gopkg.in/check.v1/printer_test.go000066400000000000000000000046261414263242200260020ustar00rootroot00000000000000package check_test import ( . "gopkg.in/check.v1" ) var _ = Suite(&PrinterS{}) type PrinterS struct{} func (s *PrinterS) TestCountSuite(c *C) { suitesRun += 1 } var printTestFuncLine int func init() { printTestFuncLine = getMyLine() + 3 } func printTestFunc() { println(1) // Comment1 if 2 == 2 { // Comment2 println(3) // Comment3 } switch 5 { case 6: println(6) // Comment6 println(7) } switch interface{}(9).(type) {// Comment9 case int: println(10) println(11) } select { case <-(chan bool)(nil): println(14) println(15) default: println(16) println(17) } println(19, 20) _ = func() { println(21) println(22) } println(24, func() { println(25) }) // Leading comment // with multiple lines. println(29) // Comment29 } var printLineTests = []struct { line int output string }{ {1, "println(1) // Comment1"}, {2, "if 2 == 2 { // Comment2\n ...\n}"}, {3, "println(3) // Comment3"}, {5, "switch 5 {\n...\n}"}, {6, "case 6:\n println(6) // Comment6\n ..."}, {7, "println(7)"}, {9, "switch interface{}(9).(type) { // Comment9\n...\n}"}, {10, "case int:\n println(10)\n ..."}, {14, "case <-(chan bool)(nil):\n println(14)\n ..."}, {15, "println(15)"}, {16, "default:\n println(16)\n ..."}, {17, "println(17)"}, {19, "println(19,\n 20)"}, {20, "println(19,\n 20)"}, {21, "_ = func() {\n println(21)\n println(22)\n}"}, {22, "println(22)"}, {24, "println(24, func() {\n println(25)\n})"}, {25, "println(25)"}, {26, "println(24, func() {\n println(25)\n})"}, {29, "// Leading comment\n// with multiple lines.\nprintln(29) // Comment29"}, } func (s *PrinterS) TestPrintLine(c *C) { for _, test := range printLineTests { output, err := PrintLine("printer_test.go", printTestFuncLine+test.line) c.Assert(err, IsNil) c.Assert(output, Equals, test.output) } } var indentTests = []struct { in, out string }{ {"", ""}, {"\n", "\n"}, {"a", ">>>a"}, {"a\n", ">>>a\n"}, {"a\nb", ">>>a\n>>>b"}, {" ", ">>> "}, } func (s *PrinterS) TestIndent(c *C) { for _, test := range indentTests { out := Indent(test.in, ">>>") c.Assert(out, Equals, test.out) } } go-gir-generator-master/vendor/src/gopkg.in/check.v1/run.go000066400000000000000000000125261414263242200240620ustar00rootroot00000000000000package check import ( "bufio" "flag" "fmt" "os" "testing" "time" ) // ----------------------------------------------------------------------- // Test suite registry. var allSuites []interface{} // Suite registers the given value as a test suite to be run. Any methods // starting with the Test prefix in the given value will be considered as // a test method. func Suite(suite interface{}) interface{} { allSuites = append(allSuites, suite) return suite } // ----------------------------------------------------------------------- // Public running interface. var ( oldFilterFlag = flag.String("gocheck.f", "", "Regular expression selecting which tests and/or suites to run") oldVerboseFlag = flag.Bool("gocheck.v", false, "Verbose mode") oldStreamFlag = flag.Bool("gocheck.vv", false, "Super verbose mode (disables output caching)") oldBenchFlag = flag.Bool("gocheck.b", false, "Run benchmarks") oldBenchTime = flag.Duration("gocheck.btime", 1*time.Second, "approximate run time for each benchmark") oldListFlag = flag.Bool("gocheck.list", false, "List the names of all tests that will be run") oldWorkFlag = flag.Bool("gocheck.work", false, "Display and do not remove the test working directory") newFilterFlag = flag.String("check.f", "", "Regular expression selecting which tests and/or suites to run") newVerboseFlag = flag.Bool("check.v", false, "Verbose mode") newStreamFlag = flag.Bool("check.vv", false, "Super verbose mode (disables output caching)") newBenchFlag = flag.Bool("check.b", false, "Run benchmarks") newBenchTime = flag.Duration("check.btime", 1*time.Second, "approximate run time for each benchmark") newBenchMem = flag.Bool("check.bmem", false, "Report memory benchmarks") newListFlag = flag.Bool("check.list", false, "List the names of all tests that will be run") newWorkFlag = flag.Bool("check.work", false, "Display and do not remove the test working directory") ) // TestingT runs all test suites registered with the Suite function, // printing results to stdout, and reporting any failures back to // the "testing" package. func TestingT(testingT *testing.T) { benchTime := *newBenchTime if benchTime == 1*time.Second { benchTime = *oldBenchTime } conf := &RunConf{ Filter: *oldFilterFlag + *newFilterFlag, Verbose: *oldVerboseFlag || *newVerboseFlag, Stream: *oldStreamFlag || *newStreamFlag, Benchmark: *oldBenchFlag || *newBenchFlag, BenchmarkTime: benchTime, BenchmarkMem: *newBenchMem, KeepWorkDir: *oldWorkFlag || *newWorkFlag, } if *oldListFlag || *newListFlag { w := bufio.NewWriter(os.Stdout) for _, name := range ListAll(conf) { fmt.Fprintln(w, name) } w.Flush() return } result := RunAll(conf) println(result.String()) if !result.Passed() { testingT.Fail() } } // RunAll runs all test suites registered with the Suite function, using the // provided run configuration. func RunAll(runConf *RunConf) *Result { result := Result{} for _, suite := range allSuites { result.Add(Run(suite, runConf)) } return &result } // Run runs the provided test suite using the provided run configuration. func Run(suite interface{}, runConf *RunConf) *Result { runner := newSuiteRunner(suite, runConf) return runner.run() } // ListAll returns the names of all the test functions registered with the // Suite function that will be run with the provided run configuration. func ListAll(runConf *RunConf) []string { var names []string for _, suite := range allSuites { names = append(names, List(suite, runConf)...) } return names } // List returns the names of the test functions in the given // suite that will be run with the provided run configuration. func List(suite interface{}, runConf *RunConf) []string { var names []string runner := newSuiteRunner(suite, runConf) for _, t := range runner.tests { names = append(names, t.String()) } return names } // ----------------------------------------------------------------------- // Result methods. func (r *Result) Add(other *Result) { r.Succeeded += other.Succeeded r.Skipped += other.Skipped r.Failed += other.Failed r.Panicked += other.Panicked r.FixturePanicked += other.FixturePanicked r.ExpectedFailures += other.ExpectedFailures r.Missed += other.Missed if r.WorkDir != "" && other.WorkDir != "" { r.WorkDir += ":" + other.WorkDir } else if other.WorkDir != "" { r.WorkDir = other.WorkDir } } func (r *Result) Passed() bool { return (r.Failed == 0 && r.Panicked == 0 && r.FixturePanicked == 0 && r.Missed == 0 && r.RunError == nil) } func (r *Result) String() string { if r.RunError != nil { return "ERROR: " + r.RunError.Error() } var value string if r.Failed == 0 && r.Panicked == 0 && r.FixturePanicked == 0 && r.Missed == 0 { value = "OK: " } else { value = "OOPS: " } value += fmt.Sprintf("%d passed", r.Succeeded) if r.Skipped != 0 { value += fmt.Sprintf(", %d skipped", r.Skipped) } if r.ExpectedFailures != 0 { value += fmt.Sprintf(", %d expected failures", r.ExpectedFailures) } if r.Failed != 0 { value += fmt.Sprintf(", %d FAILED", r.Failed) } if r.Panicked != 0 { value += fmt.Sprintf(", %d PANICKED", r.Panicked) } if r.FixturePanicked != 0 { value += fmt.Sprintf(", %d FIXTURE-PANICKED", r.FixturePanicked) } if r.Missed != 0 { value += fmt.Sprintf(", %d MISSED", r.Missed) } if r.WorkDir != "" { value += "\nWORK=" + r.WorkDir } return value } go-gir-generator-master/vendor/src/gopkg.in/check.v1/run_test.go000066400000000000000000000302571414263242200251220ustar00rootroot00000000000000// These tests verify the test running logic. package check_test import ( "errors" . "gopkg.in/check.v1" "os" "sync" ) var runnerS = Suite(&RunS{}) type RunS struct{} func (s *RunS) TestCountSuite(c *C) { suitesRun += 1 } // ----------------------------------------------------------------------- // Tests ensuring result counting works properly. func (s *RunS) TestSuccess(c *C) { output := String{} result := Run(&SuccessHelper{}, &RunConf{Output: &output}) c.Check(result.Succeeded, Equals, 1) c.Check(result.Failed, Equals, 0) c.Check(result.Skipped, Equals, 0) c.Check(result.Panicked, Equals, 0) c.Check(result.FixturePanicked, Equals, 0) c.Check(result.Missed, Equals, 0) c.Check(result.RunError, IsNil) } func (s *RunS) TestFailure(c *C) { output := String{} result := Run(&FailHelper{}, &RunConf{Output: &output}) c.Check(result.Succeeded, Equals, 0) c.Check(result.Failed, Equals, 1) c.Check(result.Skipped, Equals, 0) c.Check(result.Panicked, Equals, 0) c.Check(result.FixturePanicked, Equals, 0) c.Check(result.Missed, Equals, 0) c.Check(result.RunError, IsNil) } func (s *RunS) TestFixture(c *C) { output := String{} result := Run(&FixtureHelper{}, &RunConf{Output: &output}) c.Check(result.Succeeded, Equals, 2) c.Check(result.Failed, Equals, 0) c.Check(result.Skipped, Equals, 0) c.Check(result.Panicked, Equals, 0) c.Check(result.FixturePanicked, Equals, 0) c.Check(result.Missed, Equals, 0) c.Check(result.RunError, IsNil) } func (s *RunS) TestPanicOnTest(c *C) { output := String{} helper := &FixtureHelper{panicOn: "Test1"} result := Run(helper, &RunConf{Output: &output}) c.Check(result.Succeeded, Equals, 1) c.Check(result.Failed, Equals, 0) c.Check(result.Skipped, Equals, 0) c.Check(result.Panicked, Equals, 1) c.Check(result.FixturePanicked, Equals, 0) c.Check(result.Missed, Equals, 0) c.Check(result.RunError, IsNil) } func (s *RunS) TestPanicOnSetUpTest(c *C) { output := String{} helper := &FixtureHelper{panicOn: "SetUpTest"} result := Run(helper, &RunConf{Output: &output}) c.Check(result.Succeeded, Equals, 0) c.Check(result.Failed, Equals, 0) c.Check(result.Skipped, Equals, 0) c.Check(result.Panicked, Equals, 0) c.Check(result.FixturePanicked, Equals, 1) c.Check(result.Missed, Equals, 2) c.Check(result.RunError, IsNil) } func (s *RunS) TestPanicOnSetUpSuite(c *C) { output := String{} helper := &FixtureHelper{panicOn: "SetUpSuite"} result := Run(helper, &RunConf{Output: &output}) c.Check(result.Succeeded, Equals, 0) c.Check(result.Failed, Equals, 0) c.Check(result.Skipped, Equals, 0) c.Check(result.Panicked, Equals, 0) c.Check(result.FixturePanicked, Equals, 1) c.Check(result.Missed, Equals, 2) c.Check(result.RunError, IsNil) } // ----------------------------------------------------------------------- // Check result aggregation. func (s *RunS) TestAdd(c *C) { result := &Result{ Succeeded: 1, Skipped: 2, Failed: 3, Panicked: 4, FixturePanicked: 5, Missed: 6, ExpectedFailures: 7, } result.Add(&Result{ Succeeded: 10, Skipped: 20, Failed: 30, Panicked: 40, FixturePanicked: 50, Missed: 60, ExpectedFailures: 70, }) c.Check(result.Succeeded, Equals, 11) c.Check(result.Skipped, Equals, 22) c.Check(result.Failed, Equals, 33) c.Check(result.Panicked, Equals, 44) c.Check(result.FixturePanicked, Equals, 55) c.Check(result.Missed, Equals, 66) c.Check(result.ExpectedFailures, Equals, 77) c.Check(result.RunError, IsNil) } // ----------------------------------------------------------------------- // Check the Passed() method. func (s *RunS) TestPassed(c *C) { c.Assert((&Result{}).Passed(), Equals, true) c.Assert((&Result{Succeeded: 1}).Passed(), Equals, true) c.Assert((&Result{Skipped: 1}).Passed(), Equals, true) c.Assert((&Result{Failed: 1}).Passed(), Equals, false) c.Assert((&Result{Panicked: 1}).Passed(), Equals, false) c.Assert((&Result{FixturePanicked: 1}).Passed(), Equals, false) c.Assert((&Result{Missed: 1}).Passed(), Equals, false) c.Assert((&Result{RunError: errors.New("!")}).Passed(), Equals, false) } // ----------------------------------------------------------------------- // Check that result printing is working correctly. func (s *RunS) TestPrintSuccess(c *C) { result := &Result{Succeeded: 5} c.Check(result.String(), Equals, "OK: 5 passed") } func (s *RunS) TestPrintFailure(c *C) { result := &Result{Failed: 5} c.Check(result.String(), Equals, "OOPS: 0 passed, 5 FAILED") } func (s *RunS) TestPrintSkipped(c *C) { result := &Result{Skipped: 5} c.Check(result.String(), Equals, "OK: 0 passed, 5 skipped") } func (s *RunS) TestPrintExpectedFailures(c *C) { result := &Result{ExpectedFailures: 5} c.Check(result.String(), Equals, "OK: 0 passed, 5 expected failures") } func (s *RunS) TestPrintPanicked(c *C) { result := &Result{Panicked: 5} c.Check(result.String(), Equals, "OOPS: 0 passed, 5 PANICKED") } func (s *RunS) TestPrintFixturePanicked(c *C) { result := &Result{FixturePanicked: 5} c.Check(result.String(), Equals, "OOPS: 0 passed, 5 FIXTURE-PANICKED") } func (s *RunS) TestPrintMissed(c *C) { result := &Result{Missed: 5} c.Check(result.String(), Equals, "OOPS: 0 passed, 5 MISSED") } func (s *RunS) TestPrintAll(c *C) { result := &Result{Succeeded: 1, Skipped: 2, ExpectedFailures: 3, Panicked: 4, FixturePanicked: 5, Missed: 6} c.Check(result.String(), Equals, "OOPS: 1 passed, 2 skipped, 3 expected failures, 4 PANICKED, "+ "5 FIXTURE-PANICKED, 6 MISSED") } func (s *RunS) TestPrintRunError(c *C) { result := &Result{Succeeded: 1, Failed: 1, RunError: errors.New("Kaboom!")} c.Check(result.String(), Equals, "ERROR: Kaboom!") } // ----------------------------------------------------------------------- // Verify that the method pattern flag works correctly. func (s *RunS) TestFilterTestName(c *C) { helper := FixtureHelper{} output := String{} runConf := RunConf{Output: &output, Filter: "Test[91]"} Run(&helper, &runConf) c.Check(helper.calls[0], Equals, "SetUpSuite") c.Check(helper.calls[1], Equals, "SetUpTest") c.Check(helper.calls[2], Equals, "Test1") c.Check(helper.calls[3], Equals, "TearDownTest") c.Check(helper.calls[4], Equals, "TearDownSuite") c.Check(len(helper.calls), Equals, 5) } func (s *RunS) TestFilterTestNameWithAll(c *C) { helper := FixtureHelper{} output := String{} runConf := RunConf{Output: &output, Filter: ".*"} Run(&helper, &runConf) c.Check(helper.calls[0], Equals, "SetUpSuite") c.Check(helper.calls[1], Equals, "SetUpTest") c.Check(helper.calls[2], Equals, "Test1") c.Check(helper.calls[3], Equals, "TearDownTest") c.Check(helper.calls[4], Equals, "SetUpTest") c.Check(helper.calls[5], Equals, "Test2") c.Check(helper.calls[6], Equals, "TearDownTest") c.Check(helper.calls[7], Equals, "TearDownSuite") c.Check(len(helper.calls), Equals, 8) } func (s *RunS) TestFilterSuiteName(c *C) { helper := FixtureHelper{} output := String{} runConf := RunConf{Output: &output, Filter: "FixtureHelper"} Run(&helper, &runConf) c.Check(helper.calls[0], Equals, "SetUpSuite") c.Check(helper.calls[1], Equals, "SetUpTest") c.Check(helper.calls[2], Equals, "Test1") c.Check(helper.calls[3], Equals, "TearDownTest") c.Check(helper.calls[4], Equals, "SetUpTest") c.Check(helper.calls[5], Equals, "Test2") c.Check(helper.calls[6], Equals, "TearDownTest") c.Check(helper.calls[7], Equals, "TearDownSuite") c.Check(len(helper.calls), Equals, 8) } func (s *RunS) TestFilterSuiteNameAndTestName(c *C) { helper := FixtureHelper{} output := String{} runConf := RunConf{Output: &output, Filter: "FixtureHelper\\.Test2"} Run(&helper, &runConf) c.Check(helper.calls[0], Equals, "SetUpSuite") c.Check(helper.calls[1], Equals, "SetUpTest") c.Check(helper.calls[2], Equals, "Test2") c.Check(helper.calls[3], Equals, "TearDownTest") c.Check(helper.calls[4], Equals, "TearDownSuite") c.Check(len(helper.calls), Equals, 5) } func (s *RunS) TestFilterAllOut(c *C) { helper := FixtureHelper{} output := String{} runConf := RunConf{Output: &output, Filter: "NotFound"} Run(&helper, &runConf) c.Check(len(helper.calls), Equals, 0) } func (s *RunS) TestRequirePartialMatch(c *C) { helper := FixtureHelper{} output := String{} runConf := RunConf{Output: &output, Filter: "est"} Run(&helper, &runConf) c.Check(len(helper.calls), Equals, 8) } func (s *RunS) TestFilterError(c *C) { helper := FixtureHelper{} output := String{} runConf := RunConf{Output: &output, Filter: "]["} result := Run(&helper, &runConf) c.Check(result.String(), Equals, "ERROR: Bad filter expression: error parsing regexp: missing closing ]: `[`") c.Check(len(helper.calls), Equals, 0) } // ----------------------------------------------------------------------- // Verify that List works correctly. func (s *RunS) TestListFiltered(c *C) { names := List(&FixtureHelper{}, &RunConf{Filter: "1"}) c.Assert(names, DeepEquals, []string{ "FixtureHelper.Test1", }) } func (s *RunS) TestList(c *C) { names := List(&FixtureHelper{}, &RunConf{}) c.Assert(names, DeepEquals, []string{ "FixtureHelper.Test1", "FixtureHelper.Test2", }) } // ----------------------------------------------------------------------- // Verify that verbose mode prints tests which pass as well. func (s *RunS) TestVerboseMode(c *C) { helper := FixtureHelper{} output := String{} runConf := RunConf{Output: &output, Verbose: true} Run(&helper, &runConf) expected := "PASS: check_test\\.go:[0-9]+: FixtureHelper\\.Test1\t *[.0-9]+s\n" + "PASS: check_test\\.go:[0-9]+: FixtureHelper\\.Test2\t *[.0-9]+s\n" c.Assert(output.value, Matches, expected) } func (s *RunS) TestVerboseModeWithFailBeforePass(c *C) { helper := FixtureHelper{panicOn: "Test1"} output := String{} runConf := RunConf{Output: &output, Verbose: true} Run(&helper, &runConf) expected := "(?s).*PANIC.*\n-+\n" + // Should have an extra line. "PASS: check_test\\.go:[0-9]+: FixtureHelper\\.Test2\t *[.0-9]+s\n" c.Assert(output.value, Matches, expected) } // ----------------------------------------------------------------------- // Verify the stream output mode. In this mode there's no output caching. type StreamHelper struct { l2 sync.Mutex l3 sync.Mutex } func (s *StreamHelper) SetUpSuite(c *C) { c.Log("0") } func (s *StreamHelper) Test1(c *C) { c.Log("1") s.l2.Lock() s.l3.Lock() go func() { s.l2.Lock() // Wait for "2". c.Log("3") s.l3.Unlock() }() } func (s *StreamHelper) Test2(c *C) { c.Log("2") s.l2.Unlock() s.l3.Lock() // Wait for "3". c.Fail() c.Log("4") } func (s *RunS) TestStreamMode(c *C) { helper := &StreamHelper{} output := String{} runConf := RunConf{Output: &output, Stream: true} Run(helper, &runConf) expected := "START: run_test\\.go:[0-9]+: StreamHelper\\.SetUpSuite\n0\n" + "PASS: run_test\\.go:[0-9]+: StreamHelper\\.SetUpSuite\t *[.0-9]+s\n\n" + "START: run_test\\.go:[0-9]+: StreamHelper\\.Test1\n1\n" + "PASS: run_test\\.go:[0-9]+: StreamHelper\\.Test1\t *[.0-9]+s\n\n" + "START: run_test\\.go:[0-9]+: StreamHelper\\.Test2\n2\n3\n4\n" + "FAIL: run_test\\.go:[0-9]+: StreamHelper\\.Test2\n\n" c.Assert(output.value, Matches, expected) } type StreamMissHelper struct{} func (s *StreamMissHelper) SetUpSuite(c *C) { c.Log("0") c.Fail() } func (s *StreamMissHelper) Test1(c *C) { c.Log("1") } func (s *RunS) TestStreamModeWithMiss(c *C) { helper := &StreamMissHelper{} output := String{} runConf := RunConf{Output: &output, Stream: true} Run(helper, &runConf) expected := "START: run_test\\.go:[0-9]+: StreamMissHelper\\.SetUpSuite\n0\n" + "FAIL: run_test\\.go:[0-9]+: StreamMissHelper\\.SetUpSuite\n\n" + "START: run_test\\.go:[0-9]+: StreamMissHelper\\.Test1\n" + "MISS: run_test\\.go:[0-9]+: StreamMissHelper\\.Test1\n\n" c.Assert(output.value, Matches, expected) } // ----------------------------------------------------------------------- // Verify that that the keep work dir request indeed does so. type WorkDirSuite struct {} func (s *WorkDirSuite) Test(c *C) { c.MkDir() } func (s *RunS) TestKeepWorkDir(c *C) { output := String{} runConf := RunConf{Output: &output, Verbose: true, KeepWorkDir: true} result := Run(&WorkDirSuite{}, &runConf) c.Assert(result.String(), Matches, ".*\nWORK=" + result.WorkDir) stat, err := os.Stat(result.WorkDir) c.Assert(err, IsNil) c.Assert(stat.IsDir(), Equals, true) }