ibus-unikey-0.7.0~beta1/0000775000175000017500000000000013441506611014446 5ustar gunnargunnaribus-unikey-0.7.0~beta1/LICENSE0000664000175000017500000010451313441506611015457 0ustar gunnargunnar 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 . ibus-unikey-0.7.0~beta1/cmake/0000775000175000017500000000000013441506611015526 5ustar gunnargunnaribus-unikey-0.7.0~beta1/cmake/GSettings.cmake0000664000175000017500000000674513441506611020453 0ustar gunnargunnar# GSettings.cmake # Originally based on CMake macros written for Marlin # Updated by Yorba for newer versions of GLib. # # NOTE: This module does an in-place compilation of GSettings; the # resulting gschemas.compiled file will end up in the same # source folder as the original schema(s). option(GSETTINGS_COMPILE "Compile GSettings schemas. Can be disabled for packaging reasons." ON) option(GSETTINGS_COMPILE_IN_PLACE "Compile GSettings schemas in the build folder. This is used for running an appliction without installing the GSettings systemwide. The application will need to set GSETTINGS_SCHEMA_DIR" ON) include(GNUInstallDirs) if (GSETTINGS_COMPILE) message(STATUS "GSettings schemas will be compiled.") endif () if (GSETTINGS_COMPILE_IN_PLACE) message(STATUS "GSettings schemas will be compiled in-place.") endif () macro(add_schemas GSETTINGS_TARGET SCHEMA_DIRECTORY PREFIX) find_package(PkgConfig) # Locate all schema files. file(GLOB all_schema_files "${SCHEMA_DIRECTORY}/*.gschema.xml" ) if ("${PREFIX}" STREQUAL "") # Find the GLib path for schema installation execute_process( COMMAND ${PKG_CONFIG_EXECUTABLE} glib-2.0 --variable prefix OUTPUT_VARIABLE _glib_prefix OUTPUT_STRIP_TRAILING_WHITESPACE ) else () set(_glib_prefix ${PREFIX}) endif () set(GSETTINGS_DIR "${_glib_prefix}/share/glib-2.0/schemas/" CACHE INTERNAL "") # Fetch path for schema compiler from pkg-config execute_process( COMMAND ${PKG_CONFIG_EXECUTABLE} gio-2.0 --variable glib_compile_schemas OUTPUT_VARIABLE _glib_compile_schemas OUTPUT_STRIP_TRAILING_WHITESPACE ) set(glib_schema_compiler ${_glib_compile_schemas} CACHE INTERNAL "") if (GSETTINGS_COMPILE_IN_PLACE) set(COMPILE_IN_PLACE_DIR ${CMAKE_BINARY_DIR}/gsettings) add_custom_command( TARGET ${GSETTINGS_TARGET} COMMAND ${CMAKE_COMMAND} -E make_directory "${COMPILE_IN_PLACE_DIR}" ) # Copy all schemas to the build folder. foreach(schema_file ${all_schema_files}) add_custom_command( TARGET ${GSETTINGS_TARGET} COMMAND ${CMAKE_COMMAND} -E copy "${schema_file}" "${COMPILE_IN_PLACE_DIR}" COMMENT "Copying schema ${schema_file} to ${COMPILE_IN_PLACE_DIR}" ) endforeach() # Compile schema in-place. add_custom_command( TARGET ${GSETTINGS_TARGET} COMMAND ${glib_schema_compiler} ${COMPILE_IN_PLACE_DIR} COMMENT "Compiling schemas in folder: ${COMPILE_IN_PLACE_DIR}" ) endif () # Install and recompile schemas message(STATUS "GSettings schemas will be installed into ${GSETTINGS_DIR}") install( FILES ${all_schema_files} DESTINATION ${GSETTINGS_DIR} OPTIONAL ) if (GSETTINGS_COMPILE) install( CODE "message (STATUS \"Compiling GSettings schemas\")" ) install( CODE "execute_process (COMMAND ${glib_schema_compiler} ${GSETTINGS_DIR})" ) endif () endmacro(add_schemas) ibus-unikey-0.7.0~beta1/src/0000775000175000017500000000000013441506611015235 5ustar gunnargunnaribus-unikey-0.7.0~beta1/src/unikey.xml.in0000664000175000017500000000076413441506611017677 0ustar gunnargunnar org.freedesktop.IBus.Unikey Unikey Component ${LIBEXECDIR}/ibus-engine-unikey --ibus @VERSION@ Vietnamese Input group GPL https://github.com/vn-input/ibus-unikey ibus-unikey ibus-unikey-0.7.0~beta1/src/main.cpp0000664000175000017500000001072513441506611016672 0ustar gunnargunnar#ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include #include "engine.h" #include "unikey.h" #define _(string) gettext(string) static IBusBus* bus = NULL; static IBusFactory* factory = NULL; /* option */ static gboolean xml = FALSE; static gboolean ibus = FALSE; static gboolean verbose = FALSE; static const GOptionEntry entries[] = { { "xml", 'x', 0, G_OPTION_ARG_NONE, &xml, "generate xml for engines", NULL }, { "ibus", 'i', 0, G_OPTION_ARG_NONE, &ibus, "component is executed by ibus", NULL }, { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "verbose", NULL }, { NULL }, }; static IBusComponent* ibus_unikey_get_component(); static void ibus_disconnected_cb(IBusBus* bus, gpointer user_data) { ibus_quit(); } static void start_component(void) { GList* engines; GList* p; IBusComponent* component; ibus_init(); bus = ibus_bus_new(); g_signal_connect(bus, "disconnected", G_CALLBACK(ibus_disconnected_cb), NULL); component = ibus_unikey_get_component(); factory = ibus_factory_new(ibus_bus_get_connection(bus)); engines = ibus_component_get_engines(component); for (p = engines; p != NULL; p = p->next) { IBusEngineDesc* engine = (IBusEngineDesc*)p->data; ibus_factory_add_engine(factory, ibus_engine_desc_get_name(engine), IBUS_TYPE_UNIKEY_ENGINE); } if (ibus) ibus_bus_request_name(bus, "org.freedesktop.IBus.Unikey", 0); else ibus_bus_register_component(bus, component); g_object_unref(component); ibus_unikey_init(bus); ibus_main(); ibus_unikey_exit(); } static void print_engines_xml(void) { IBusComponent* component; GString* output; ibus_init(); component = ibus_unikey_get_component(); output = g_string_new(""); ibus_component_output_engines(component, output, 0); fprintf(stdout, "%s", output->str); g_string_free(output, TRUE); } int main(gint argc, gchar** argv) { GError* error = NULL; GOptionContext* context; setlocale(LC_ALL, ""); bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR); textdomain(GETTEXT_PACKAGE); context = g_option_context_new("- ibus unikey engine component"); g_option_context_add_main_entries(context, entries, "ibus-unikey"); if (!g_option_context_parse(context, &argc, &argv, &error)) { g_print("Option parsing failed: %s\n", error->message); exit(-1); } if (xml) { print_engines_xml(); return 0; } start_component(); return 0; } #define IU_DESC _("Vietnamese Input Method Engine for IBus using Unikey Engine\n\ Usage:\n\ - Choose input method, output charset, options in language bar.\n\ - There are 4 input methods: Telex, Vni, STelex (simple telex) \ and STelex2 (which same as STelex, the difference is it use w as ư).\n\ - And 7 output charsets: Unicode (UTF-8), TCVN3, VNI Win, VIQR, CString, NCR Decimal and NCR Hex.\n\ - Use + or + to restore keystrokes.\n\ - Use to commit a word.\ ") static IBusComponent* ibus_unikey_get_component() { IBusComponent* component; IBusEngineDesc* engine; component = ibus_component_new("org.freedesktop.IBus.Unikey", "Unikey component", PACKAGE_VERSION, "GPLv3", "Vietnamese input group", PACKAGE_BUGREPORT, "", PACKAGE_NAME); engine = ibus_engine_desc_new_varargs ("name", "Unikey", "longname", "Unikey", "description", IU_DESC, "language", "vi", "license", "GPLv3", "author", "Vietnamese input group", "icon", PKGDATADIR "/icons/ibus-unikey.svg", "layout", "*", "rank", 99, "setup", LIBEXECDIR "/ibus-setup-unikey", NULL); ibus_component_add_engine(component, engine); return component; } ibus-unikey-0.7.0~beta1/src/CMakeLists.txt0000664000175000017500000000104213441506611017772 0ustar gunnargunnarfind_package(PkgConfig) pkg_check_modules(IBUS REQUIRED ibus-1.0) add_subdirectory(config) add_executable(ibus-engine-unikey main.cpp engine.cpp ) target_link_libraries(ibus-engine-unikey ukengine unikey-config ${IBUS_LIBRARIES} ) target_include_directories(ibus-engine-unikey PUBLIC ${IBUS_INCLUDE_DIRS}) configure_file(unikey.xml.in unikey.xml) install(TARGETS ibus-engine-unikey DESTINATION ${LIBEXECDIR}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/unikey.xml DESTINATION "${CMAKE_INSTALL_FULL_DATADIR}/ibus/component") ibus-unikey-0.7.0~beta1/src/config/0000775000175000017500000000000013441506611016502 5ustar gunnargunnaribus-unikey-0.7.0~beta1/src/config/CMakeLists.txt0000664000175000017500000000044013441506611021240 0ustar gunnargunnarFIND_PACKAGE(PkgConfig) PKG_CHECK_MODULES(GIO REQUIRED gio-2.0) add_library(unikey-config STATIC unikey_config.cpp) TARGET_INCLUDE_DIRECTORIES(unikey-config PUBLIC ${GIO_INCLUDE_DIRS}) include(GSettings) add_schemas(unikey-config ${CMAKE_CURRENT_SOURCE_DIR} "${CMAKE_INSTALL_PREFIX}") ibus-unikey-0.7.0~beta1/src/config/unikey_config.h0000664000175000017500000000402713441506611021507 0ustar gunnargunnar#if !defined (__IBUS_UNIKEY_CONFIG_H__) #define __IBUS_UNIKEY_CONFIG_H__ #include #include #include #include "ukengine.h" #define UNIKEY_MACRO_FILE ".ibus/unikey/macro" #define UNIKEY_GSCHEMA_ID "org.freedesktop.ibus.engine.unikey" #define CONFIG_INPUTMETHOD "input-method" #define CONFIG_OUTPUTCHARSET "output-charset" #define CONFIG_SPELLCHECK "spell-check" #define CONFIG_AUTORESTORENONVN "auto-restore-non-vn" #define CONFIG_MODERNSTYLE "modern-style" #define CONFIG_FREEMARKING "free-marking" #define CONFIG_MACROENABLED "macro-enabled" #define CONFIG_STANDALONEW "standalone-w-as-uw" const std::map> input_method_map { { "telex", { UkTelex, "Extend Telex" } }, { "vni", { UkVni, "VNI" } }, { "stelex", { UkSimpleTelex, "STelex" } }, { "stelex2", { UkSimpleTelex2, "STelex 2" } }, }; const std::map> output_charset_map { { "unicode", { CONV_CHARSET_XUTF8, "Unicode" } }, { "tcvn3", { CONV_CHARSET_TCVN3, "TCVN3" } }, { "vni-win", { CONV_CHARSET_VNIWIN, "VNI Win" } }, { "viqr", { CONV_CHARSET_VIQR, "VIQR" } }, { "bk-hcm2", { CONV_CHARSET_BKHCM2, "BK HCM 2" } }, { "cstr", { CONV_CHARSET_UNI_CSTRING, "CString" } }, { "ncr-dec", { CONV_CHARSET_UNIREF, "NCR Decimal" } }, { "ncr-hex", { CONV_CHARSET_UNIREF_HEX, "NCR Hex" } }, }; #define get_macro_file() (g_build_filename(g_getenv("HOME"), UNIKEY_MACRO_FILE, NULL)) void ibus_unikey_config_init(); void ibus_unikey_config_on_changed(void(*cb)(gchar *, gpointer), gpointer user_data); gboolean ibus_unikey_config_get_string(const gchar* name, gchar** result); void ibus_unikey_config_set_string(const gchar* name, const gchar* value); gboolean ibus_unikey_config_get_boolean(const gchar* name, gboolean* result); void ibus_unikey_config_set_boolean(const gchar* name, gboolean value); #endif ibus-unikey-0.7.0~beta1/src/config/org.freedesktop.ibus.engine.unikey.gschema.xml0000664000175000017500000000411313441506611027442 0ustar gunnargunnar 'telex' Input Method 'unicode' Output charset Allow to choice old Vietnamese charset (hidden setting) true Spell check true Auto restore non Vietnamese word Auto restore word that not in Vietnamese (required spell-check) false Modern style Use oà, _uý (instead of òa, úy) true Free marking Allow type with more freedom false Use macro Enable macro feature true Standalone W as ư (Telex only) ibus-unikey-0.7.0~beta1/src/config/unikey_config.cpp0000664000175000017500000000313313441506611022037 0ustar gunnargunnar#ifdef HAVE_CONFIG_H #include "config.h" #endif #include "unikey_config.h" static GSettings* settings; void ibus_unikey_config_init() { settings = g_settings_new(UNIKEY_GSCHEMA_ID); } struct changed_data { void(*cb)(gchar *, gpointer); gpointer user_data; }; static void settings_changed_wrap(GSettings* settings, gchar *name, gpointer user_data) { auto data = (changed_data*)user_data; data->cb(name, data->user_data); } void ibus_unikey_config_on_changed(void(*cb)(gchar *, gpointer), gpointer user_data) { // TODO should provide a way to cleanup auto data = new changed_data{cb, user_data}; g_signal_connect(settings, "changed", G_CALLBACK(settings_changed_wrap), data); } gboolean ibus_unikey_config_get_string(const gchar* name, gchar** result) { GVariant *value = NULL; value = g_settings_get_value(settings, name); if (value) { *result = g_variant_dup_string(value, NULL); g_variant_unref(value); return true; } return false; } void ibus_unikey_config_set_string(const gchar* name, const gchar* value) { g_settings_set_value(settings, name, g_variant_new_string(value)); } gboolean ibus_unikey_config_get_boolean(const gchar* name, gboolean* result) { GVariant *value = NULL; value = g_settings_get_value(settings, name); if (value) { *result = g_variant_get_boolean(value); g_variant_unref(value); return true; } return false; } void ibus_unikey_config_set_boolean(const gchar* name, gboolean value) { g_settings_set_value(settings, name, g_variant_new_boolean(value)); } ibus-unikey-0.7.0~beta1/src/engine.cpp0000664000175000017500000004706313441506611017220 0ustar gunnargunnar#ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include #include "unikey.h" #include "vnconv.h" #include "engine_private.h" #include "unikey_config.h" #define _(string) gettext(string) #define CONVERT_BUF_SIZE 1024 static unsigned char WordBreakSyms[] = { ',', ';', ':', '.', '\"', '\'', '!', '?', ' ', '<', '>', '=', '+', '-', '*', '/', '\\', '_', '~', '`', '@', '#', '$', '%', '^', '&', '(', ')', '{', '}', '[', ']', '|' }; static IBusEngineClass* parent_class = NULL; static IBusUnikeyEngine* unikey; // current (focus) unikey engine GType ibus_unikey_engine_get_type(void) { static GType type = 0; static const GTypeInfo type_info = { sizeof(IBusUnikeyEngineClass), (GBaseInitFunc)NULL, (GBaseFinalizeFunc)NULL, (GClassInitFunc)ibus_unikey_engine_class_init, NULL, NULL, sizeof(IBusUnikeyEngine), 0, (GInstanceInitFunc)ibus_unikey_engine_init, }; if (type == 0) { type = g_type_register_static(IBUS_TYPE_ENGINE, "IBusUnikeyEngine", &type_info, (GTypeFlags)0); } return type; } void ibus_unikey_init(IBusBus* bus) { UnikeySetup(); ibus_unikey_config_init(); ibus_unikey_config_on_changed(ibus_unikey_config_value_changed, NULL); } void ibus_unikey_exit() { UnikeyCleanup(); } static void ibus_unikey_engine_class_init(IBusUnikeyEngineClass* klass) { GObjectClass* object_class = G_OBJECT_CLASS(klass); IBusObjectClass* ibus_object_class = IBUS_OBJECT_CLASS(klass); IBusEngineClass* engine_class = IBUS_ENGINE_CLASS(klass); parent_class = (IBusEngineClass* )g_type_class_peek_parent(klass); object_class->constructor = ibus_unikey_engine_constructor; ibus_object_class->destroy = (IBusObjectDestroyFunc)ibus_unikey_engine_destroy; engine_class->process_key_event = ibus_unikey_engine_process_key_event; engine_class->reset = ibus_unikey_engine_reset; engine_class->enable = ibus_unikey_engine_enable; engine_class->disable = ibus_unikey_engine_disable; engine_class->focus_in = ibus_unikey_engine_focus_in; engine_class->focus_out = ibus_unikey_engine_focus_out; engine_class->property_activate = ibus_unikey_engine_property_activate; } static void ibus_unikey_engine_init(IBusUnikeyEngine* unikey) { ibus_unikey_engine_load_config(unikey); UnikeySetInputMethod(unikey->im); UnikeySetOutputCharset(unikey->oc); UnikeySetOptions(&unikey->ukopt); unikey->preeditstr = new std::string(); ibus_unikey_engine_create_property_list(unikey); } static IBusProperty* find_prop_from_list(IBusPropList* list, const char* key) { for (guint i = 0; i < list->properties->len ; i++) { IBusProperty* prop = ibus_prop_list_get(list, i); if (prop == NULL) return NULL; if (strcmp(ibus_property_get_key(prop), key) == 0) return prop; } return NULL; } static void ibus_unikey_engine_update_property_list(IBusUnikeyEngine* unikey) { bool b; IBusProperty* prop; b = unikey->ukopt.spellCheckEnabled; prop = find_prop_from_list(unikey->prop_list, CONFIG_SPELLCHECK); if (prop != NULL) { ibus_property_set_state(prop, (b == 1) ? PROP_STATE_CHECKED:PROP_STATE_UNCHECKED); } b = unikey->ukopt.autoNonVnRestore; prop = find_prop_from_list(unikey->prop_list, CONFIG_AUTORESTORENONVN); if (prop != NULL) { ibus_property_set_state(prop, (b == 1) ? PROP_STATE_CHECKED:PROP_STATE_UNCHECKED); } b = unikey->ukopt.macroEnabled; prop = find_prop_from_list(unikey->prop_list, CONFIG_MACROENABLED); if (prop != NULL) { ibus_property_set_state(prop, (b == 1) ? PROP_STATE_CHECKED:PROP_STATE_UNCHECKED); } } static void ibus_unikey_engine_load_config(IBusUnikeyEngine* unikey) { gchar* str; gboolean b; auto im = input_method_map.at("telex").first; if (ibus_unikey_config_get_string(CONFIG_INPUTMETHOD, &str)) { auto p = input_method_map.at(std::string(str)); im = p.first; g_free(str); } unikey->im = im; auto oc = output_charset_map.at("unicode").first; if (ibus_unikey_config_get_string(CONFIG_OUTPUTCHARSET, &str)) { auto p = output_charset_map.at(std::string(str)); oc = p.first; g_free(str); } unikey->oc = oc; if (ibus_unikey_config_get_boolean(CONFIG_FREEMARKING, &b)) unikey->ukopt.freeMarking = b; if (ibus_unikey_config_get_boolean(CONFIG_MODERNSTYLE, &b)) unikey->ukopt.modernStyle = b; if (ibus_unikey_config_get_boolean(CONFIG_MACROENABLED, &b)) unikey->ukopt.macroEnabled = b; if (ibus_unikey_config_get_boolean(CONFIG_SPELLCHECK, &b)) unikey->ukopt.spellCheckEnabled = b; if (ibus_unikey_config_get_boolean(CONFIG_AUTORESTORENONVN, &b)) unikey->ukopt.autoNonVnRestore = b; if (ibus_unikey_config_get_boolean(CONFIG_STANDALONEW, &b)) unikey->process_w_at_begin = b; // load macro gchar* fn = get_macro_file(); UnikeyLoadMacroTable(fn); g_free(fn); } static GObject* ibus_unikey_engine_constructor(GType type, guint n_construct_params, GObjectConstructParam* construct_params) { IBusUnikeyEngine* unikey; unikey = (IBusUnikeyEngine*) G_OBJECT_CLASS(parent_class)->constructor(type, n_construct_params, construct_params); return (GObject*)unikey; } static void ibus_unikey_engine_destroy(IBusUnikeyEngine* unikey) { delete unikey->preeditstr; g_object_unref(unikey->prop_list); IBUS_OBJECT_CLASS(parent_class)->destroy((IBusObject*)unikey); } static void ibus_unikey_buffer_reset(IBusEngine* engine) { unikey = (IBusUnikeyEngine*)engine; ibus_engine_hide_preedit_text(engine); unikey->preeditstr->clear(); UnikeyResetBuf(); } static void ibus_unikey_buffer_commit(IBusEngine* engine) { unikey = (IBusUnikeyEngine*)engine; if (unikey->preeditstr->length() > 0) { IBusText *text; text = ibus_text_new_from_static_string(unikey->preeditstr->c_str()); ibus_engine_commit_text(engine, text); } ibus_unikey_buffer_reset(engine); } static void ibus_unikey_engine_focus_in(IBusEngine* engine) { unikey = (IBusUnikeyEngine*)engine; ibus_engine_register_properties(engine, unikey->prop_list); parent_class->focus_in(engine); } static void ibus_unikey_engine_focus_out(IBusEngine* engine) { ibus_unikey_buffer_reset(engine); parent_class->focus_out(engine); } static void ibus_unikey_engine_reset(IBusEngine* engine) { ibus_unikey_buffer_reset(engine); parent_class->reset(engine); } static void ibus_unikey_engine_enable(IBusEngine* engine) { parent_class->enable(engine); } static void ibus_unikey_engine_disable(IBusEngine* engine) { parent_class->disable(engine); } static void ibus_unikey_config_value_changed(gchar* name, gpointer user_data) { ibus_unikey_engine_load_config(unikey); UnikeySetInputMethod(unikey->im); UnikeySetOutputCharset(unikey->oc); UnikeySetOptions(&unikey->ukopt); ibus_unikey_engine_update_property_list(unikey); } static void ibus_unikey_engine_property_activate(IBusEngine* engine, const gchar* prop_name, guint prop_state) { unikey = (IBusUnikeyEngine*)engine; if (strcmp(prop_name, "more-settings") == 0) { int ret = 0; ret = system(LIBEXECDIR "/ibus-setup-unikey &"); if (ret == -1) { g_print("Failed to open ibus-setup-unikey"); } return; } if (strcmp(prop_name, CONFIG_SPELLCHECK) == 0) { unikey->ukopt.spellCheckEnabled = prop_state > 0; ibus_unikey_config_set_boolean(prop_name, prop_state > 0); } else if (strcmp(prop_name, CONFIG_AUTORESTORENONVN) == 0) { unikey->ukopt.autoNonVnRestore = prop_state > 0; ibus_unikey_config_set_boolean(prop_name, prop_state > 0); } else if (strcmp(prop_name, CONFIG_MACROENABLED) == 0) { unikey->ukopt.macroEnabled = prop_state > 0; ibus_unikey_config_set_boolean(prop_name, prop_state > 0); } } static void ibus_unikey_engine_create_property_list(IBusUnikeyEngine* unikey) { IBusProperty* prop; IBusText* label; if (unikey->prop_list != NULL) return; unikey->prop_list = ibus_prop_list_new(); g_object_ref_sink(unikey->prop_list); // spellcheck property label = ibus_text_new_from_static_string(_("Enable spell check")); prop = ibus_property_new(CONFIG_SPELLCHECK, PROP_TYPE_TOGGLE, label, "", NULL, TRUE, TRUE, (unikey->ukopt.spellCheckEnabled==1)? PROP_STATE_CHECKED:PROP_STATE_UNCHECKED, NULL); if (ibus_prop_list_update_property(unikey->prop_list, prop) == false) ibus_prop_list_append(unikey->prop_list, prop); // auto restore property label = ibus_text_new_from_static_string(_("Auto restore non Vietnamese word")); prop = ibus_property_new(CONFIG_AUTORESTORENONVN, PROP_TYPE_TOGGLE, label, "", NULL, TRUE, TRUE, (unikey->ukopt.autoNonVnRestore==1)? PROP_STATE_CHECKED:PROP_STATE_UNCHECKED, NULL); if (ibus_prop_list_update_property(unikey->prop_list, prop) == false) ibus_prop_list_append(unikey->prop_list, prop); // macroEnabled property label = ibus_text_new_from_static_string(_("Enable Macro")); prop = ibus_property_new(CONFIG_MACROENABLED, PROP_TYPE_TOGGLE, label, "", NULL, TRUE, TRUE, (unikey->ukopt.macroEnabled==1)? PROP_STATE_CHECKED:PROP_STATE_UNCHECKED, NULL); if (ibus_prop_list_update_property(unikey->prop_list, prop) == false) ibus_prop_list_append(unikey->prop_list, prop); // more setting property label = ibus_text_new_from_static_string(_("More settings...")); prop = ibus_property_new("more-settings", PROP_TYPE_NORMAL, label, "", NULL, TRUE, TRUE, PROP_STATE_UNCHECKED, NULL); if (ibus_prop_list_update_property(unikey->prop_list, prop) == false) ibus_prop_list_append(unikey->prop_list, prop); } static void ibus_unikey_engine_update_preedit_string(IBusEngine *engine, const gchar *string, gboolean visible) { IBusText *text; text = ibus_text_new_from_static_string(string); // underline text ibus_text_append_attribute(text, IBUS_ATTR_TYPE_UNDERLINE, IBUS_ATTR_UNDERLINE_SINGLE, 0, -1); // update and display text ibus_engine_update_preedit_text_with_mode(engine, text, ibus_text_get_length(text), visible, IBUS_ENGINE_PREEDIT_COMMIT); } static void ibus_unikey_engine_erase_chars(IBusEngine *engine, int count) { int i = unikey->preeditstr->length(); while (i > 0 && count > 0) { unsigned char code = unikey->preeditstr->at(i-1); // count down if code is the first byte of utf-8 char // REF: http://en.wikipedia.org/wiki/UTF-8 if (code >> 6 != 2) { // ignore 10xxxxxx count--; } i--; } unikey->preeditstr->erase(i); } // code from x-unikey, for convert charset that not is XUtf-8 int latinToUtf(unsigned char* dst, unsigned char* src, int inSize, int* pOutSize) { int i; int outLeft; unsigned char ch; outLeft = *pOutSize; for (i=0; i= 0) *dst++ = ch; } else { outLeft -= 2; if (outLeft >= 0) { *dst++ = (0xC0 | ch >> 6); *dst++ = (0x80 | (ch & 0x3F)); } } } *pOutSize = outLeft; return (outLeft >= 0); } static gboolean ibus_unikey_engine_process_key_event(IBusEngine* engine, guint keyval, guint keycode, guint modifiers) { static gboolean tmp; unikey = (IBusUnikeyEngine*)engine; tmp = ibus_unikey_engine_process_key_event_preedit(engine, keyval, keycode, modifiers); // check last keyevent with shift if (keyval >= IBUS_space && keyval <=IBUS_asciitilde) { unikey->last_key_with_shift = modifiers & IBUS_SHIFT_MASK; } else { unikey->last_key_with_shift = false; } // end check last keyevent with shift return tmp; } static gboolean ibus_unikey_engine_process_key_event_preedit(IBusEngine* engine, guint keyval, guint keycode, guint modifiers) { if (modifiers & IBUS_RELEASE_MASK) { return false; } else if (modifiers & IBUS_CONTROL_MASK || modifiers & IBUS_MOD1_MASK // alternate mask || keyval == IBUS_Control_L || keyval == IBUS_Control_R || keyval == IBUS_Tab || keyval == IBUS_Return || keyval == IBUS_Delete || keyval == IBUS_KP_Enter || (keyval >= IBUS_Home && keyval <= IBUS_Insert) || (keyval >= IBUS_KP_Home && keyval <= IBUS_KP_Delete) ) { ibus_unikey_buffer_commit(engine); return false; } else if ((keyval >= IBUS_Caps_Lock && keyval <= IBUS_Hyper_R) || (!(modifiers & IBUS_SHIFT_MASK) && (keyval == IBUS_Shift_L || keyval == IBUS_Shift_R)) // when press one shift key ) { return false; } // capture BackSpace else if (keyval == IBUS_BackSpace) { UnikeyBackspacePress(); if (UnikeyBackspaces == 0 || unikey->preeditstr->empty()) { return false; } else { if (unikey->preeditstr->length() <= (guint)UnikeyBackspaces) { ibus_unikey_buffer_reset(engine); } else { ibus_unikey_engine_erase_chars(engine, UnikeyBackspaces); ibus_unikey_engine_update_preedit_string(engine, unikey->preeditstr->c_str(), true); } // change tone position after press backspace if (UnikeyBufChars > 0) { if (unikey->oc == CONV_CHARSET_XUTF8) { unikey->preeditstr->append((const gchar*)UnikeyBuf, UnikeyBufChars); } else { static unsigned char buf[CONVERT_BUF_SIZE]; int bufSize = CONVERT_BUF_SIZE; latinToUtf(buf, UnikeyBuf, UnikeyBufChars, &bufSize); unikey->preeditstr->append((const gchar*)buf, CONVERT_BUF_SIZE - bufSize); } ibus_unikey_engine_update_preedit_string(engine, unikey->preeditstr->c_str(), true); } } return true; } // end capture BackSpace else if (keyval >=IBUS_KP_Multiply && keyval <=IBUS_KP_9) { ibus_unikey_buffer_commit(engine); return false; } // capture ascii printable char else if ((keyval >= IBUS_space && keyval <=IBUS_asciitilde) || keyval == IBUS_Shift_L || keyval == IBUS_Shift_R) // sure this have IBUS_SHIFT_MASK { UnikeySetCapsState(modifiers & IBUS_SHIFT_MASK, modifiers & IBUS_LOCK_MASK); // process keyval if ((unikey->im == UkTelex || unikey->im == UkSimpleTelex2) && unikey->process_w_at_begin == false && UnikeyAtWordBeginning() && (keyval == IBUS_w || keyval == IBUS_W)) { UnikeyPutChar(keyval); unikey->preeditstr->append(keyval==IBUS_w?"w":"W"); ibus_unikey_engine_update_preedit_string(engine, unikey->preeditstr->c_str(), true); return true; } // shift + space, shift + shift event if ((unikey->last_key_with_shift == false && modifiers & IBUS_SHIFT_MASK && keyval == IBUS_space && !UnikeyAtWordBeginning()) || (keyval == IBUS_Shift_L || keyval == IBUS_Shift_R) // (&& modifiers & IBUS_SHIFT_MASK), sure this have IBUS_SHIFT_MASK ) { UnikeyRestoreKeyStrokes(); } // end shift + space, shift + shift event else { UnikeyFilter(keyval); } // end process keyval // process result of ukengine if (UnikeyBackspaces > 0) { if (unikey->preeditstr->length() <= (guint)UnikeyBackspaces) { unikey->preeditstr->clear(); } else { ibus_unikey_engine_erase_chars(engine, UnikeyBackspaces); } } if (UnikeyBufChars > 0) { if (unikey->oc == CONV_CHARSET_XUTF8) { unikey->preeditstr->append((const gchar*)UnikeyBuf, UnikeyBufChars); } else { static unsigned char buf[CONVERT_BUF_SIZE]; int bufSize = CONVERT_BUF_SIZE; latinToUtf(buf, UnikeyBuf, UnikeyBufChars, &bufSize); unikey->preeditstr->append((const gchar*)buf, CONVERT_BUF_SIZE - bufSize); } } else if (keyval != IBUS_Shift_L && keyval != IBUS_Shift_R) // if ukengine not process { static int n; static char s[6]; n = g_unichar_to_utf8(keyval, s); // convert ucs4 to utf8 char unikey->preeditstr->append(s, n); } // end process result of ukengine // commit string: if need if (unikey->preeditstr->length() > 0) { static guint i; for (i = 0; i < sizeof(WordBreakSyms); i++) { if (WordBreakSyms[i] == unikey->preeditstr->at(unikey->preeditstr->length()-1) && WordBreakSyms[i] == keyval) { ibus_unikey_buffer_commit(engine); return true; } } } // end commit string ibus_unikey_engine_update_preedit_string(engine, unikey->preeditstr->c_str(), true); return true; } //end capture printable char // non process key ibus_unikey_buffer_commit(engine); return false; } ibus-unikey-0.7.0~beta1/src/engine.h0000664000175000017500000000035313441506611016654 0ustar gunnargunnar#ifndef __ENGINE_H__ #define __ENGINE_H__ #include #define IBUS_TYPE_UNIKEY_ENGINE (ibus_unikey_engine_get_type()) void ibus_unikey_init(IBusBus* bus); void ibus_unikey_exit(); GType ibus_unikey_engine_get_type(); #endif ibus-unikey-0.7.0~beta1/src/engine_private.h0000664000175000017500000000517313441506611020413 0ustar gunnargunnar#ifndef __ENGINE_PRIVATE_H__ #define __ENGINE_PRIVATE_H__ #include #include #include "unikey.h" #include "vnconv.h" typedef struct _IBusUnikeyEngine IBusUnikeyEngine; typedef struct _IBusUnikeyEngineClass IBusUnikeyEngineClass; struct _IBusUnikeyEngine { IBusEngine parent; /* members */ IBusPropList* prop_list; UkInputMethod im; // input method unsigned int oc; // output charset UnikeyOptions ukopt; gboolean process_w_at_begin; gboolean last_key_with_shift; std::string* preeditstr; }; struct _IBusUnikeyEngineClass { IBusEngineClass parent; }; // prototype static void ibus_unikey_engine_class_init(IBusUnikeyEngineClass* kclass); static void ibus_unikey_engine_init(IBusUnikeyEngine* unikey); static GObject* ibus_unikey_engine_constructor(GType type, guint n_construct_params, GObjectConstructParam* construct_params); static void ibus_unikey_engine_destroy(IBusUnikeyEngine* unikey); static gboolean ibus_unikey_engine_process_key_event(IBusEngine* engine, guint keyval, guint keycode, guint modifiers); static void ibus_unikey_engine_focus_in(IBusEngine* engine); static void ibus_unikey_engine_focus_out(IBusEngine* engine); static void ibus_unikey_engine_reset(IBusEngine* engine); static void ibus_unikey_engine_enable(IBusEngine* engine); static void ibus_unikey_engine_disable(IBusEngine* engine); static void ibus_unikey_engine_load_config(IBusUnikeyEngine* unikey); static void ibus_unikey_config_value_changed(gchar* name, gpointer user_data); static void ibus_unikey_engine_property_activate(IBusEngine* engine, const gchar* prop_name, guint prop_state); static gboolean ibus_unikey_engine_process_key_event_preedit(IBusEngine* engine, guint keyval, guint keycode, guint modifiers); static void ibus_unikey_engine_create_property_list(IBusUnikeyEngine* unikey); static void ibus_unikey_engine_update_preedit_string(IBusEngine *engine, const gchar *string, gboolean visible); static void ibus_unikey_engine_erase_chars(IBusEngine *engine, int num_chars); static int latinToUtf(unsigned char* dst, unsigned char* src, int inSize, int* pOutSize); #endif ibus-unikey-0.7.0~beta1/setup/0000775000175000017500000000000013441506611015606 5ustar gunnargunnaribus-unikey-0.7.0~beta1/setup/main.cpp0000664000175000017500000000220013441506611017230 0ustar gunnargunnar#ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include "unikey_config.h" #define _(string) gettext(string) GtkWidget* mwin; GtkWidget* dlgMacro; GtkTreeView* tree_macro; void init_gtk_builder() { GtkBuilder* builder = gtk_builder_new(); gtk_builder_add_from_file(builder, PKGDATADIR "/ui/ibus-unikey.ui", NULL); gtk_builder_connect_signals(builder, NULL); mwin = GTK_WIDGET(gtk_builder_get_object(builder, "main_window")); dlgMacro = GTK_WIDGET(gtk_builder_get_object(builder, "macro_dialog")); gtk_window_set_transient_for(GTK_WINDOW(dlgMacro), GTK_WINDOW(mwin)); tree_macro = GTK_TREE_VIEW(gtk_builder_get_object(builder, "tree_macro")); g_object_unref(builder); } int main(int argc, char** argv) { setlocale(LC_ALL, ""); bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR); textdomain(GETTEXT_PACKAGE); ibus_unikey_config_init(); gtk_init(&argc, &argv); gtk_window_set_default_icon_from_file(PKGDATADIR "/icons/ibus-unikey.svg", NULL); init_gtk_builder(); gtk_widget_show_all(mwin); gtk_main(); return 0; } ibus-unikey-0.7.0~beta1/setup/signal_handlers.cpp0000664000175000017500000002216713441506611021457 0ustar gunnargunnar#include #include #include #include "mactab.h" #include "unikey_config.h" #include "macro_utils.h" #include "signal_handlers.h" #define _(str) gettext(str) extern GtkWidget* dlgMacro; extern GtkTreeView* tree_macro; #define MACRO_DEFAULT_VALUE _("(replace text)") gboolean on_main_window_key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data) { if (event->keyval == GDK_KEY_Escape) { gtk_main_quit(); return true; } return false; } void on_main_window_destroy(GtkWidget* btn, gpointer user_data) { gtk_main_quit(); } void on_btn_close_clicked(GtkButton* btn, gpointer user_data) { gtk_main_quit(); } static void cbb_config_update(GtkComboBox* cbb, const gchar* key) { GValue val = {0}; GtkTreeIter iter; GtkTreeModel* model; model = gtk_combo_box_get_model(cbb); gtk_combo_box_get_active_iter(cbb, &iter); gtk_tree_model_get_value(model, &iter, 0, &val); ibus_unikey_config_set_string(key, g_value_get_string(&val)); g_value_unset(&val); } void on_input_method_changed(GtkComboBox* cbb, gpointer user_data) { cbb_config_update(cbb, CONFIG_INPUTMETHOD); } void on_output_charset_changed(GtkComboBox* cbb, gpointer user_data) { cbb_config_update(cbb, CONFIG_OUTPUTCHARSET); } void cbb_config_set_active(GtkComboBox* cbb, const gchar* key) { GValue val = {0}; GtkTreeIter iter; GtkTreeModel* model; gchar *im; if (!ibus_unikey_config_get_string(key, &im)) { return; } model = gtk_combo_box_get_model(cbb); gtk_tree_model_get_iter_first(model, &iter); do { gtk_tree_model_get_value(model, &iter, 0, &val); if (strcmp(im, g_value_get_string(&val)) == 0) { gtk_combo_box_set_active_iter(cbb, &iter); g_value_unset(&val); break; } g_value_unset(&val); } while (gtk_tree_model_iter_next(model, &iter)); g_free(im); } void on_input_method_realize(GtkComboBox* cbb, gpointer user_data) { cbb_config_set_active(cbb, CONFIG_INPUTMETHOD); } void on_output_charset_realize(GtkComboBox* cbb, gpointer user_data) { cbb_config_set_active(cbb, CONFIG_OUTPUTCHARSET); } void on_setting_toggled(GtkToggleButton* btn, gpointer user_data) { const gchar* key = gtk_widget_get_name(GTK_WIDGET(btn)); key = key + 4; // skip "cfg_" gboolean b = gtk_toggle_button_get_active(btn); ibus_unikey_config_set_boolean(key, b); } void on_setting_realize(GtkToggleButton* btn, gpointer user_data) { const gchar* key = gtk_widget_get_name(GTK_WIDGET(btn)); key = key + 4; // skip "cfg_" gboolean b; if (ibus_unikey_config_get_boolean(key, &b)) { gtk_toggle_button_set_active(btn, b); } } void on_btn_macroedit_clicked(GtkButton* btn, gpointer user_data) { gchar* macrofile = get_macro_file(); CMacroTable macro; macro.init(); macro.loadFromFile(macrofile); auto store = GTK_LIST_STORE(gtk_tree_view_get_model(tree_macro)); unikey_macro_to_store(¯o, store); int ret = gtk_dialog_run(GTK_DIALOG(dlgMacro)); if (ret == GTK_RESPONSE_OK) { unikey_store_to_macro(store, ¯o); GFile* f = g_file_get_parent(g_file_new_for_path(macrofile)); if (g_file_query_exists(f, NULL) == FALSE) { g_file_make_directory_with_parents(f, NULL, NULL); } g_object_unref(f); macro.writeToFile(macrofile); } g_free(macrofile); } gboolean on_macro_dialog_delete(GtkWidget* wid, GdkEvent* ev, gpointer user_data) { gtk_widget_hide(dlgMacro); return true; } void macro_dialog_hide(GtkButton* btn, gpointer user_data) { gtk_widget_hide(dlgMacro); } void on_cell_key_edited(GtkCellRendererText *celltext, const gchar *string_path, const gchar *newkey, gpointer data) { GtkTreeIter iter; gchar *oldkey; gchar nkey[MAX_MACRO_KEY_LEN]; auto model = gtk_tree_view_get_model(tree_macro); strncpy(nkey, newkey, MAX_MACRO_KEY_LEN-1); nkey[MAX_MACRO_KEY_LEN-1] = '\0'; if (strcmp(nkey, STR_NULL_ITEM) == 0 || (strlen(STR_NULL_ITEM) != 0 && strlen(nkey) == 0)) return; if (list_store_check_exists(GTK_LIST_STORE(model), nkey)) return; gtk_tree_model_get_iter_from_string(model, &iter, string_path); gtk_tree_model_get(model, &iter, COL_KEY, &oldkey, -1); if (strcmp(oldkey, STR_NULL_ITEM) == 0) gtk_list_store_set(GTK_LIST_STORE(model), &iter, COL_KEY, nkey, COL_VALUE, MACRO_DEFAULT_VALUE, -1); else gtk_list_store_set(GTK_LIST_STORE(model), &iter, COL_KEY, nkey, -1); g_free(oldkey); list_store_add_null_item(GTK_LIST_STORE(model)); } void on_cell_value_edited(GtkCellRendererText *celltext, const gchar *string_path, const gchar *newvalue, gpointer data) { GtkTreeIter iter; gchar *key; gchar value[MAX_MACRO_TEXT_LEN]; auto model = gtk_tree_view_get_model(tree_macro); gtk_tree_model_get_iter_from_string(model, &iter, string_path); gtk_tree_model_get(model, &iter, COL_KEY, &key, -1); strncpy(value, newvalue, MAX_MACRO_TEXT_LEN-1); value[MAX_MACRO_TEXT_LEN-1] = '\0'; if (strcmp(key, STR_NULL_ITEM) != 0) { gtk_list_store_set(GTK_LIST_STORE(model), &iter, COL_VALUE, value, -1); } g_free(key); } void on_btn_macro_del_clicked(GtkButton *button, gpointer user_data) { GtkTreeIter iter; auto select = gtk_tree_view_get_selection(tree_macro); if (gtk_tree_selection_get_selected(select, NULL, &iter) == TRUE) { auto store = GTK_LIST_STORE(gtk_tree_view_get_model(tree_macro)); gchar *key; gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, COL_KEY, &key, -1); if (strcmp(key, STR_NULL_ITEM) != 0) { gtk_list_store_remove(store, &iter); } gtk_tree_selection_select_iter(select, &iter); // select current index g_free(key); } } void on_btn_macro_clear_clicked(GtkButton *button, gpointer data) { auto store = GTK_LIST_STORE(gtk_tree_view_get_model(tree_macro)); gtk_list_store_clear(store); list_store_add_null_item(store); auto select = gtk_tree_view_get_selection(tree_macro); GtkTreeIter iter; gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter); gtk_tree_selection_select_iter(select, &iter); } void on_btn_macro_import_clicked(GtkButton *button, gpointer data) { auto file = gtk_file_chooser_dialog_new(_("Import macro"), GTK_WINDOW(dlgMacro), GTK_FILE_CHOOSER_ACTION_OPEN, dgettext("gtk30", "_Cancel"), GTK_RESPONSE_CANCEL, dgettext("gtk30", "_Open"), GTK_RESPONSE_OK, NULL); if (gtk_dialog_run(GTK_DIALOG(file)) == GTK_RESPONSE_OK) { auto fn = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(file)); CMacroTable macro; macro.init(); macro.loadFromFile(fn); g_free(fn); auto store = GTK_LIST_STORE(gtk_tree_view_get_model(tree_macro)); GtkTreeIter iter; auto n = gtk_tree_model_iter_n_children(GTK_TREE_MODEL(store), NULL); // get number of iter gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(store), &iter, NULL, n-1); // get last iter gtk_list_store_remove(store, &iter); // remove last iter (...) list_store_append(store, ¯o); list_store_add_null_item(store); // add iter (...) // select first iter auto select = gtk_tree_view_get_selection(tree_macro); gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter); gtk_tree_selection_select_iter(select, &iter); } gtk_widget_destroy(file); } void on_btn_macro_export_clicked(GtkButton *button, gpointer data) { auto file = gtk_file_chooser_dialog_new(_("Export macro"), GTK_WINDOW(dlgMacro), GTK_FILE_CHOOSER_ACTION_SAVE, dgettext("gtk30", "_Cancel"), GTK_RESPONSE_CANCEL, dgettext("gtk30", "_Save"), GTK_RESPONSE_OK, NULL); if (gtk_dialog_run(GTK_DIALOG(file)) == GTK_RESPONSE_OK) { CMacroTable macro; macro.init(); auto model = GTK_TREE_MODEL(gtk_tree_view_get_model(tree_macro)); GtkTreeIter iter; gchar* key, *value; gboolean b = gtk_tree_model_get_iter_first(model, &iter); while (b == TRUE) { gtk_tree_model_get(model, &iter, COL_KEY, &key, COL_VALUE, &value, -1); if (strcasecmp(key, STR_NULL_ITEM) != 0) { macro.addItem(key, value, CONV_CHARSET_XUTF8); } g_free(key); g_free(value); b = gtk_tree_model_iter_next(model, &iter); } auto fn = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(file)); macro.writeToFile(fn); g_free(fn); } gtk_widget_destroy(file); } ibus-unikey-0.7.0~beta1/setup/CMakeLists.txt0000664000175000017500000000070213441506611020345 0ustar gunnargunnarfind_package(PkgConfig) pkg_check_modules(GTK3 REQUIRED gtk+-3.0) add_executable(ibus-setup-unikey main.cpp signal_handlers.cpp macro_utils.cpp ) target_link_libraries(ibus-setup-unikey ukengine unikey-config ${GTK3_LIBRARIES} ) target_include_directories(ibus-setup-unikey PUBLIC ${GTK3_INCLUDE_DIRS}) install(TARGETS ibus-setup-unikey DESTINATION ${LIBEXECDIR}) install(FILES ibus-unikey.ui DESTINATION ${PKGDATADIR}/ui) ibus-unikey-0.7.0~beta1/setup/signal_handlers.h0000664000175000017500000000356013441506611021120 0ustar gunnargunnar#include extern "C" { G_MODULE_EXPORT void on_main_window_destroy(GtkWidget* w, gpointer user_data); G_MODULE_EXPORT gboolean on_main_window_key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data); G_MODULE_EXPORT void on_btn_close_clicked(GtkButton* btn, gpointer user_data); G_MODULE_EXPORT void on_setting_toggled(GtkToggleButton* btn, gpointer user_data); G_MODULE_EXPORT void on_setting_realize(GtkToggleButton* btn, gpointer user_data); G_MODULE_EXPORT void on_btn_macroedit_clicked(GtkButton* btn, gpointer user_data); G_MODULE_EXPORT void on_input_method_changed(GtkComboBox* cbb, gpointer user_data); G_MODULE_EXPORT void on_input_method_realize(GtkComboBox* cbb, gpointer user_data); G_MODULE_EXPORT void on_output_charset_changed(GtkComboBox* cbb, gpointer user_data); G_MODULE_EXPORT void on_output_charset_realize(GtkComboBox* cbb, gpointer user_data); G_MODULE_EXPORT gboolean on_macro_dialog_delete(GtkWidget* wid, GdkEvent* ev, gpointer user_data); G_MODULE_EXPORT void macro_dialog_hide(GtkButton* btn, gpointer user_data); G_MODULE_EXPORT void on_btn_macro_del_clicked(GtkButton *button, gpointer user_data); G_MODULE_EXPORT void on_btn_macro_clear_clicked(GtkButton *button, gpointer user_data); G_MODULE_EXPORT void on_btn_macro_import_clicked(GtkButton *button, gpointer user_data); G_MODULE_EXPORT void on_btn_macro_export_clicked(GtkButton *button, gpointer user_data); G_MODULE_EXPORT void on_cell_key_edited(GtkCellRendererText *celltext, const gchar *string_path, const gchar *newkey, gpointer user_data); G_MODULE_EXPORT void on_cell_value_edited(GtkCellRendererText *celltext, const gchar *string_path, const gchar *newvalue, gpointer data); } ibus-unikey-0.7.0~beta1/setup/macro_utils.h0000664000175000017500000000076313441506611020306 0ustar gunnargunnar#ifndef __SETUP_MACRO_UTIL_H__ #define __SETUP_MACRO_UTIL_H__ #include #include "mactab.h" enum {COL_KEY = 0, COL_VALUE}; #define STR_NULL_ITEM "..." gboolean list_store_check_exists(GtkListStore* store, gchar* check_key); void list_store_add_null_item(GtkListStore* list); void list_store_append(GtkListStore* list, CMacroTable* macro); void unikey_macro_to_store(CMacroTable* macro, GtkListStore* store); void unikey_store_to_macro(GtkListStore* store, CMacroTable* macro); #endif ibus-unikey-0.7.0~beta1/setup/ibus-unikey.ui0000664000175000017500000007070113441506611020416 0ustar gunnargunnar telex Extend Telex vni VNI stelex Simple Telex stelex2 Simple Telex 2 600 360 False Macro - ibus-unikey True mouse dialog True False 8 8 8 8 vertical 2 False 8 end gtk-cancel True True True True True True False False 0 gtk-save True True True True True True False False 1 False False 0 True False True True True True list_macro 0 True Word True True 24 0 True Replace with True True 1 True True 0 True False 8 vertical 4 gtk-delete True True True True False True 0 gtk-clear True True True True True False False 1 True False False True 2 _Import... True True True True False False 3 _Export... True True True True False False 4 False True 1 True True 1 btn_cancel btn_save unicode Unicode tcvn3 TCVN3 vni-win VNI Win viqr VIQR bk-hcm2 BK HCM 2 cstr CString ncr-dec NCR Decimal ncr-hex NCR Hex False Settings - ibus-unikey mouse True False 8 8 8 8 vertical True False 0 none True False 12 4 True False Output charset: 0 0 1 True False True list_output_charset 0 1 1 1 True False True list_input_method 0 1 1 0 True False Input method: 0 0 0 True False <b>Input/Output</b> True True True 0 True False 0 none True False 12 vertical Enable _spell check cfg_spell-check True True False True True False True 0 Auto restore non Vietnamese word cfg_auto-restore-non-vn True True False True True False True 1 Use oà, _uý (instead of òa, úy) cfg_modern-style True True False True True False True 2 Allow type with more _freedom cfg_free-marking True True False True True False True 3 True False Enable _macro cfg_macro-enabled True True False True True True True 0 _Edit macro True True True True False True 1 False True 4 Standalone "_W" as "Ư" (Telex only) cfg_standalone-w-as-uw True True False True True False True 5 True False <b>Options</b> True True True 1 True False 8 vertical start gtk-close True True True True False False 0 False True 2 ibus-unikey-0.7.0~beta1/setup/macro_utils.cpp0000664000175000017500000000672113441506611020641 0ustar gunnargunnar#include #include #include "keycons.h" #include "macro_utils.h" #define _(str) gettext(str) gboolean list_store_check_exists(GtkListStore* store, gchar* check_key) { GtkTreeIter iter; gchar* key; auto model = GTK_TREE_MODEL(store); auto b = gtk_tree_model_get_iter_first(model, &iter); while (b) { gtk_tree_model_get(model, &iter, COL_KEY, &key, -1); if (strcasecmp(key, check_key) == 0) { g_free(key); return true; } g_free(key); b = gtk_tree_model_iter_next(model, &iter); } return false; } void list_store_append(GtkListStore* list, CMacroTable* macro) { gchar key[MAX_MACRO_KEY_LEN*3]; gchar value[MAX_MACRO_TEXT_LEN*3]; UKBYTE* p; for (int i = 0 ; i < macro->getCount(); i++) { // get key and convert to XUTF charset p = (UKBYTE*)macro->getKey(i); int inLen = -1; int maxOutLen = sizeof(key); int ret = VnConvert(CONV_CHARSET_VNSTANDARD, CONV_CHARSET_XUTF8, p, (UKBYTE*)key, &inLen, &maxOutLen); if (ret != 0) continue; if (list_store_check_exists(list, key)) continue; // get value and convert to XUTF charset p = (UKBYTE*)macro->getText(i); inLen = -1; maxOutLen = sizeof(value); ret = VnConvert(CONV_CHARSET_VNSTANDARD, CONV_CHARSET_XUTF8, p, (UKBYTE*)value, &inLen, &maxOutLen); if (ret != 0) continue; // append to liststore GtkTreeIter iter; gtk_list_store_append(list, &iter); gtk_list_store_set(list, &iter, COL_KEY, key, COL_VALUE, value, -1); } } void unikey_macro_to_store(CMacroTable* macro, GtkListStore* store) { gtk_list_store_clear(store); list_store_append(store, macro); list_store_add_null_item(store); // select first iter //GtkTreeSelection* select = gtk_tree_view_get_selection(tree_macro); //gtk_tree_model_get_iter_first(GTK_TREE_MODEL(list), &iter); //gtk_tree_selection_select_iter(select, &iter); } void unikey_store_to_macro(GtkListStore* store, CMacroTable* macro) { auto model = GTK_TREE_MODEL(store); GtkTreeIter iter; auto b = gtk_tree_model_get_iter_first(model, &iter); macro->resetContent(); while (b == TRUE) { gchar *key, *value; gtk_tree_model_get(model, &iter, COL_KEY, &key, COL_VALUE, &value, -1); if (strcasecmp(key, STR_NULL_ITEM) != 0) { macro->addItem(key, value, CONV_CHARSET_XUTF8); } g_free(key); g_free(value); b = gtk_tree_model_iter_next(model, &iter); } } void list_store_add_null_item(GtkListStore* list) { GtkTreeIter iter; auto n = gtk_tree_model_iter_n_children(GTK_TREE_MODEL(list), NULL); if (n > 0) { gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(list), &iter, NULL, n-1); gchar *key; gtk_tree_model_get(GTK_TREE_MODEL(list), &iter, COL_KEY, &key, -1); if (strcmp(key, STR_NULL_ITEM) == 0) { g_free(key); return; } g_free(key); } // if last item is valid item or no item in list, add new NULL item gtk_list_store_append(list, &iter); gtk_list_store_set(list, &iter, COL_KEY, STR_NULL_ITEM, COL_VALUE, STR_NULL_ITEM, -1); } ibus-unikey-0.7.0~beta1/CMakeLists.txt0000664000175000017500000000200713441506611017205 0ustar gunnargunnarcmake_minimum_required (VERSION 3.0) project (ibus-unikey) cmake_policy(SET CMP0054 NEW) add_compile_options(-std=c++11 -Werror) list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/cmake) include(GNUInstallDirs) set(LIBEXECDIR "${CMAKE_INSTALL_FULL_LIBEXECDIR}" CACHE string "where to install ibus-{engine,setup}-unikey") set(PKGDATADIR "${CMAKE_INSTALL_FULL_DATADIR}/${PROJECT_NAME}") set(LOCALEDIR "${CMAKE_INSTALL_FULL_LOCALEDIR}") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L ${LIBEXECDIR}") add_definitions( -DPACKAGE_NAME="${PROJECT_NAME}" -DGETTEXT_PACKAGE="${PROJECT_NAME}" -DPACKAGE_VERSION="0.7.0" -DPACKAGE_BUGREPORT="https://github.com/vn-input/ibus-unikey/issues" -DLOCALEDIR="${LOCALEDIR}" -DPKGDATADIR="${PKGDATADIR}" -DLIBEXECDIR="${LIBEXECDIR}" ) include_directories( ${PROJECT_SOURCE_DIR}/ukengine ${PROJECT_SOURCE_DIR}/src/config ) add_subdirectory(ukengine) add_subdirectory(src) add_subdirectory(setup) add_subdirectory(data) add_subdirectory(po) ibus-unikey-0.7.0~beta1/.gitignore0000664000175000017500000000050213441506611016433 0ustar gunnargunnar*.m4 *.in /config.* autom4te.cache/ *.*~ .deps/ stamp-* ABOUT-NLS INSTALL compile configure depcomp install-sh ltmain.sh missing Makefile ibus-unikey.spec libtool po/Makevars.template po/Rules-quot po/boldquot.sed po/*@boldquot.header po/*@quot.header po/insert-header.sin po/quot.sed po/remove-potcdate.sin po/POTFILES ibus-unikey-0.7.0~beta1/data/0000775000175000017500000000000013441506611015357 5ustar gunnargunnaribus-unikey-0.7.0~beta1/data/CMakeLists.txt0000664000175000017500000000007713441506611020123 0ustar gunnargunnarinstall(FILES ibus-unikey.svg DESTINATION ${PKGDATADIR}/icons) ibus-unikey-0.7.0~beta1/data/ibus-unikey.svg0000664000175000017500000001033713441506611020350 0ustar gunnargunnar image/svg+xmlibus-unikey-0.7.0~beta1/.travis.yml0000664000175000017500000000025513441506611016561 0ustar gunnargunnarlanguage: cpp before_install: - sudo apt-get install -y libibus-1.0-dev libgtk-3-dev addons: apt: update: true script: mkdir build && cd build && cmake .. && make ibus-unikey-0.7.0~beta1/po/0000775000175000017500000000000013441506611015064 5ustar gunnargunnaribus-unikey-0.7.0~beta1/po/CMakeLists.txt0000664000175000017500000000032313441506611017622 0ustar gunnargunnarfind_package(Gettext REQUIRED) gettext_process_po_files(vi ALL PO_FILES vi.po) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/vi.gmo" DESTINATION "${LOCALEDIR}/vi/LC_MESSAGES" RENAME "${PROJECT_NAME}.mo") ibus-unikey-0.7.0~beta1/po/vi.po0000664000175000017500000001436013441506611016046 0ustar gunnargunnar# Vietnamese translations for ibus-unikey package # Bản dịch Việt ngữ cho gói tin ibus-unikey. # Copyright (C) 2009 Free Software Foundation, Inc. # This file is distributed under the same license as the ibus-unikey package. # Lê Quốc Tuấn , 2009. # msgid "" msgstr "" "Project-Id-Version: ibus-unikey 0.6.1\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2018-08-17 21:19+0700\n" "PO-Revision-Date: 2018-08-17 21:22+0700\n" "Last-Translator: Lê Quốc Tuấn \n" "Language-Team: Vietnamese\n" "Language: vi_VN\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" "X-Poedit-SourceCharset: utf-8\n" "X-Generator: Poedit 1.8.7.1\n" #: setup/signal_handlers.cpp:16 msgid "(replace text)" msgstr "(chuỗi thay thế)" #: setup/ibus-unikey.ui:410 msgid "Input/Output" msgstr "Nhập/Xuất" #: setup/ibus-unikey.ui:573 msgid "Options" msgstr "Tùy chọn" #: setup/ibus-unikey.ui:489 msgid "Allow type with more _freedom" msgstr "Cho phép bỏ dấu _tự do" #. auto restore property #: src/engine.cpp:336 setup/ibus-unikey.ui:453 msgid "Auto restore non Vietnamese word" msgstr "Tự động trả phím khi không phải tiếng Việt" #. macroEnabled property #: src/engine.cpp:351 msgid "Enable Macro" msgstr "Bật gõ tắt" #: setup/ibus-unikey.ui:511 msgid "Enable _macro" msgstr "Bật _gõ tắt" #: setup/ibus-unikey.ui:435 msgid "Enable _spell check" msgstr "Bật kiểm tra _chính tả" #. spellcheck property #: src/engine.cpp:321 msgid "Enable spell check" msgstr "Bật kiểm tra chính tả" #: setup/signal_handlers.cpp:286 msgid "Export macro" msgstr "Xuất bảng gõ tắt" #: setup/ibus-unikey.ui:15 msgid "Extend Telex" msgstr "Telex mở rộng" #: setup/signal_handlers.cpp:249 msgid "Import macro" msgstr "Nhập bảng gõ tắt" #: setup/ibus-unikey.ui:396 msgid "Input method:" msgstr "Kiểu gõ: " #: setup/ibus-unikey.ui:43 msgid "Macro - ibus-unikey" msgstr "Bảng gõ tắt - ibus-unikey" #. more setting property #: src/engine.cpp:366 msgid "More settings..." msgstr "Thêm tùy chọn..." #: setup/ibus-unikey.ui:342 msgid "Output charset: " msgstr "Bảng mã: " #: setup/ibus-unikey.ui:144 msgid "Replace with" msgstr "Thay thế bởi" #: setup/ibus-unikey.ui:310 msgid "Settings - ibus-unikey" msgstr "Cấu hình - ibus-unikey" #: setup/ibus-unikey.ui:23 msgid "Simple Telex" msgstr "Telex đơn giản" #: setup/ibus-unikey.ui:27 msgid "Simple Telex 2" msgstr "Telex đơn giản 2" #: setup/ibus-unikey.ui:551 msgid "Standalone \"_W\" as \"Ư\" (Telex only)" msgstr "\"_W\" đứng riêng thành \"Ư\" (chỉ Telex)" #: setup/ibus-unikey.ui:471 msgid "Use oà, _uý (instead of òa, úy)" msgstr "Dùng oà, _uý (thay vì òa, úy)" #: setup/ibus-unikey.ui:19 msgid "VNI" msgstr "VNI" #: src/main.cpp:119 msgid "" "Vietnamese Input Method Engine for IBus using Unikey Engine\n" "Usage:\n" " - Choose input method, output charset, options in language bar.\n" " - There are 4 input methods: Telex, Vni, STelex (simple telex) and STelex2 " "(which same as STelex, the difference is it use w as ư).\n" " - And 7 output charsets: Unicode (UTF-8), TCVN3, VNI Win, VIQR, CString, " "NCR Decimal and NCR Hex.\n" " - Use + or + to restore keystrokes.\n" " - Use to commit a word." msgstr "" "Bộ gõ tiếng Việt cho IBus dùng Unikey Engine\n" "Sử dụng:\n" " - Chọn kiểu gõ, bảng mã, tùy chọn trên thanh ngôn ngữ.\n" " - Có 4 kiểu gõ: Telex, Vni, STelex (telex đơn giản) và STelex2 (giống như " "STelex, chỉ khác là nó dùng w như ư).\n" " - Và 7 bảng mã: Unicode (UTF-8), TCVN3, VNI Win, VIQR, CString, NCR Decimal " "và NCR Hex.\n" " - Dùng + hoặc + để khôi phục phím.\n" " - Dùng để xác nhận từ (kết thúc từ)." #: setup/ibus-unikey.ui:127 msgid "Word" msgstr "Từ" #: setup/signal_handlers.cpp:252 setup/signal_handlers.cpp:289 msgid "_Cancel" msgstr "_Cancel" #: setup/ibus-unikey.ui:529 msgid "_Edit macro" msgstr "_Sửa bảng gõ tắt" #: setup/ibus-unikey.ui:232 msgid "_Export..." msgstr "_Xuất..." #: setup/ibus-unikey.ui:217 msgid "_Import..." msgstr "_Nhập..." #: setup/signal_handlers.cpp:253 msgid "_Open" msgstr "_Open" #: setup/signal_handlers.cpp:290 msgid "_Save" msgstr "_Save" #~ msgid "Use _macro" #~ msgstr "Sử dụng gõ tắt" #~ msgid "Auto _restore keys with invalid words" #~ msgstr "Tự động _trả phím khi gõ từ không hợp lệ" #~ msgid "BK HCM 2" #~ msgstr "BK HCM 2" #~ msgid "CString" #~ msgstr "CString" #~ msgid "NCR Decimal" #~ msgstr "NCR Decimal" #~ msgid "NCR Hex" #~ msgstr "NCR Hex" #~ msgid "TCVN3" #~ msgstr "TCVN3" #~ msgid "Unicode" #~ msgstr "Unicode" #~ msgid "VIQR" #~ msgstr "VIQR" #~ msgid "VNI Win" #~ msgstr "VNI Win" #~ msgid "If enable, you can decrease mistake when typing" #~ msgstr "Nếu bật, bạn có thể giảm lỗi chính tả khi gõ" #~ msgid "Capture mouse event" #~ msgstr "Bắt sự kiện chuột" #~ msgid "Auto send PreEdit string to Application when mouse move or click" #~ msgstr "" #~ "Tự động gửi chuỗi PreEdit đến ứng dụng khi chuột di chuyển hoặc click" #~ msgid "Full setup..." #~ msgstr "Cài đặt đầy đủ..." #~ msgid "Full setup utility for IBus-Unikey" #~ msgstr "Tiện ích cài đặt đầy đủ cho IBus-Unikey" #~ msgid "Choose input method" #~ msgstr "Chọn kiểu gõ" #~ msgid "Choose output charset" #~ msgstr "Chọn bảng mã" #~ msgid "Options" #~ msgstr "Tùy chọn" #~ msgid "Options for Unikey" #~ msgstr "Tùy chọn cho Unikey" #~ msgid "Choose file to import" #~ msgstr "Chọn tập tin để nhập" #~ msgid "Choose file to export" #~ msgstr "Chọn tập tin để xuất" #~ msgid "Telex" #~ msgstr "Telex" #~ msgid "Vni" #~ msgstr "Vni" #~ msgid "IBus-Unikey Setup" #~ msgstr "Cài đặt IBus-Unikey" #~ msgid "Process _W at word begin" #~ msgstr "Xử lý phím _W ở đầu từ" #~ msgid "Capture _mouse event" #~ msgstr "Bắt sự _kiện chuột" #~ msgid "Macro table definition" #~ msgstr "Định nghĩa bảng gõ tắt" #~ msgid "Delete _all" #~ msgstr "Xóa _hết" ibus-unikey-0.7.0~beta1/README.md0000664000175000017500000000057413441506611015733 0ustar gunnargunnarIBus-Unikey IME =============== [![Build Status](https://travis-ci.org/vn-input/ibus-unikey.svg?branch=master)](https://travis-ci.org/vn-input/ibus-unikey) ibus-unikey is an [IBus](https://github.com/ibus/ibus) IME. It use Unikey-engine for progress key event. (a modified version of it) ### For install, please visit [wiki](https://github.com/vn-input/ibus-unikey/wiki) page ibus-unikey-0.7.0~beta1/ukengine/0000775000175000017500000000000013441506611016253 5ustar gunnargunnaribus-unikey-0.7.0~beta1/ukengine/charset.h0000664000175000017500000002324013441506611020056 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /*------------------------------------------------------------------------------ VnConv: Vietnamese Encoding Converter Library UniKey Project: http://unikey.sourceforge.net Copyleft (C) 1998-2002 Pham Kim Long Contact: longp@cslab.felk.cvut.cz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --------------------------------------------------------------------------------*/ #ifndef __CHARSET_CONVERT_H #define __CHARSET_CONVERT_H #if !defined(_WIN32) #include #endif #if defined(_WIN32) #if defined(UNIKEYHOOK) #define DllInterface __declspec( dllexport ) #else #define DllInterface __declspec( dllimport ) #endif #else #define DllInterface //not used #define DllExport #define DllImport #endif #include "vnconv.h" #include "byteio.h" #include "pattern.h" #define TOTAL_VNCHARS 213 #define TOTAL_ALPHA_VNCHARS 186 #if defined(_WIN32) typedef unsigned __int32 StdVnChar; typedef unsigned __int16 UnicodeChar; typedef unsigned __int16 UKWORD; typedef unsigned __int32 UKDWORD; #else //typedef unsigned int StdVnChar; //the size should be more specific typedef uint32_t StdVnChar; typedef uint16_t UnicodeChar; typedef uint16_t UKWORD; typedef uint32_t UKDWORD; #endif //typedef unsigned short UnicodeChar; //typedef unsigned short UKWORD; //typedef unsigned int UKDWORD; //the size should be more specific #ifndef LOWORD #define LOWORD(l) ((UKWORD)(l)) #endif #ifndef HIWORD #define HIWORD(l) ((UKWORD)(((UKDWORD)(l) >> 16) & 0xFFFF)) #endif #ifndef MAKEWORD #define MAKEWORD(a, b) ((UKWORD)(((UKBYTE)(a)) | ((UKWORD)((UKBYTE)(b))) << 8)) #endif const StdVnChar VnStdCharOffset = 0x10000; const StdVnChar INVALID_STD_CHAR = 0xFFFFFFFF; //const unsigned char PadChar = '?'; //? is used for VIQR charset const unsigned char PadChar = '#'; const unsigned char PadStartQuote = '\"'; const unsigned char PadEndQuote = '\"'; const unsigned char PadEllipsis = '.'; class DllInterface VnCharset { public: virtual void startInput() {}; virtual void startOutput() {}; // virtual UKBYTE *nextInput(UKBYTE *input, int inLen, StdVnChar & stdChar, int & bytesRead) = 0; virtual int nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead) = 0; //------------------------------------------------------------------------ // put a character to the output after converting it // Arguments: // output[in]: output buffer // stdChar[in]: character in standard charset // outLen[out]: length of converted sequence // maxAvail[in]: max length available. // Returns: next position in output //------------------------------------------------------------------------ virtual int putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen) = 0; virtual int elementSize(); virtual ~VnCharset() {} }; //-------------------------------------------------- class SingleByteCharset: public VnCharset { protected: UKWORD m_stdMap[256]; unsigned char * m_vnChars; public: SingleByteCharset(unsigned char * vnChars); virtual int nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead); virtual int putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen); }; //-------------------------------------------------- class VnInternalCharset: public VnCharset { public: VnInternalCharset() {}; virtual int nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead); virtual int putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen); virtual int elementSize(); }; //-------------------------------------------------- class UnicodeCharset: public VnCharset { protected: UKDWORD m_vnChars[TOTAL_VNCHARS]; UnicodeChar * m_toUnicode; public: UnicodeCharset(UnicodeChar *vnChars); virtual int nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead); virtual int putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen); virtual int elementSize(); }; //-------------------------------------------------- class DoubleByteCharset: public VnCharset { protected: UKWORD m_stdMap[256]; UKDWORD m_vnChars[TOTAL_VNCHARS]; UKWORD * m_toDoubleChar; public: DoubleByteCharset(UKWORD *vnChars); virtual int nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead); virtual int putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen); }; //-------------------------------------------------- class UnicodeUTF8Charset: public UnicodeCharset { public: UnicodeUTF8Charset(UnicodeChar *vnChars) : UnicodeCharset(vnChars) {} virtual int nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead); virtual int putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen); }; //-------------------------------------------------- class UnicodeRefCharset: public UnicodeCharset { public: UnicodeRefCharset(UnicodeChar *vnChars) : UnicodeCharset(vnChars) {} virtual int nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead); virtual int putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen); }; //-------------------------------------------------- class UnicodeHexCharset: public UnicodeRefCharset { public: UnicodeHexCharset(UnicodeChar *vnChars) : UnicodeRefCharset(vnChars) {} virtual int putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen); }; //-------------------------------------------------- class UnicodeCStringCharset: public UnicodeCharset { protected: int m_prevIsHex; public: UnicodeCStringCharset(UnicodeChar *vnChars) : UnicodeCharset(vnChars) {} virtual int nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead); virtual int putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen); virtual void startInput(); }; //-------------------------------------------------- class WinCP1258Charset: public VnCharset { protected: UKWORD m_stdMap[256]; UKDWORD m_vnChars[TOTAL_VNCHARS*2]; UKWORD *m_toDoubleChar; int m_totalChars; public: WinCP1258Charset(UKWORD *compositeChars, UKWORD *precomposedChars); virtual int nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead); virtual int putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen); }; //-------------------------------------------------- struct UniCompCharInfo { UKDWORD compChar; int stdIndex; }; class UnicodeCompCharset: public VnCharset { protected: UniCompCharInfo m_info[TOTAL_VNCHARS*2]; UKDWORD *m_uniCompChars; int m_totalChars; public: UnicodeCompCharset(UnicodeChar *uniChars, UKDWORD *uniCompChars); virtual int nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead); virtual int putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen); virtual int elementSize(); }; //-------------------------------------------------- class VIQRCharset: public VnCharset { protected: UKDWORD *m_vnChars; UKWORD m_stdMap[256]; int m_atWordBeginning; int m_escapeBowl; int m_escapeRoof; int m_escapeHook; int m_escapeTone; int m_gotTone; int m_escAll; int m_noOutEsc; public: int m_suspicious; VIQRCharset(UKDWORD *vnChars); virtual void startInput(); virtual void startOutput(); virtual int nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead); virtual int putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen); }; //-------------------------------------------------- class UTF8VIQRCharset: public VnCharset { protected: VIQRCharset *m_pViqr; UnicodeUTF8Charset *m_pUtf; public: UTF8VIQRCharset(UnicodeUTF8Charset *pUtf, VIQRCharset *pViqr); virtual void startInput(); virtual void startOutput(); virtual int nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead); virtual int putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen); }; //-------------------------------------------------- class DllInterface CVnCharsetLib { protected: SingleByteCharset * m_sgCharsets[CONV_TOTAL_SINGLE_CHARSETS]; DoubleByteCharset * m_dbCharsets[CONV_TOTAL_DOUBLE_CHARSETS]; UnicodeCharset * m_pUniCharset; UnicodeCompCharset * m_pUniCompCharset; UnicodeUTF8Charset * m_pUniUTF8; UnicodeRefCharset * m_pUniRef; UnicodeHexCharset * m_pUniHex; VIQRCharset * m_pVIQRCharObj; UTF8VIQRCharset * m_pUVIQRCharObj; WinCP1258Charset * m_pWinCP1258; UnicodeCStringCharset *m_pUniCString; VnInternalCharset *m_pVnIntCharset; public: PatternList m_VIQREscPatterns, m_VIQROutEscPatterns; VnConvOptions m_options; CVnCharsetLib(); ~CVnCharsetLib(); VnCharset * getVnCharset(int charsetIdx); }; extern unsigned char SingleByteTables[][TOTAL_VNCHARS]; extern UKWORD DoubleByteTables[][TOTAL_VNCHARS]; extern UnicodeChar UnicodeTable[TOTAL_VNCHARS]; extern UKDWORD VIQRTable[TOTAL_VNCHARS]; extern UKDWORD UnicodeComposite[TOTAL_VNCHARS]; extern UKWORD WinCP1258[TOTAL_VNCHARS]; extern UKWORD WinCP1258Pre[TOTAL_VNCHARS]; extern DllInterface CVnCharsetLib VnCharsetLibObj; extern VnConvOptions VnConvGlobalOptions; extern int StdVnNoTone[TOTAL_VNCHARS]; extern int StdVnRootChar[TOTAL_VNCHARS]; DllInterface int genConvert(VnCharset & incs, VnCharset & outcs, ByteInStream & input, ByteOutStream & output); StdVnChar StdVnToUpper(StdVnChar ch); StdVnChar StdVnToLower(StdVnChar ch); StdVnChar StdVnGetRoot(StdVnChar ch); #endif ibus-unikey-0.7.0~beta1/ukengine/usrkeymap.cpp0000664000175000017500000001575013441506611021007 0ustar gunnargunnar// -*- mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /* Unikey Vietnamese Input Method * Copyright (C) 2000-2005 Pham Kim Long * Contact: * unikey@gmail.com * UniKey project: http://unikey.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include #include #include using namespace std; #include #include "usrkeymap.h" int getLabelIndex(int action); void initKeyMap(int keyMap[256]); #define OPT_COMMENT_CHAR ';' struct UkEventLabelPair { char label[32]; int ev; }; UkEventLabelPair UkEvLabelList[] = { {"Tone0", vneTone0}, {"Tone1", vneTone1}, {"Tone2", vneTone2}, {"Tone3", vneTone3}, {"Tone4", vneTone4}, {"Tone5", vneTone5}, {"Roof-All", vneRoofAll}, {"Roof-A", vneRoof_a}, {"Roof-E", vneRoof_e}, {"Roof-O", vneRoof_o}, {"Hook-Bowl", vneHookAll}, {"Hook-UO", vneHook_uo}, {"Hook-U", vneHook_u}, {"Hook-O", vneHook_o}, {"Bowl", vneBowl}, {"D-Mark", vneDd}, {"Telex-W", vne_telex_w}, {"Escape", vneEscChar}, {"DD", vneCount + vnl_DD}, {"dd", vneCount + vnl_dd}, {"A^", vneCount + vnl_Ar}, {"a^", vneCount + vnl_ar}, {"A(", vneCount + vnl_Ab}, {"a(", vneCount + vnl_ab}, {"E^", vneCount + vnl_Er}, {"e^", vneCount + vnl_er}, {"O^", vneCount + vnl_Or}, {"o^", vneCount + vnl_or}, {"O+", vneCount + vnl_Oh}, {"o+", vneCount + vnl_oh}, {"U+", vneCount + vnl_Uh}, {"u+", vneCount + vnl_uh} }; const int UkEvLabelCount = sizeof(UkEvLabelList)/sizeof(UkEventLabelPair); //-------------------------------------------------- static int parseNameValue(char *line, char **name, char **value) { char *p, *mark; char ch; if (line == 0) return 0; // get rid of comment p = strchr(line, OPT_COMMENT_CHAR); if (p) *p = 0; //get option name for (p=line; *p == ' '; p++); if (*p == 0) return 0; *name = p; mark = p; //mark the last non-space character p++; while ((ch=*p) != '=' && ch!=0) { if (ch != ' ') mark = p; p++; } if (ch == 0) return 0; *(mark+1) = 0; //terminate name with a null character //get option value p++; while (*p == ' ') p++; if (*p == 0) return 0; *value = p; mark = p; while (*p) { //strip trailing spaces if (*p != ' ') mark = p; p++; } *++mark = 0; return 1; } //----------------------------------------------------- DllExport int UkLoadKeyMap(const char *fileName, int keyMap[256]) { int i, mapCount; UkKeyMapPair orderMap[256]; if (!UkLoadKeyOrderMap(fileName, orderMap, &mapCount)) return 0; initKeyMap(keyMap); for (i=0; i < mapCount; i++) { keyMap[orderMap[i].key] = orderMap[i].action; if (orderMap[i].action < vneCount) { keyMap[tolower(orderMap[i].key)] = orderMap[i].action; } } return 1; } //------------------------------------------------------------------ DllExport int UkLoadKeyOrderMap(const char *fileName, UkKeyMapPair *pMap, int *pMapCount) { FILE *f; char *buf; char *name, *value; size_t len; int i, bufSize, lineCount; unsigned char c; int mapCount; int keyMap[256]; f = fopen(fileName, "r"); if (f == 0) { cerr << "Failed to open file: " << fileName << endl; return 0; } initKeyMap(keyMap); bufSize = 256; buf = new char[bufSize]; lineCount = 0; mapCount = 0; while (!feof(f)) { if (fgets((char *)buf, bufSize, f) == 0) break; lineCount++; len = strlen(buf); if (len == 0) break; if (buf[len-1] == '\n') buf[len-1] = 0; if (parseNameValue(buf, (char **)&name, (char **)&value)) { if (strlen(name) == 1) { for (i=0; i < UkEvLabelCount; i++) { if (strcmp(UkEvLabelList[i].label, value) == 0) { c = (unsigned char)name[0]; if (keyMap[c] != vneNormal) { //already assigned, don't accept this map break; } //cout << "key: " << c << " value: " << UkEvLabelList[i].ev << endl; //DEBUG keyMap[c] = UkEvLabelList[i].ev; pMap[mapCount].action = UkEvLabelList[i].ev; if (keyMap[c] < vneCount) { pMap[mapCount].key = toupper(c); keyMap[toupper(c)] = UkEvLabelList[i].ev; } else { pMap[mapCount].key = c; } mapCount++; break; } } if (i == UkEvLabelCount) { cerr << "Error in user key layout, line " << lineCount << ": command not found" << endl; } } else { cerr << "Error in user key layout, line " << lineCount << ": key name is not a single character" << endl; } } } delete [] buf; fclose(f); *pMapCount = mapCount; return 1; } //------------------------------------------- void initKeyMap(int keyMap[256]) { unsigned int c; for (c=0; c<256; c++) keyMap[c] = vneNormal; } const char *UkKeyMapHeader = "; This is UniKey user-defined key mapping file, generated from UniKey (Windows)\n\n"; DllExport int UkStoreKeyOrderMap(const char *fileName, UkKeyMapPair *pMap, int mapCount) { FILE *f; int i; int labelIndex; char line[128]; f = fopen(fileName, "wt"); if (f == 0) { cerr << "Failed to open file: " << fileName << endl; return 0; } fputs(UkKeyMapHeader, f); for (i=0; i < mapCount; i++) { labelIndex = getLabelIndex(pMap[i].action); if (labelIndex != -1) { sprintf(line, "%c = %s\n", pMap[i].key, UkEvLabelList[labelIndex].label); fputs(line, f); } } fclose(f); return 1; } int getLabelIndex(int event) { int i; for (i = 0; i < UkEvLabelCount; i++) { if (UkEvLabelList[i].ev == event) return i; } return -1; } ibus-unikey-0.7.0~beta1/ukengine/mactab.cpp0000664000175000017500000002250413441506611020211 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /* Unikey Vietnamese Input Method * Copyright (C) 2000-2005 Pham Kim Long * Contact: * unikey@gmail.com * UniKey project: http://unikey.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include #include #include #include #include "mactab.h" #include "vnconv.h" using namespace std; #define UKMACRO_VERSION_UTF8 1 //--------------------------------------------------------------- void CMacroTable::init() { m_memSize = MACRO_MEM_SIZE; m_count = 0; m_occupied = 0; } //--------------------------------------------------------------- char *MacCompareStartMem; #define STD_TO_LOWER(x) (((x) >= VnStdCharOffset && \ (x) < (VnStdCharOffset + TOTAL_ALPHA_VNCHARS) && \ !((x) & 1)) ? \ (x+1) : (x)) int macCompare(const void *p1, const void *p2) { StdVnChar *s1 = (StdVnChar *) ((char *)MacCompareStartMem + ((MacroDef *)p1)->keyOffset); StdVnChar *s2 = (StdVnChar *) ((char *)MacCompareStartMem + ((MacroDef *)p2)->keyOffset); int i; StdVnChar ls1, ls2; for (i=0; s1[i] != 0 && s2[i] != 0; i++) { ls1 = STD_TO_LOWER(s1[i]); ls2 = STD_TO_LOWER(s2[i]); if (ls1 > ls2) return 1; if (ls1 < ls2) return -1; /* if (s1[i] > s2[i]) return 1; if (s1[i] < s2[i]) return -1; */ } if (s1[i] == 0) return (s2[i] == 0)? 0 : -1; return 1; } //--------------------------------------------------------------- int macKeyCompare(const void *key, const void *ele) { StdVnChar *s1 = (StdVnChar *)key; StdVnChar *s2 = (StdVnChar *) ((char *)MacCompareStartMem + ((MacroDef *)ele)->keyOffset); StdVnChar ls1, ls2; int i; for (i=0; s1[i] != 0 && s2[i] != 0; i++) { ls1 = STD_TO_LOWER(s1[i]); ls2 = STD_TO_LOWER(s2[i]); if (ls1 > ls2) return 1; if (ls1 < ls2) return -1; /* if (s1[i] > s2[i]) return 1; if (s1[i] < s2[i]) return -1; */ } if (s1[i] == 0) return (s2[i] == 0)? 0 : -1; return 1; } //--------------------------------------------------------------- const StdVnChar *CMacroTable::lookup(StdVnChar *key) { MacCompareStartMem = m_macroMem; MacroDef *p = (MacroDef *)bsearch(key, m_table, m_count, sizeof(MacroDef), macKeyCompare); if (p) return (StdVnChar *)(m_macroMem + p->textOffset); return 0; } //---------------------------------------------------------------------------- // Read header, if it's present in the file. Get the version of the file // If header is absent, go back to the beginning of file and set version to 0 // Return false if reading failed. // // Header format: ;[DO NOT DELETE THIS LINE]***version=n //---------------------------------------------------------------------------- bool CMacroTable::readHeader(FILE *f, int & version) { char line[MAX_MACRO_LINE]; if (!fgets(line, sizeof(line), f)) { if (feof(f)) { fseek(f, 0, SEEK_SET); version = 0; return true; } return false; } //if BOM is available, skip it char *p = line; size_t len = strlen(line); if (len >= 3 && (unsigned char)line[0] == 0xEF && (unsigned char)line[1] == 0xBB && (unsigned char)line[2] == 0xBF) { p += 3; } //read version number p = strstr(p, "***"); if (p) { p += 3; //skip possible spaces while (*p == ' ') p++; if (sscanf(p, "version=%d", &version) == 1) return true; } fseek(f, 0, SEEK_SET); version = 0; return true; } //---------------------------------------------------------------- void CMacroTable::writeHeader(FILE *f) { #if defined(WIN32) fprintf(f, "\xEF\xBB\xBF;DO NOT DELETE THIS LINE*** version=%d ***\n", UKMACRO_VERSION_UTF8); #else fprintf(f, "DO NOT DELETE THIS LINE*** version=%d ***\n", UKMACRO_VERSION_UTF8); #endif } //--------------------------------------------------------------- int CMacroTable::loadFromFile(const char *fname) { FILE *f; #if defined(WIN32) f = _tfopen(fname, _TEXT("rt")); #else f = fopen(fname, "r"); #endif if (f == NULL) return 0; char line[MAX_MACRO_LINE]; size_t len; resetContent(); //read possible header int version; if (!readHeader(f, version)) { version = 0; } while (fgets(line, sizeof(line), f)) { len = strlen(line); if (len > 0 && line[len-1] == '\n') line[len-1] = 0; if (len > 1 && line[len-2] == '\r') line[len-2] = 0; if (version == UKMACRO_VERSION_UTF8) addItem(line, CONV_CHARSET_UNIUTF8); else addItem(line, CONV_CHARSET_VIQR); } fclose(f); MacCompareStartMem = m_macroMem; qsort(m_table, m_count, sizeof(MacroDef), macCompare); // Convert old version if (version != UKMACRO_VERSION_UTF8) { writeToFile(fname); } return 1; } //--------------------------------------------------------------- int CMacroTable::writeToFile(const char *fname) { int ret; int inLen, maxOutLen; FILE *f; #if defined(WIN32) f = _tfopen(fname, _TEXT("wt")); #else f = fopen(fname, "w"); #endif if (f == NULL) return 0; char line[MAX_MACRO_LINE*3+1]; //1 VnChar may need 3 chars in UTF8 char key[MAX_MACRO_KEY_LEN*3]; char text[MAX_MACRO_TEXT_LEN*3]; writeHeader(f); UKBYTE *p; for (int i=0; i < m_count; i++) { p = (UKBYTE *)m_macroMem + m_table[i].keyOffset; inLen = -1; maxOutLen = sizeof(key); ret = VnConvert(CONV_CHARSET_VNSTANDARD, CONV_CHARSET_UNIUTF8, (UKBYTE *) p, (UKBYTE *)key, &inLen, &maxOutLen); if (ret != 0) continue; p = (UKBYTE *)m_macroMem + m_table[i].textOffset; inLen = -1; maxOutLen = sizeof(text); ret = VnConvert(CONV_CHARSET_VNSTANDARD, CONV_CHARSET_UNIUTF8, p, (UKBYTE *)text, &inLen, &maxOutLen); if (ret != 0) continue; if (i < m_count-1) sprintf(line, "%s:%s\n", key, text); else sprintf(line, "%s:%s", key, text); fputs(line, f); } fclose(f); return 1; } //--------------------------------------------------------------- int CMacroTable::addItem(const void *key, const void *text, int charset) { int ret; int inLen, maxOutLen; int offset = m_occupied; char *p = m_macroMem + offset; if (m_count >= MAX_MACRO_ITEMS) return -1; m_table[m_count].keyOffset = offset; // Convert macro key to VN standard inLen = -1; //input is null-terminated maxOutLen = MAX_MACRO_KEY_LEN * sizeof(StdVnChar); if (maxOutLen + offset > m_memSize) maxOutLen = m_memSize - offset; ret = VnConvert(charset, CONV_CHARSET_VNSTANDARD, (UKBYTE *)key, (UKBYTE *)p, &inLen, &maxOutLen); if (ret != 0) return -1; offset += maxOutLen; p += maxOutLen; //convert macro text to VN standard m_table[m_count].textOffset = offset; inLen = -1; //input is null-terminated maxOutLen = MAX_MACRO_TEXT_LEN * sizeof(StdVnChar); if (maxOutLen + offset > m_memSize) maxOutLen = m_memSize - offset; ret = VnConvert(charset, CONV_CHARSET_VNSTANDARD, (UKBYTE *)text, (UKBYTE *)p, &inLen, &maxOutLen); if (ret != 0) return -1; m_occupied = offset + maxOutLen; m_count++; return (m_count-1); } //--------------------------------------------------------------- // add a new macro into the sorted macro table // item format: key:text (key and text are separated by a colon) //--------------------------------------------------------------- int CMacroTable::addItem(const char *item, int charset) { char key[MAX_MACRO_KEY_LEN]; // Parse the input item char * pos = (char*)strchr(item, ':'); if (pos == NULL) return -1; int keyLen = (int)(pos - item); if (keyLen > MAX_MACRO_KEY_LEN-1) keyLen = MAX_MACRO_KEY_LEN-1; strncpy(key, item, keyLen); key[keyLen] = '\0'; return addItem(key, ++pos, charset); } //--------------------------------------------------------------- void CMacroTable::resetContent() { m_occupied = 0; m_count = 0; } //--------------------------------------------------------------- const StdVnChar *CMacroTable::getKey(int idx) { if (idx < 0 || idx >= m_count) return 0; return (StdVnChar *)(m_macroMem + m_table[idx].keyOffset); } //--------------------------------------------------------------- const StdVnChar *CMacroTable::getText(int idx) { if (idx < 0 || idx >= m_count) return 0; return (StdVnChar *)(m_macroMem + m_table[idx].textOffset); } ibus-unikey-0.7.0~beta1/ukengine/LICENSE0000664000175000017500000006131413441506611017265 0ustar gunnargunnar GNU LIBRARY GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the library GPL. It is numbered 2 because it goes with version 2 of the ordinary GPL.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to any other libraries whose authors decide to use it. You can use it for your libraries, 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library, after making changes to the library and recompiling it. And you must show them these terms so they know their rights. Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the library. Also, for each distributor's protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don't assume that anything in it is the same as in the ordinary license. The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such. Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better. However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, while the latter only works together with the library. Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one. GNU LIBRARY GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also compile or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. c) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. d) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Library 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307 USA. Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! ibus-unikey-0.7.0~beta1/ukengine/pattern.cpp0000664000175000017500000000555213441506611020443 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /*------------------------------------------------------------------------------ VnConv: Vietnamese Encoding Converter Library UniKey Project: http://unikey.sourceforge.net Copyleft (C) 1998-2002 Pham Kim Long Contact: longp@cslab.felk.cvut.cz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --------------------------------------------------------------------------------*/ #include "pattern.h" ////////////////////////////////////////////////// // Pattern matching (based on KPM algorithm) ////////////////////////////////////////////////// //---------------------------- void PatternState::reset() { m_pos = 0; m_found = 0; } //---------------------------- void PatternState::init(char *pattern) { m_pos = 0; m_found = 0; m_pattern = pattern; int i=0, j=-1; m_border[i]=j; while (m_pattern[i]) { while (j>=0 && m_pattern[i]!=m_pattern[j]) j=m_border[j]; i++; j++; m_border[i]=j; } } //----------------------------------------------------- //get next input char, returns 1 if pattern is found. //----------------------------------------------------- int PatternState::foundAtNextChar(char ch) { int ret = 0; //int j = m_pos; while (m_pos>=0 && ch!=m_pattern[m_pos]) m_pos=m_border[m_pos]; m_pos++; if (m_pattern[m_pos]==0) { m_found++; m_pos = m_border[m_pos]; ret = 1; } return ret; } //----------------------------------------------------- void PatternList::init(char **patterns, int count) { m_count = count; delete [] m_patterns; m_patterns = new PatternState[count]; for (int i=0; i #include "inputproc.h" using namespace std; /* unsigned char WordBreakSyms[] = { ',', ';', ':', '.', '\"', '\'', '!', '?', ' ', '<', '>', '=', '+', '-', '*', '/', '\\', '_', '~', '`', '@', '#', '$', '%', '^', '&', '(', ')', '{', '}', '[', ']'}; */ unsigned char WordBreakSyms[] = { ',', ';', ':', '.', '\"', '\'', '!', '?', ' ', '<', '>', '=', '+', '-', '*', '/', '\\', '_', '@', '#', '$', '%', '&', '(', ')', '{', '}', '[', ']', '|'}; //we excluded ~, `, ^ VnLexiName AZLexiUpper[] = {vnl_A, vnl_B, vnl_C, vnl_D, vnl_E, vnl_F, vnl_G, vnl_H, vnl_I, vnl_J, vnl_K, vnl_L, vnl_M, vnl_N, vnl_O, vnl_P, vnl_Q, vnl_R, vnl_S, vnl_T, vnl_U, vnl_V, vnl_W, vnl_X, vnl_Y, vnl_Z}; VnLexiName AZLexiLower[] = {vnl_a, vnl_b, vnl_c, vnl_d, vnl_e, vnl_f, vnl_g, vnl_h, vnl_i, vnl_j, vnl_k, vnl_l, vnl_m, vnl_n, vnl_o, vnl_p, vnl_q, vnl_r, vnl_s, vnl_t, vnl_u, vnl_v, vnl_w, vnl_x, vnl_y, vnl_z}; UkCharType UkcMap[256]; struct _ascVnLexi { int asc; VnLexiName lexi; }; //List of western characters outside range A-Z that are //also Vietnamese characters _ascVnLexi AscVnLexiList[] = { {0xC0, vnl_A2}, {0xC1, vnl_A1}, {0xC2, vnl_Ar}, {0xC2, vnl_A4}, {0xC8, vnl_E2}, {0xC9, vnl_E1}, {0xCA, vnl_Er}, {0xCC, vnl_I2}, {0xCD, vnl_I1}, {0xD2, vnl_O2}, {0xD3, vnl_O1}, {0xD4, vnl_Or}, {0xD5, vnl_O4}, {0xD9, vnl_U2}, {0xDA, vnl_U1}, {0xDD, vnl_Y1}, {0xE0, vnl_a2}, {0xE1, vnl_a1}, {0xE2, vnl_ar}, {0xE3, vnl_a4}, {0xE8, vnl_e2}, {0xE9, vnl_e1}, {0xEA, vnl_er}, {0xEC, vnl_i2}, {0xED, vnl_i1}, {0xF2, vnl_o2}, {0xF3, vnl_o1}, {0xF4, vnl_or}, {0xF5, vnl_o4}, {0xF9, vnl_u2}, {0xFA, vnl_u1}, {0xFD, vnl_y1}, {0x00, vnl_nonVnChar} }; VnLexiName IsoVnLexiMap[256]; bool ClassifierTableInitialized = false; DllExport UkKeyMapping TelexMethodMapping[] = { {'Z', vneTone0}, {'S', vneTone1}, {'F', vneTone2}, {'R', vneTone3}, {'X', vneTone4}, {'J', vneTone5}, {'W', vne_telex_w}, {'A', vneRoof_a}, {'E', vneRoof_e}, {'O', vneRoof_o}, {'D', vneDd}, {'[', vneCount + vnl_oh}, {']', vneCount + vnl_uh}, {'{', vneCount + vnl_Oh}, {'}', vneCount + vnl_Uh}, {0, vneNormal} }; DllExport UkKeyMapping SimpleTelexMethodMapping[] = { {'Z', vneTone0}, {'S', vneTone1}, {'F', vneTone2}, {'R', vneTone3}, {'X', vneTone4}, {'J', vneTone5}, {'W', vneHookAll}, {'A', vneRoof_a}, {'E', vneRoof_e}, {'O', vneRoof_o}, {'D', vneDd}, {0, vneNormal} }; DllExport UkKeyMapping SimpleTelex2MethodMapping[] = { {'Z', vneTone0}, {'S', vneTone1}, {'F', vneTone2}, {'R', vneTone3}, {'X', vneTone4}, {'J', vneTone5}, {'W', vne_telex_w}, {'A', vneRoof_a}, {'E', vneRoof_e}, {'O', vneRoof_o}, {'D', vneDd}, {0, vneNormal} }; DllExport UkKeyMapping VniMethodMapping[] = { {'0', vneTone0}, {'1', vneTone1}, {'2', vneTone2}, {'3', vneTone3}, {'4', vneTone4}, {'5', vneTone5}, {'6', vneRoofAll}, {'7', vneHook_uo}, {'8', vneBowl}, {'9', vneDd}, {0, vneNormal} }; DllExport UkKeyMapping VIQRMethodMapping[] = { {'0', vneTone0}, {'\'', vneTone1}, {'`', vneTone2}, {'?', vneTone3}, {'~', vneTone4}, {'.', vneTone5}, {'^', vneRoofAll}, {'+', vneHook_uo}, {'*', vneHook_uo}, {'(', vneBowl}, {'D', vneDd}, {'\\', vneEscChar}, {0, vneNormal} }; DllExport UkKeyMapping MsViMethodMapping[] = { {'5', vneTone2}, {'%', vneTone2}, {'6', vneTone3}, {'^', vneTone3}, {'7', vneTone4}, {'&', vneTone4}, {'8', vneTone1}, {'*', vneTone1}, {'9', vneTone5}, {'(', vneTone5}, {'1', vneCount + vnl_ab}, {'!', vneCount + vnl_Ab}, {'2', vneCount + vnl_ar}, {'@', vneCount + vnl_Ar}, {'3', vneCount + vnl_er}, {'#', vneCount + vnl_Er}, {'4', vneCount + vnl_or}, {'$', vneCount + vnl_Or}, {'0', vneCount + vnl_dd}, {')', vneCount + vnl_DD}, {'[', vneCount + vnl_uh}, {']', vneCount + vnl_oh}, {'{', vneCount + vnl_Uh}, {'}', vneCount + vnl_Oh}, {0, vneNormal} }; //------------------------------------------- void SetupInputClassifierTable() { unsigned int c; int i; for (c=0; c<=32; c++) { UkcMap[c] = ukcReset; } for (c=33; c<256; c++) { UkcMap[c] = ukcNonVn; } /* for (c = '0'; c <= '9'; c++) UkcMap[c] = ukcNonVn; */ for (c = 'a'; c <= 'z'; c++) UkcMap[c] = ukcVn; for (c = 'A'; c <= 'Z'; c++) UkcMap[c] = ukcVn; for (i=0; AscVnLexiList[i].asc; i++) { UkcMap[AscVnLexiList[i].asc] = ukcVn; } UkcMap[(unsigned char)'j'] = ukcNonVn; UkcMap[(unsigned char)'J'] = ukcNonVn; UkcMap[(unsigned char)'f'] = ukcNonVn; UkcMap[(unsigned char)'F'] = ukcNonVn; UkcMap[(unsigned char)'w'] = ukcNonVn; UkcMap[(unsigned char)'W'] = ukcNonVn; int count = sizeof(WordBreakSyms)/sizeof(unsigned char); for (i = 0; i < count; i++) UkcMap[WordBreakSyms[i]] = ukcWordBreak; //Calculate IsoVnLexiMap for (i = 0; i < 256; i++) { IsoVnLexiMap[i] = vnl_nonVnChar; } for (i = 0; AscVnLexiList[i].asc; i++) { IsoVnLexiMap[AscVnLexiList[i].asc] = AscVnLexiList[i].lexi; } for (c = 'a'; c <= 'z'; c++) { IsoVnLexiMap[c] = AZLexiLower[c - 'a']; } for (c = 'A'; c <= 'Z'; c++) { IsoVnLexiMap[c] = AZLexiUpper[c - 'A']; } } //------------------------------------------- void UkInputProcessor::init() { if (!ClassifierTableInitialized) { SetupInputClassifierTable(); ClassifierTableInitialized = true; } setIM(UkTelex); } //------------------------------------------- int UkInputProcessor::setIM(UkInputMethod im) { m_im = im; switch (im) { case UkTelex: useBuiltIn(TelexMethodMapping); break; case UkSimpleTelex: useBuiltIn(SimpleTelexMethodMapping); break; case UkSimpleTelex2: useBuiltIn(SimpleTelex2MethodMapping); break; case UkVni: useBuiltIn(VniMethodMapping); break; case UkViqr: useBuiltIn(VIQRMethodMapping); break; case UkMsVi: useBuiltIn(MsViMethodMapping); break; default: m_im = UkTelex; useBuiltIn(TelexMethodMapping); } return 1; } //------------------------------------------- int UkInputProcessor::setIM(int map[256]) { int i; m_im = UkUsrIM; for (i=0; i<256; i++) m_keyMap[i] = map[i]; return 1; } //------------------------------------------- void UkResetKeyMap(int keyMap[256]) { unsigned int c; for (c=0; c<256; c++) keyMap[c] = vneNormal; } //------------------------------------------- void UkInputProcessor::useBuiltIn(UkKeyMapping *map) { UkResetKeyMap(m_keyMap); for (int i=0; map[i].key; i++) { m_keyMap[map[i].key] = map[i].action; if (map[i].action < vneCount) { if (islower(map[i].key)) { m_keyMap[toupper(map[i].key)] = map[i].action; } else if (isupper(map[i].key)) { m_keyMap[tolower(map[i].key)] = map[i].action; } } } } //------------------------------------------- void UkInputProcessor::keyCodeToEvent(unsigned int keyCode, UkKeyEvent & ev) { ev.keyCode = keyCode; if (keyCode > 255) { ev.evType = vneNormal; ev.vnSym = IsoToVnLexi(keyCode); ev.chType = (ev.vnSym == vnl_nonVnChar)? ukcNonVn : ukcVn; } else { ev.chType = UkcMap[keyCode]; ev.evType = m_keyMap[keyCode]; if (ev.evType >= vneTone0 && ev.evType <= vneTone5) { ev.tone = ev.evType - vneTone0; } if (ev.evType >= vneCount) { ev.chType = ukcVn; ev.vnSym = (VnLexiName)(ev.evType - vneCount); ev.evType = vneMapChar; } else { ev.vnSym = IsoToVnLexi(keyCode); } } } //---------------------------------------------------------------- // This method translates a key stroke to a symbol. // Key strokes are simply considered character input, not action keys as in // keyCodeToEvent method //---------------------------------------------------------------- void UkInputProcessor::keyCodeToSymbol(unsigned int keyCode, UkKeyEvent & ev) { ev.keyCode = keyCode; ev.evType = vneNormal; ev.vnSym = IsoToVnLexi(keyCode); if (keyCode > 255) { ev.chType = (ev.vnSym == vnl_nonVnChar)? ukcNonVn : ukcVn; } else { ev.chType = UkcMap[keyCode]; } } //------------------------------------------- UkCharType UkInputProcessor::getCharType(unsigned int keyCode) { if (keyCode > 255) return (IsoToVnLexi(keyCode) == vnl_nonVnChar) ? ukcNonVn : ukcVn; return UkcMap[keyCode]; } //------------------------------------------- void UkInputProcessor::getKeyMap(int map[256]) { int i; for (i=0; i<256; i++) map[i] = m_keyMap[i]; } ibus-unikey-0.7.0~beta1/ukengine/unikey.h0000664000175000017500000001024313441506611017730 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /*------------------------------------------------------------------------------ UniKey - Open-source Vietnamese Keyboard Copyright (C) 2000-2005 Pham Kim Long Contact: unikey@gmail.com http://unikey.org This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --------------------------------------------------------------------------------*/ #ifndef __UNIKEY_H #define __UNIKEY_H #include "keycons.h" /*---------------------------------------------------- Initialization steps: 1. UnikeySetup: This will initialized Unikey module, with default options, input method = TELEX, output format = UTF-8 2. If you want a different settings: + Call UnikeySetInputMethod to change input method + Call UnikeySetOutputVIQR/UTF8 to chang output format + Call UnikeySetOptions to change extra options Key event handling: - Call UnikeyFilter when a key event occurs, examine results in + UnikeyBackspaces: number of backspaces that need to be sent + UnikeyBufChars: number of chars in buffer that need to be sent + UnikeyAnsiBuf: buffer containing output characters. + UnikeyUniBuf: not used You should also call UnikeySetCapsState() before calling UnikeyFilter. To make this module portable across platforms, UnikeyFilter should not be called on special keys: Enter, Tab, movement keys, delete, backspace... - Special events: + Call UnikeyResetBuf to reset the engine's state in situations such as: focus lost, movement keys: arrow keys, pgup, pgdown.... + If a backspace is received, call UnikeyBackspacePress, then examine the result: UnikeyBackspaces is the number of backspaces actually required to remove one character. Clean up: - When the Engine is no longer needed, call UnikeyCleanup ------------------------------------------------------*/ #if defined(__cplusplus) extern "C" { #endif extern unsigned char UnikeyBuf[]; extern int UnikeyBackspaces; extern int UnikeyBufChars; extern UkOutputType UnikeyOutput; void UnikeySetup(); // always call this first void UnikeyCleanup(); // call this when unloading unikey module // call this to reset Unikey's state when focus, context is changed or // some control key is pressed void UnikeyResetBuf(); // main handler, call every time a character input is received void UnikeyFilter(unsigned int ch); void UnikeyPutChar(unsigned int ch); // put new char without filtering // call this before UnikeyFilter for correctly processing some TELEX shortcuts void UnikeySetCapsState(int shiftPressed, int CapsLockOn); // call this when backspace is pressed void UnikeyBackspacePress(); // call this to restore to original key strokes void UnikeyRestoreKeyStrokes(); //set extra options void UnikeySetOptions(UnikeyOptions *pOpt); void CreateDefaultUnikeyOptions(UnikeyOptions *pOpt); void UnikeyGetOptions(UnikeyOptions *pOpt); // set input method // im: TELEX_INPUT, VNI_INPUT, VIQR_INPUT, VIQR_STAR_INPUT void UnikeySetInputMethod(UkInputMethod im); // set output format // void UnikeySetOutputVIQR(); // void UnikeySetOutputUTF8(); int UnikeySetOutputCharset(int charset); int UnikeyLoadMacroTable(const char *fileName); int UnikeyLoadUserKeyMap(const char *fileName); //call this to enable typing vietnamese even in a non-vn sequence //e.g: GD&DDT,QDDND... //The engine will return to normal mode when a word-break occurs. void UnikeySetSingleMode(); bool UnikeyAtWordBeginning(); #if defined(__cplusplus) } #endif #endif ibus-unikey-0.7.0~beta1/ukengine/data.h0000664000175000017500000000102713441506611017335 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- #ifndef VIETNAMESE_CHARSET_DATA_H #define VIETNAMESE_CHARSET_DATA_H // This header defines some special characters const StdVnChar StdStartQuote = (VnStdCharOffset + 201); // 0x93 in the Western charset // 201 is the offset of character 0x93 (start quote) in Vn charsets const StdVnChar StdEndQuote = (VnStdCharOffset + 202); // 0x94 in the Western charset const StdVnChar StdEllipsis = (VnStdCharOffset + 190); // 0x85 in Western charet. #endif ibus-unikey-0.7.0~beta1/ukengine/vnlexi.h0000664000175000017500000000705113441506611017734 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /* Unikey Vietnamese Input Method * Copyright (C) 2000-2005 Pham Kim Long * Contact: * unikey@gmail.com * UniKey project: http://unikey.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __VN_LEXI_H #define __VN_LEXI_H enum VnLexiName { vnl_nonVnChar = -1, vnl_A, vnl_a, vnl_A1, vnl_a1, vnl_A2, vnl_a2, vnl_A3, vnl_a3, vnl_A4, vnl_a4, vnl_A5, vnl_a5, vnl_Ar, vnl_ar, vnl_Ar1, vnl_ar1, vnl_Ar2, vnl_ar2, vnl_Ar3, vnl_ar3, vnl_Ar4, vnl_ar4, vnl_Ar5, vnl_ar5, vnl_Ab, vnl_ab, vnl_Ab1, vnl_ab1, vnl_Ab2, vnl_ab2, vnl_Ab3, vnl_ab3, vnl_Ab4, vnl_ab4, vnl_Ab5, vnl_ab5, vnl_B, vnl_b, vnl_C, vnl_c, vnl_D, vnl_d, vnl_DD, vnl_dd, vnl_E, vnl_e, vnl_E1, vnl_e1, vnl_E2, vnl_e2, vnl_E3, vnl_e3, vnl_E4, vnl_e4, vnl_E5, vnl_e5, vnl_Er, vnl_er, vnl_Er1, vnl_er1, vnl_Er2, vnl_er2, vnl_Er3, vnl_er3, vnl_Er4, vnl_er4, vnl_Er5, vnl_er5, vnl_F, vnl_f, vnl_G, vnl_g, vnl_H, vnl_h, vnl_I, vnl_i, vnl_I1, vnl_i1, vnl_I2, vnl_i2, vnl_I3, vnl_i3, vnl_I4, vnl_i4, vnl_I5, vnl_i5, vnl_J, vnl_j, vnl_K, vnl_k, vnl_L, vnl_l, vnl_M, vnl_m, vnl_N, vnl_n, vnl_O, vnl_o, vnl_O1, vnl_o1, vnl_O2, vnl_o2, vnl_O3, vnl_o3, vnl_O4, vnl_o4, vnl_O5, vnl_o5, vnl_Or, vnl_or, vnl_Or1, vnl_or1, vnl_Or2, vnl_or2, vnl_Or3, vnl_or3, vnl_Or4, vnl_or4, vnl_Or5, vnl_or5, vnl_Oh, vnl_oh, vnl_Oh1, vnl_oh1, vnl_Oh2, vnl_oh2, vnl_Oh3, vnl_oh3, vnl_Oh4, vnl_oh4, vnl_Oh5, vnl_oh5, vnl_P, vnl_p, vnl_Q, vnl_q, vnl_R, vnl_r, vnl_S, vnl_s, vnl_T, vnl_t, vnl_U, vnl_u, vnl_U1, vnl_u1, vnl_U2, vnl_u2, vnl_U3, vnl_u3, vnl_U4, vnl_u4, vnl_U5, vnl_u5, vnl_Uh, vnl_uh, vnl_Uh1, vnl_uh1, vnl_Uh2, vnl_uh2, vnl_Uh3, vnl_uh3, vnl_Uh4, vnl_uh4, vnl_Uh5, vnl_uh5, vnl_V, vnl_v, vnl_W, vnl_w, vnl_X, vnl_x, vnl_Y, vnl_y, vnl_Y1, vnl_y1, vnl_Y2, vnl_y2, vnl_Y3, vnl_y3, vnl_Y4, vnl_y4, vnl_Y5, vnl_y5, vnl_Z, vnl_z, vnl_lastChar, }; enum VowelSeq { vs_nil = -1, vs_a, vs_ar, vs_ab, vs_e, vs_er, vs_i, vs_o, vs_or, vs_oh, vs_u, vs_uh, vs_y, vs_ai, vs_ao, vs_au, vs_ay, vs_aru, vs_ary, vs_eo, vs_eu, vs_eru, vs_ia, vs_ie, vs_ier, vs_iu, vs_oa, vs_oab, vs_oe, vs_oi, vs_ori, vs_ohi, vs_ua, vs_uar, vs_ue, vs_uer, vs_ui, vs_uo, vs_uor, vs_uoh, vs_uu, vs_uy, vs_uha, vs_uhi, vs_uho, vs_uhoh, vs_uhu, vs_ye, vs_yer, vs_ieu, vs_ieru, vs_oai, vs_oay, vs_oeo, vs_uay, vs_uary, vs_uoi, vs_uou, vs_uori, vs_uohi, vs_uohu, vs_uya, vs_uye, vs_uyer, vs_uyu, vs_uhoi, vs_uhou, vs_uhohi, vs_uhohu, vs_yeu, vs_yeru }; enum ConSeq { cs_nil = -1, cs_b, cs_c, cs_ch, cs_d, cs_dd, cs_dz, cs_g, cs_gh, cs_gi, cs_gin, cs_h, cs_k, cs_kh, cs_l, cs_m, cs_n, cs_ng, cs_ngh, cs_nh, cs_p, cs_ph, cs_q, cs_qu, cs_r, cs_s, cs_t, cs_th, cs_tr, cs_v, cs_x }; #endif ibus-unikey-0.7.0~beta1/ukengine/byteio.cpp0000664000175000017500000002270713441506611020262 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- #include #include "byteio.h" //------------------------------------------------ StringBIStream::StringBIStream(UKBYTE *data, int len, int elementSize) { m_data = m_current = data; m_len = m_left = len; if (len == -1) { if (elementSize == 2) m_eos = (*(UKWORD *)data == 0); else if (elementSize == 4) m_eos = (*(UKDWORD *)data == 4); else m_eos = (*data == 0); } else m_eos = (len <= 0); m_didBookmark = 0; } //------------------------------------------------ int StringBIStream::eos() { return m_eos; } //------------------------------------------------ int StringBIStream::getNext(UKBYTE & b) { if (m_eos) return 0; b = *m_current++; if (m_len == -1) { m_eos = (b == 0); } else { m_left--; m_eos = (m_left <= 0); } return 1; } //------------------------------------------------ int StringBIStream::unget(UKBYTE b) { if (m_current != m_data) { *--m_current = b; m_eos = 0; if (m_len != -1) m_left++; } return 1; } //------------------------------------------------ int StringBIStream::getNextW(UKWORD & w) { if (m_eos) return 0; w = *((UKWORD *)m_current); m_current += 2; if (m_len == -1) m_eos = (w == 0); else { m_left -= 2; m_eos = (m_left <= 0); } return 1; } //------------------------------------------------ int StringBIStream::getNextDW(UKDWORD & dw) { if (m_eos) return 0; dw = *((UKDWORD *)m_current); m_current += 4; if (m_len == -1) m_eos = (dw == 0); else { m_left -= 4; m_eos = (m_left <= 0); } return 1; } //------------------------------------------------ int StringBIStream::peekNext(UKBYTE & b) { if (m_eos) return 0; b = *m_current; return 1; } //------------------------------------------------ int StringBIStream::peekNextW(UKWORD & w) { if (m_eos) return 0; w = *((UKWORD *)m_current); return 1; } /* //------------------------------------------------ int StringBIStream::peekNextDW(UKDWORD & dw) { if (m_eos) return 0; dw = *((UKDWORD *)m_current); return 1; } */ //------------------------------------------------ void StringBIStream::reopen() { m_current = m_data; m_left = m_len; if (m_len == -1) m_eos = (m_data == 0); else m_eos = (m_len <= 0); m_didBookmark = 0; } //------------------------------------------------ int StringBIStream::bookmark() { m_didBookmark = 1; m_bookmark.current = m_current; m_bookmark.data = m_data; m_bookmark.eos = m_eos; m_bookmark.left = m_left; m_bookmark.len = m_len; return 1; } //------------------------------------------------ int StringBIStream::gotoBookmark() { if (!m_didBookmark) return 0; m_current = m_bookmark.current; m_data = m_bookmark.data; m_eos = m_bookmark.eos; m_left = m_bookmark.left; m_len = m_bookmark.len; return 1; } //------------------------------------------------ int StringBIStream::close() { return 1; } ////////////////////////////////////////////////// // Class StringBOStream ////////////////////////////////////////////////// //------------------------------------------------ StringBOStream::StringBOStream(UKBYTE *buf, int len) { m_current = m_buf = buf; m_len = len; m_out = 0; m_bad = 0; } //------------------------------------------------ int StringBOStream::putB(UKBYTE b) { m_out++; /* if (m_out >= 2147483647) { int err; err = 1; } */ if (m_bad) return 0; /* if (m_out < 0) { int i; i = 1; } */ if (m_out <= m_len) { *m_current++ = b; return 1; } m_bad = 1; return 0; } //------------------------------------------------ int StringBOStream::putW(UKWORD w) { m_out += 2; if (m_bad) return 0; if (m_out <= m_len) { *((UKWORD *)m_current) = w; m_current += 2; return 1; } m_bad = 1; return 0; } //------------------------------------------------ int StringBOStream::puts(const char *s, int size) { if (size == -1) { while (*s) { m_out++; if (m_out <= m_len) *m_current++ = *s; s++; } if (!m_bad && m_out > m_len) m_bad = 1; return (!m_bad); } int n; if (!m_bad && m_out <= m_len) { n = m_len - m_out; if (n>size) n = size; memcpy(m_current, s, n); m_current += n; } m_out += size; if (!m_bad && m_out > m_len) m_bad = 1; return (!m_bad); } //------------------------------------------------ void StringBOStream::reopen() { m_current = m_buf; m_out = 0; m_bad = 0; } //------------------------------------------------ int StringBOStream::isOK() { return !m_bad; } //////////////////////////////////////////////////// // Class FileBIStream // //////////////////////////////////////////////////// //---------------------------------------------------- FileBIStream::FileBIStream(int bufSize, char *buf) { m_file = NULL; m_buf = buf; m_bufSize = bufSize; m_own = 1; m_didBookmark = 0; m_readAhead = 0; m_lastIsAhead = 0; } //---------------------------------------------------- FileBIStream::~FileBIStream() { if (m_own) close(); } //---------------------------------------------------- int FileBIStream::open(const char *fileName) { m_file = fopen(fileName, "rb"); if (m_file == NULL) return 0; setvbuf(m_file, m_buf, _IOFBF, m_bufSize); m_own = 0; m_readAhead = 0; m_lastIsAhead = 0; return 1; } //---------------------------------------------------- int FileBIStream::close() { if (m_file != NULL) { fclose(m_file); m_file = NULL; } return 1; } //---------------------------------------------------- void FileBIStream::attach(FILE * f) { m_file = f; m_own = 0; m_readAhead = 0; m_lastIsAhead = 0; } //---------------------------------------------------- int FileBIStream::eos() { if (m_readAhead) return 0; return feof(m_file); } //---------------------------------------------------- int FileBIStream::getNext(UKBYTE &b) { if (m_readAhead) { m_readAhead = 0; b = m_readByte; m_lastIsAhead = 1; return 1; } m_lastIsAhead = 0; b = fgetc(m_file); return (!feof(m_file)); } //---------------------------------------------------- int FileBIStream::peekNext(UKBYTE &b) { if (m_readAhead) { b = m_readByte; return 1; } b = fgetc(m_file); if (feof(m_file)) return 0; ungetc(b, m_file); return 1; } //---------------------------------------------------- int FileBIStream::unget(UKBYTE b) { if (m_lastIsAhead) { m_lastIsAhead = 0; m_readAhead = 1; m_readByte = b; return 1; } ungetc(b, m_file); return 1; } //---------------------------------------------------- int FileBIStream::getNextW(UKWORD &w) { UKBYTE b1, b2; if (getNext(b1)) { if (getNext(b2)) { *((UKBYTE *)&w) = b1; *(((UKBYTE *)&w)+1) = b2; return 1; } } return 0; } //---------------------------------------------------- int FileBIStream::getNextDW(UKDWORD &dw) { UKWORD w1, w2; if (getNextW(w1)) { if (getNextW(w2)) { *((UKWORD *)&dw) = w1; *(((UKWORD *)&dw)+1) = w2; return 1; } } return 0; } //---------------------------------------------------- int FileBIStream::peekNextW(UKWORD &w) { UKBYTE hi, low; if (getNext(low)) { if (getNext(hi)) { unget(hi); w = hi; w = (w << 8) + low; m_readAhead = 1; m_readByte = low; m_lastIsAhead = 0; return 1; } m_readAhead = 1; m_readByte = low; m_lastIsAhead = 0; return 0; } return 0; } //---------------------------------------------------- int FileBIStream::bookmark() { m_didBookmark = 1; m_bookmark.pos = ftell(m_file); return 1; } //---------------------------------------------------- int FileBIStream::gotoBookmark() { if (!m_didBookmark) return 0; fseek(m_file, m_bookmark.pos, SEEK_SET); return 1; } //////////////////////////////////////////////////// // Class FileBOStream // //////////////////////////////////////////////////// //---------------------------------------------------- FileBOStream::FileBOStream(int bufSize, char *buf) { m_file = NULL; m_buf = buf; m_bufSize = bufSize; m_own = 1; m_bad = 1; } //---------------------------------------------------- FileBOStream::~FileBOStream() { if (m_own) close(); } //---------------------------------------------------- int FileBOStream::open(const char *fileName) { m_file = fopen(fileName, "wb"); if (m_file == NULL) return 0; m_bad = 0; setvbuf(m_file, m_buf, _IOFBF, m_bufSize); m_own = 1; return 1; } //---------------------------------------------------- void FileBOStream::attach(FILE * f) { m_file = f; m_own = 0; m_bad = 0; } //---------------------------------------------------- int FileBOStream::close() { if (m_file != NULL) { fclose(m_file); m_file = NULL; } return 1; } //---------------------------------------------------- int FileBOStream::putB(UKBYTE b) { if (m_bad) return 0; m_bad = (fputc(b, m_file) == EOF); return (!m_bad); } //---------------------------------------------------- int FileBOStream::putW(UKWORD w) { if (m_bad) return 0; // m_bad = (fputwc(w, m_file) == WEOF); m_bad = (fputc((UKBYTE)w, m_file) == EOF); if (m_bad) return 0; m_bad = (fputc((UKBYTE)(w >> 8), m_file) == EOF); return (!m_bad); } //---------------------------------------------------- int FileBOStream::puts(const char *s, int size) { if (m_bad) return 0; if (size == -1) { m_bad = (fputs(s, m_file) == EOF); return (!m_bad); } int out = fwrite(s, 1, size, m_file); m_bad = (out != size); return (!m_bad); } //---------------------------------------------------- int FileBOStream::isOK() { return !m_bad; } ibus-unikey-0.7.0~beta1/ukengine/CMakeLists.txt0000664000175000017500000000051213441506611021011 0ustar gunnargunnarset (SOURCES byteio.cpp charset.cpp convert.cpp data.cpp error.cpp inputproc.cpp mactab.cpp pattern.cpp ukengine.cpp usrkeymap.cpp unikey.cpp ) add_library(ukengine STATIC ${SOURCES}) set_target_properties(ukengine PROPERTIES COMPILE_FLAGS "-funsigned-char -Wno-invalid-source-encoding") ibus-unikey-0.7.0~beta1/ukengine/inputproc.h0000664000175000017500000000650213441506611020452 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /* Unikey Vietnamese Input Method * Copyright (C) 2000-2005 Pham Kim Long * Contact: * unikey@gmail.com * UniKey project: http://unikey.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __UK_INPUT_PROCESSOR_H #define __UK_INPUT_PROCESSOR_H #include "keycons.h" #include "vnlexi.h" #if defined(_WIN32) #define DllExport __declspec( dllexport ) #define DllImport __declspec( dllimport ) #if defined(UNIKEYHOOK) #define DllInterface __declspec( dllexport ) #else #define DllInterface __declspec( dllimport ) #endif #else #define DllInterface //not used #define DllExport #define DllImport #endif enum UkKeyEvName { vneRoofAll, vneRoof_a, vneRoof_e, vneRoof_o, vneHookAll, vneHook_uo, vneHook_u, vneHook_o, vneBowl, vneDd, vneTone0, vneTone1, vneTone2, vneTone3, vneTone4, vneTone5, vne_telex_w, //special for telex vneMapChar, //e.g. [ -> u+ , ] -> o+ vneEscChar, vneNormal, //does not belong to any of the above categories vneCount //just to count how many event types there are }; enum UkCharType { ukcVn, ukcWordBreak, ukcNonVn, ukcReset }; struct UkKeyEvent { int evType; UkCharType chType; VnLexiName vnSym; //meaningful only when chType==ukcVn unsigned int keyCode; int tone; //meaningful only when this is a vowel }; struct UkKeyMapping { unsigned char key; int action; }; /////////////////////////////////////////// class UkInputProcessor { public: //don't do anything with constructor, because //this object can be allocated in shared memory //Use init method instead //UkInputProcessor(); void init(); UkInputMethod getIM() { return m_im; } void keyCodeToEvent(unsigned int keyCode, UkKeyEvent & ev); void keyCodeToSymbol(unsigned int keyCode, UkKeyEvent & ev); int setIM(UkInputMethod im); int setIM(int map[256]); void getKeyMap(int map[256]); UkCharType getCharType(unsigned int keyCode); protected: static bool m_classInit; UkInputMethod m_im; int m_keyMap[256]; void useBuiltIn(UkKeyMapping *map); }; void UkResetKeyMap(int keyMap[256]); void SetupInputClassifierTable(); DllInterface extern UkKeyMapping TelexMethodMapping[]; DllInterface extern UkKeyMapping SimpleTelexMethodMapping[]; DllInterface extern UkKeyMapping VniMethodMapping[]; DllInterface extern UkKeyMapping VIQRMethodMapping[]; DllInterface extern UkKeyMapping MsViMethodMapping[]; extern VnLexiName IsoVnLexiMap[]; inline VnLexiName IsoToVnLexi(unsigned int keyCode) { return (keyCode >= 256)? vnl_nonVnChar : IsoVnLexiMap[keyCode]; } #endif ibus-unikey-0.7.0~beta1/ukengine/convert.cpp0000664000175000017500000001455413441506611020450 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /*------------------------------------------------------------------------------ VnConv: Vietnamese Encoding Converter Library UniKey Project: http://unikey.sourceforge.net Copyleft (C) 1998-2002 Pham Kim Long Contact: longp@cslab.felk.cvut.cz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --------------------------------------------------------------------------------*/ #include "charset.h" #include #include #include #if defined(_WIN32) #include #include #endif #include "vnconv.h" int vnFileStreamConvert(int inCharset, int outCharset, FILE * inf, FILE *outf); DllExport int genConvert(VnCharset & incs, VnCharset & outcs, ByteInStream & input, ByteOutStream & output) { StdVnChar stdChar; int bytesRead, bytesWritten; incs.startInput(); outcs.startOutput(); int ret = 1; while (!input.eos()) { stdChar = 0; if (incs.nextInput(input, stdChar, bytesRead)) { if (stdChar != INVALID_STD_CHAR) { if (VnCharsetLibObj.m_options.toLower) stdChar = StdVnToLower(stdChar); else if (VnCharsetLibObj.m_options.toUpper) stdChar = StdVnToUpper(stdChar); if (VnCharsetLibObj.m_options.removeTone) stdChar = StdVnGetRoot(stdChar); ret = outcs.putChar(output, stdChar, bytesWritten); } } else break; } return (ret? 0 : VNCONV_OUT_OF_MEMORY); } //---------------------------------------------- // Arguments: // inCharset: charset of input // outCharset: charset of output // input: input data // output: output data // inLen: [in] size of input. if inLen = -1, input data is null-terminated. // [out] if input inLen != -1, output iLen is the numbers of byte left in input. // maxOutLen: [in] size of output. // [out] number of bytes output, if enough memory // number of bytes needed for output, if not enough memory // Returns: 0 if successful // error code: if failed //---------------------------------------------- //int VnConvert(int inCharset, int outCharset, UKBYTE *input, UKBYTE *output, int & inLen, int & maxOutLen) DllExport int VnConvert(int inCharset, int outCharset, UKBYTE *input, UKBYTE *output, int * pInLen, int * pMaxOutLen) { int inLen, maxOutLen; int ret = -1; inLen = *pInLen; maxOutLen = *pMaxOutLen; if (inLen != -1 && inLen < 0) // invalid inLen return ret; VnCharset *pInCharset = VnCharsetLibObj.getVnCharset(inCharset); VnCharset *pOutCharset = VnCharsetLibObj.getVnCharset(outCharset); if (!pInCharset || !pOutCharset) return VNCONV_INVALID_CHARSET; StringBIStream is(input, inLen, pInCharset->elementSize()); StringBOStream os(output, maxOutLen); ret = genConvert(*pInCharset, *pOutCharset, is, os); *pMaxOutLen = os.getOutBytes(); *pInLen = is.left(); return ret; } //--------------------------------------- // Arguments: // inFile: input file name. NULL if STDIN is used // outFile: output file name, NULL if STDOUT is used // Returns: // 0: successful // errCode: if failed //--------------------------------------- DllExport int VnFileConvert(int inCharset, int outCharset, const char *inFile, const char *outFile) { FILE *inf = NULL; FILE *outf = NULL; int ret = 0; char tmpName[32]; if (inFile == NULL) { inf = stdin; #if defined(_WIN32) _setmode( _fileno(stdin), _O_BINARY); #endif } else { inf = fopen(inFile, "rb"); if (inf == NULL) { ret = VNCONV_ERR_INPUT_FILE; goto end; } } if (outFile == NULL) outf = stdout; else { // setup temporary output file (because real output file may be the same as input file char outDir[256]; strcpy(outDir, outFile); #if defined(_WIN32) char *p = strrchr(outDir, '\\'); #else char *p = strrchr(outDir, '/'); #endif if (p == NULL) outDir[0] = 0; else *p = 0; strcpy(tmpName, outDir); strcat(tmpName, "XXXXXX"); if (mkstemp(tmpName) == -1) { fclose(inf); ret = VNCONV_ERR_OUTPUT_FILE; goto end; } outf = fopen(tmpName, "wb"); if (outf == NULL) { fclose(inf); ret = VNCONV_ERR_OUTPUT_FILE; goto end; } } ret = vnFileStreamConvert(inCharset, outCharset, inf, outf); if (inf != stdin) fclose(inf); if (outf != stdout) { fclose(outf); // delete output file if exisits if (ret == 0) { remove(outFile); #if !defined(_WIN32) char cmd[256]; sprintf(cmd, "mv %s %s", tmpName, outFile); cmd[0] = system(cmd); #else if (rename(tmpName, outFile) != 0) { remove(tmpName); ret = VNCONV_ERR_OUTPUT_FILE; goto end; } #endif } else remove(tmpName); } end: #if defined(_WIN32) if (inf == stdin) { _setmode( _fileno(stdin), _O_BINARY); } #endif return ret; } //------------------------------------------------ // Returns: // 0: successful // errCode: if failed //--------------------------------------- int vnFileStreamConvert(int inCharset, int outCharset, FILE * inf, FILE *outf) { VnCharset *pInCharset = VnCharsetLibObj.getVnCharset(inCharset); VnCharset *pOutCharset = VnCharsetLibObj.getVnCharset(outCharset); if (!pInCharset || !pOutCharset) return VNCONV_INVALID_CHARSET; if (outCharset == CONV_CHARSET_UNICODE) { UKWORD sign = 0xFEFF; fwrite(&sign, sizeof(UKWORD), 1, outf); } FileBIStream is; FileBOStream os; is.attach(inf); os.attach(outf); return genConvert(*pInCharset, *pOutCharset, is, os); } const char *ErrTable[VNCONV_LAST_ERROR] = {"No error", "Unknown error", "Invalid charset", "Error opening input file", "Error opening output file", "Error writing to output stream", "Not enough memory", }; DllExport const char * VnConvErrMsg(int errCode) { if (errCode < 0 || errCode >= VNCONV_LAST_ERROR) errCode = VNCONV_UNKNOWN_ERROR; return ErrTable[errCode]; } ibus-unikey-0.7.0~beta1/ukengine/ukengine.cpp0000664000175000017500000022663613441506611020603 0ustar gunnargunnar// -*- mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /* Unikey Vietnamese Input Method * Copyright (C) 2000-2005 Pham Kim Long * Contact: * unikey@gmail.com * UniKey project: http://unikey.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include #include #include #include "keycons.h" /* #if defined(_WIN32) #include "keyhook.h" #endif */ #include "vnlexi.h" #include "ukengine.h" #include "charset.h" using namespace std; #define ENTER_CHAR 13 #define IS_ODD(x) (x & 1) #define IS_EVEN(x) (!(x & 1)) #define IS_STD_VN_LOWER(x) ((x) >= VnStdCharOffset && (x) < (VnStdCharOffset + TOTAL_ALPHA_VNCHARS) && IS_ODD(x)) #define IS_STD_VN_UPPER(x) ((x) >= VnStdCharOffset && (x) < (VnStdCharOffset + TOTAL_ALPHA_VNCHARS) && IS_EVEN(x)) bool IsVnVowel[vnl_lastChar]; extern VnLexiName AZLexiUpper[]; //defined in inputproc.cpp extern VnLexiName AZLexiLower[]; //see vnconv/data.cpp for explanation of these characters unsigned char SpecialWesternChars[] = { 0x80, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8E, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9E, 0x9F, 0x00}; StdVnChar IsoStdVnCharMap[256]; inline StdVnChar IsoToStdVnChar(int keyCode) { return (keyCode < 256)? IsoStdVnCharMap[keyCode] : keyCode; } struct VowelSeqInfo { int len; int complete; int conSuffix; //allow consonnant suffix VnLexiName v[3]; VowelSeq sub[3]; int roofPos; VowelSeq withRoof; int hookPos; VowelSeq withHook; //hook & bowl }; VowelSeqInfo VSeqList[] = { {1, 1, 1, {vnl_a, vnl_nonVnChar, vnl_nonVnChar}, {vs_a, vs_nil, vs_nil}, -1, vs_ar, -1, vs_ab}, {1, 1, 1, {vnl_ar, vnl_nonVnChar, vnl_nonVnChar}, {vs_ar, vs_nil, vs_nil}, 0, vs_nil, -1, vs_ab}, {1, 1, 1, {vnl_ab, vnl_nonVnChar, vnl_nonVnChar}, {vs_ab, vs_nil, vs_nil}, -1, vs_ar, 0, vs_nil}, {1, 1, 1, {vnl_e, vnl_nonVnChar, vnl_nonVnChar}, {vs_e, vs_nil, vs_nil}, -1, vs_er, -1, vs_nil}, {1, 1, 1, {vnl_er, vnl_nonVnChar, vnl_nonVnChar}, {vs_er, vs_nil, vs_nil}, 0, vs_nil, -1, vs_nil}, {1, 1, 1, {vnl_i, vnl_nonVnChar, vnl_nonVnChar}, {vs_i, vs_nil, vs_nil}, -1, vs_nil, -1, vs_nil}, {1, 1, 1, {vnl_o, vnl_nonVnChar, vnl_nonVnChar}, {vs_o, vs_nil, vs_nil}, -1, vs_or, -1, vs_oh}, {1, 1, 1, {vnl_or, vnl_nonVnChar, vnl_nonVnChar}, {vs_or, vs_nil, vs_nil}, 0, vs_nil, -1, vs_oh}, {1, 1, 1, {vnl_oh, vnl_nonVnChar, vnl_nonVnChar}, {vs_oh, vs_nil, vs_nil}, -1, vs_or, 0, vs_nil}, {1, 1, 1, {vnl_u, vnl_nonVnChar, vnl_nonVnChar}, {vs_u, vs_nil, vs_nil}, -1, vs_nil, -1, vs_uh}, {1, 1, 1, {vnl_uh, vnl_nonVnChar, vnl_nonVnChar}, {vs_uh, vs_nil, vs_nil}, -1, vs_nil, 0, vs_nil}, {1, 1, 1, {vnl_y, vnl_nonVnChar, vnl_nonVnChar}, {vs_y, vs_nil, vs_nil}, -1, vs_nil, -1, vs_nil}, {2, 1, 0, {vnl_a, vnl_i, vnl_nonVnChar}, {vs_a, vs_ai, vs_nil}, -1, vs_nil, -1, vs_nil}, {2, 1, 0, {vnl_a, vnl_o, vnl_nonVnChar}, {vs_a, vs_ao, vs_nil}, -1, vs_nil, -1, vs_nil}, {2, 1, 0, {vnl_a, vnl_u, vnl_nonVnChar}, {vs_a, vs_au, vs_nil}, -1, vs_aru, -1, vs_nil}, {2, 1, 0, {vnl_a, vnl_y, vnl_nonVnChar}, {vs_a, vs_ay, vs_nil}, -1, vs_ary, -1, vs_nil}, {2, 1, 0, {vnl_ar, vnl_u, vnl_nonVnChar}, {vs_ar, vs_aru, vs_nil}, 0, vs_nil, -1, vs_nil}, {2, 1, 0, {vnl_ar, vnl_y, vnl_nonVnChar}, {vs_ar, vs_ary, vs_nil}, 0, vs_nil, -1, vs_nil}, {2, 1, 0, {vnl_e, vnl_o, vnl_nonVnChar}, {vs_e, vs_eo, vs_nil}, -1, vs_nil, -1, vs_nil}, {2, 0, 0, {vnl_e, vnl_u, vnl_nonVnChar}, {vs_e, vs_eu, vs_nil}, -1, vs_eru, -1, vs_nil}, {2, 1, 0, {vnl_er, vnl_u, vnl_nonVnChar}, {vs_er, vs_eru, vs_nil}, 0, vs_nil, -1, vs_nil}, {2, 1, 0, {vnl_i, vnl_a, vnl_nonVnChar}, {vs_i, vs_ia, vs_nil}, -1, vs_nil, -1, vs_nil}, {2, 0, 1, {vnl_i, vnl_e, vnl_nonVnChar}, {vs_i, vs_ie, vs_nil}, -1, vs_ier, -1, vs_nil}, {2, 1, 1, {vnl_i, vnl_er, vnl_nonVnChar}, {vs_i, vs_ier, vs_nil}, 1, vs_nil, -1, vs_nil}, {2, 1, 0, {vnl_i, vnl_u, vnl_nonVnChar}, {vs_i, vs_iu, vs_nil}, -1, vs_nil, -1, vs_nil}, {2, 1, 1, {vnl_o, vnl_a, vnl_nonVnChar}, {vs_o, vs_oa, vs_nil}, -1, vs_nil, -1, vs_oab}, {2, 1, 1, {vnl_o, vnl_ab, vnl_nonVnChar}, {vs_o, vs_oab, vs_nil}, -1, vs_nil, 1, vs_nil}, {2, 1, 1, {vnl_o, vnl_e, vnl_nonVnChar}, {vs_o, vs_oe, vs_nil}, -1, vs_nil, -1, vs_nil}, {2, 1, 0, {vnl_o, vnl_i, vnl_nonVnChar}, {vs_o, vs_oi, vs_nil}, -1, vs_ori, -1, vs_ohi}, {2, 1, 0, {vnl_or, vnl_i, vnl_nonVnChar}, {vs_or, vs_ori, vs_nil}, 0, vs_nil, -1, vs_ohi}, {2, 1, 0, {vnl_oh, vnl_i, vnl_nonVnChar}, {vs_oh, vs_ohi, vs_nil}, -1, vs_ori, 0, vs_nil}, {2, 1, 1, {vnl_u, vnl_a, vnl_nonVnChar}, {vs_u, vs_ua, vs_nil}, -1, vs_uar, -1, vs_uha}, {2, 1, 1, {vnl_u, vnl_ar, vnl_nonVnChar}, {vs_u, vs_uar, vs_nil}, 1, vs_nil, -1, vs_nil}, {2, 0, 1, {vnl_u, vnl_e, vnl_nonVnChar}, {vs_u, vs_ue, vs_nil}, -1, vs_uer, -1, vs_nil}, {2, 1, 1, {vnl_u, vnl_er, vnl_nonVnChar}, {vs_u, vs_uer, vs_nil}, 1, vs_nil, -1, vs_nil}, {2, 1, 0, {vnl_u, vnl_i, vnl_nonVnChar}, {vs_u, vs_ui, vs_nil}, -1, vs_nil, -1, vs_uhi}, {2, 0, 1, {vnl_u, vnl_o, vnl_nonVnChar}, {vs_u, vs_uo, vs_nil}, -1, vs_uor, -1, vs_uho}, {2, 1, 1, {vnl_u, vnl_or, vnl_nonVnChar}, {vs_u, vs_uor, vs_nil}, 1, vs_nil, -1, vs_uoh}, {2, 1, 1, {vnl_u, vnl_oh, vnl_nonVnChar}, {vs_u, vs_uoh, vs_nil}, -1, vs_uor, 1, vs_uhoh}, {2, 0, 0, {vnl_u, vnl_u, vnl_nonVnChar}, {vs_u, vs_uu, vs_nil}, -1, vs_nil, -1, vs_uhu}, {2, 1, 1, {vnl_u, vnl_y, vnl_nonVnChar}, {vs_u, vs_uy, vs_nil}, -1, vs_nil, -1, vs_nil}, {2, 1, 0, {vnl_uh, vnl_a, vnl_nonVnChar}, {vs_uh, vs_uha, vs_nil}, -1, vs_nil, 0, vs_nil}, {2, 1, 0, {vnl_uh, vnl_i, vnl_nonVnChar}, {vs_uh, vs_uhi, vs_nil}, -1, vs_nil, 0, vs_nil}, {2, 0, 1, {vnl_uh, vnl_o, vnl_nonVnChar}, {vs_uh, vs_uho, vs_nil}, -1, vs_nil, 0, vs_uhoh}, {2, 1, 1, {vnl_uh, vnl_oh, vnl_nonVnChar}, {vs_uh, vs_uhoh, vs_nil}, -1, vs_nil, 0, vs_nil}, {2, 1, 0, {vnl_uh, vnl_u, vnl_nonVnChar}, {vs_uh, vs_uhu, vs_nil}, -1, vs_nil, 0, vs_nil}, {2, 0, 1, {vnl_y, vnl_e, vnl_nonVnChar}, {vs_y, vs_ye, vs_nil}, -1, vs_yer, -1, vs_nil}, {2, 1, 1, {vnl_y, vnl_er, vnl_nonVnChar}, {vs_y, vs_yer, vs_nil}, 1, vs_nil, -1, vs_nil}, {3, 0, 0, {vnl_i, vnl_e, vnl_u}, {vs_i, vs_ie, vs_ieu}, -1, vs_ieru, -1, vs_nil}, {3, 1, 0, {vnl_i, vnl_er, vnl_u}, {vs_i, vs_ier, vs_ieru}, 1, vs_nil, -1, vs_nil}, {3, 1, 0, {vnl_o, vnl_a, vnl_i}, {vs_o, vs_oa, vs_oai}, -1, vs_nil, -1, vs_nil}, {3, 1, 0, {vnl_o, vnl_a, vnl_y}, {vs_o, vs_oa, vs_oay}, -1, vs_nil, -1, vs_nil}, {3, 1, 0, {vnl_o, vnl_e, vnl_o}, {vs_o, vs_oe, vs_oeo}, -1, vs_nil, -1, vs_nil}, {3, 0, 0, {vnl_u, vnl_a, vnl_y}, {vs_u, vs_ua, vs_uay}, -1, vs_uary, -1, vs_nil}, {3, 1, 0, {vnl_u, vnl_ar, vnl_y}, {vs_u, vs_uar, vs_uary}, 1, vs_nil, -1, vs_nil}, {3, 0, 0, {vnl_u, vnl_o, vnl_i}, {vs_u, vs_uo, vs_uoi}, -1, vs_uori, -1, vs_uhoi}, {3, 0, 0, {vnl_u, vnl_o, vnl_u}, {vs_u, vs_uo, vs_uou}, -1, vs_nil, -1, vs_uhou}, {3, 1, 0, {vnl_u, vnl_or, vnl_i}, {vs_u, vs_uor, vs_uori}, 1, vs_nil, -1, vs_uohi}, {3, 0, 0, {vnl_u, vnl_oh, vnl_i}, {vs_u, vs_uoh, vs_uohi}, -1, vs_uori, 1, vs_uhohi}, {3, 0, 0, {vnl_u, vnl_oh, vnl_u}, {vs_u, vs_uoh, vs_uohu}, -1, vs_nil, 1, vs_uhohu}, {3, 1, 0, {vnl_u, vnl_y, vnl_a}, {vs_u, vs_uy, vs_uya}, -1, vs_nil, -1, vs_nil}, {3, 0, 1, {vnl_u, vnl_y, vnl_e}, {vs_u, vs_uy, vs_uye}, -1, vs_uyer, -1, vs_nil}, {3, 1, 1, {vnl_u, vnl_y, vnl_er}, {vs_u, vs_uy, vs_uyer}, 2, vs_nil, -1, vs_nil}, {3, 1, 0, {vnl_u, vnl_y, vnl_u}, {vs_u, vs_uy, vs_uyu}, -1, vs_nil, -1, vs_nil}, {3, 0, 0, {vnl_uh, vnl_o, vnl_i}, {vs_uh, vs_uho, vs_uhoi}, -1, vs_nil, 0, vs_uhohi}, {3, 0, 0, {vnl_uh, vnl_o, vnl_u}, {vs_uh, vs_uho, vs_uhou}, -1, vs_nil, 0, vs_uhohu}, {3, 1, 0, {vnl_uh, vnl_oh, vnl_i}, {vs_uh, vs_uhoh, vs_uhohi}, -1, vs_nil, 0, vs_nil}, {3, 1, 0, {vnl_uh, vnl_oh, vnl_u}, {vs_uh, vs_uhoh, vs_uhohu}, -1, vs_nil, 0, vs_nil}, {3, 0, 0, {vnl_y, vnl_e, vnl_u}, {vs_y, vs_ye, vs_yeu}, -1, vs_yeru, -1, vs_nil}, {3, 1, 0, {vnl_y, vnl_er, vnl_u}, {vs_y, vs_yer, vs_yeru}, 1, vs_nil, -1, vs_nil} }; struct ConSeqInfo { int len; VnLexiName c[3]; bool suffix; }; ConSeqInfo CSeqList[] = { {1, {vnl_b, vnl_nonVnChar, vnl_nonVnChar}, false}, {1, {vnl_c, vnl_nonVnChar, vnl_nonVnChar}, true}, {2, {vnl_c, vnl_h, vnl_nonVnChar}, true}, {1, {vnl_d, vnl_nonVnChar, vnl_nonVnChar}, false}, {1, {vnl_dd, vnl_nonVnChar, vnl_nonVnChar}, false}, {2, {vnl_d, vnl_z, vnl_nonVnChar}, false}, {1, {vnl_g, vnl_nonVnChar, vnl_nonVnChar}, false}, {2, {vnl_g, vnl_h, vnl_nonVnChar}, false}, {2, {vnl_g, vnl_i, vnl_nonVnChar}, false}, {3, {vnl_g, vnl_i, vnl_n}, false}, {1, {vnl_h, vnl_nonVnChar, vnl_nonVnChar}, false}, {1, {vnl_k, vnl_nonVnChar, vnl_nonVnChar}, false}, {2, {vnl_k, vnl_h, vnl_nonVnChar}, false}, {1, {vnl_l, vnl_nonVnChar, vnl_nonVnChar}, false}, {1, {vnl_m, vnl_nonVnChar, vnl_nonVnChar}, true}, {1, {vnl_n, vnl_nonVnChar, vnl_nonVnChar}, true}, {2, {vnl_n, vnl_g, vnl_nonVnChar}, true}, {3, {vnl_n, vnl_g, vnl_h}, false}, {2, {vnl_n, vnl_h, vnl_nonVnChar}, true}, {1, {vnl_p, vnl_nonVnChar, vnl_nonVnChar}, true}, {2, {vnl_p, vnl_h, vnl_nonVnChar}, false}, {1, {vnl_q, vnl_nonVnChar, vnl_nonVnChar}, false}, {2, {vnl_q, vnl_u, vnl_nonVnChar}, false}, {1, {vnl_r, vnl_nonVnChar, vnl_nonVnChar}, false}, {1, {vnl_s, vnl_nonVnChar, vnl_nonVnChar}, false}, {1, {vnl_t, vnl_nonVnChar, vnl_nonVnChar}, true}, {2, {vnl_t, vnl_h, vnl_nonVnChar}, false}, {2, {vnl_t, vnl_r, vnl_nonVnChar}, false}, {1, {vnl_v, vnl_nonVnChar, vnl_nonVnChar}, false}, {1, {vnl_x, vnl_nonVnChar, vnl_nonVnChar}, false} }; const int VSeqCount = sizeof(VSeqList)/sizeof(VowelSeqInfo); struct VSeqPair { VnLexiName v[3]; VowelSeq vs; }; VSeqPair SortedVSeqList[VSeqCount]; const int CSeqCount = sizeof(CSeqList)/sizeof(ConSeqInfo); struct CSeqPair { VnLexiName c[3]; ConSeq cs; }; CSeqPair SortedCSeqList[CSeqCount]; struct VCPair { VowelSeq v; ConSeq c; }; VCPair VCPairList [] = { {vs_a, cs_c}, {vs_a, cs_ch}, {vs_a, cs_m}, {vs_a, cs_n}, {vs_a, cs_ng}, {vs_a, cs_nh}, {vs_a, cs_p}, {vs_a, cs_t}, {vs_ar, cs_c}, {vs_ar, cs_m}, {vs_ar, cs_n}, {vs_ar, cs_ng}, {vs_ar, cs_p}, {vs_ar, cs_t}, {vs_ab, cs_c}, {vs_ab, cs_m}, {vs_ab, cs_n}, {vs_ab, cs_ng}, {vs_ab, cs_p}, {vs_ab, cs_t}, {vs_e, cs_c}, {vs_e, cs_ch}, {vs_e, cs_m}, {vs_e, cs_n}, {vs_e, cs_ng}, {vs_e, cs_nh}, {vs_e, cs_p}, {vs_e, cs_t}, {vs_er, cs_c}, {vs_er, cs_ch}, {vs_er, cs_m}, {vs_er, cs_n}, {vs_er, cs_nh}, {vs_er, cs_p}, {vs_er, cs_t}, {vs_i, cs_c}, {vs_i, cs_ch}, {vs_i, cs_m}, {vs_i, cs_n}, {vs_i, cs_nh}, {vs_i, cs_p}, {vs_i, cs_t}, {vs_o, cs_c}, {vs_o, cs_m}, {vs_o, cs_n}, {vs_o, cs_ng}, {vs_o, cs_p}, {vs_o, cs_t}, {vs_or, cs_c}, {vs_or, cs_m}, {vs_or, cs_n}, {vs_or, cs_ng}, {vs_or, cs_p}, {vs_or, cs_t}, {vs_oh, cs_m}, {vs_oh, cs_n}, {vs_oh, cs_p}, {vs_oh, cs_t}, {vs_u, cs_c}, {vs_u, cs_m}, {vs_u, cs_n}, {vs_u, cs_ng}, {vs_u, cs_p}, {vs_u, cs_t}, {vs_uh, cs_c}, {vs_uh, cs_m}, {vs_uh, cs_n}, {vs_uh, cs_ng}, {vs_uh, cs_t}, {vs_y, cs_t}, {vs_ie, cs_c}, {vs_ie, cs_m}, {vs_ie, cs_n}, {vs_ie, cs_ng}, {vs_ie, cs_p}, {vs_ie, cs_t}, {vs_ier, cs_c}, {vs_ier, cs_m}, {vs_ier, cs_n}, {vs_ier, cs_ng}, {vs_ier, cs_p}, {vs_ier, cs_t}, {vs_oa, cs_c}, {vs_oa, cs_ch}, {vs_oa, cs_m}, {vs_oa, cs_n}, {vs_oa, cs_ng}, {vs_oa, cs_nh}, {vs_oa, cs_p}, {vs_oa, cs_t}, {vs_oab, cs_c}, {vs_oab, cs_m}, {vs_oab, cs_n}, {vs_oab, cs_ng}, {vs_oab, cs_t}, {vs_oe, cs_n}, {vs_oe, cs_t}, {vs_ua, cs_n}, {vs_ua, cs_ng}, {vs_ua, cs_t}, {vs_uar, cs_n}, {vs_uar, cs_ng}, {vs_uar, cs_t}, {vs_ue, cs_c}, {vs_ue, cs_ch}, {vs_ue, cs_n}, {vs_ue, cs_nh}, {vs_uer, cs_c}, {vs_uer, cs_ch}, {vs_uer, cs_n}, {vs_uer, cs_nh}, {vs_uo, cs_c}, {vs_uo, cs_m}, {vs_uo, cs_n}, {vs_uo, cs_ng}, {vs_uo, cs_p}, {vs_uo, cs_t}, {vs_uor, cs_c}, {vs_uor, cs_m}, {vs_uor, cs_n}, {vs_uor, cs_ng}, {vs_uor, cs_t}, {vs_uho, cs_c}, {vs_uho, cs_m}, {vs_uho, cs_n}, {vs_uho, cs_ng}, {vs_uho, cs_p}, {vs_uho, cs_t}, {vs_uhoh, cs_c}, {vs_uhoh, cs_m}, {vs_uhoh, cs_n}, {vs_uhoh, cs_ng}, {vs_uhoh, cs_p}, {vs_uhoh, cs_t}, {vs_uy, cs_c}, {vs_uy, cs_ch}, {vs_uy, cs_n}, {vs_uy, cs_nh}, {vs_uy, cs_p}, {vs_uy, cs_t}, {vs_ye, cs_m}, {vs_ye, cs_n}, {vs_ye, cs_ng}, {vs_ye, cs_p}, {vs_ye, cs_t}, {vs_yer, cs_m}, {vs_yer, cs_n}, {vs_yer, cs_ng}, {vs_yer, cs_t}, {vs_uye, cs_n}, {vs_uye, cs_t}, {vs_uyer, cs_n}, {vs_uyer, cs_t} }; const int VCPairCount = sizeof(VCPairList)/sizeof(VCPair); //TODO: auto-complete: e.g. luan -> lua^n typedef int (UkEngine::* UkKeyProc)(UkKeyEvent & ev); UkKeyProc UkKeyProcList[vneCount] = { &UkEngine::processRoof, //vneRoofAll &UkEngine::processRoof, //vneRoof_a &UkEngine::processRoof, //vneRoof_e &UkEngine::processRoof, //vneRoof_o &UkEngine::processHook, //vneHookAll &UkEngine::processHook, //vneHook_uo &UkEngine::processHook, //vneHook_u &UkEngine::processHook, //vneHook_o &UkEngine::processHook, //vneBowl &UkEngine::processDd, //vneDd &UkEngine::processTone, //vneTone0 &UkEngine::processTone, //vneTone1 &UkEngine::processTone, //vneTone2 &UkEngine::processTone, //vneTone3 &UkEngine::processTone, //vneTone4 &UkEngine::processTone, //vneTone5 &UkEngine::processTelexW, //vne_telex_w &UkEngine::processMapChar, //vneMapChar &UkEngine::processEscChar, //vneEscChar &UkEngine::processAppend //vneNormal }; VowelSeq lookupVSeq(VnLexiName v1, VnLexiName v2 = vnl_nonVnChar, VnLexiName v3 = vnl_nonVnChar); ConSeq lookupCSeq(VnLexiName c1, VnLexiName c2 = vnl_nonVnChar, VnLexiName c3 = vnl_nonVnChar); bool UkEngine::m_classInit = false; //------------------------------------------------ int tripleVowelCompare(const void *p1, const void *p2) { VSeqPair *t1 = (VSeqPair *)p1; VSeqPair *t2 = (VSeqPair *)p2; for (int i=0; i<3; i++) { if (t1->v[i] < t2->v[i]) return -1; if (t1->v[i] > t2->v[i]) return 1; } return 0; } //------------------------------------------------ int tripleConCompare(const void *p1, const void *p2) { CSeqPair *t1 = (CSeqPair *)p1; CSeqPair *t2 = (CSeqPair *)p2; for (int i=0; i<3; i++) { if (t1->c[i] < t2->c[i]) return -1; if (t1->c[i] > t2->c[i]) return 1; } return 0; } //------------------------------------------------ int VCPairCompare(const void *p1, const void *p2) { VCPair *t1 = (VCPair *)p1; VCPair *t2 = (VCPair *)p2; if (t1->v < t2->v) return -1; if (t1->v > t2->v) return 1; if (t1->c < t2->c) return -1; if (t1->c > t2->c) return 1; return 0; } //---------------------------------------------------------- bool isValidCV(ConSeq c, VowelSeq v) { if (c == cs_nil || v == vs_nil) return true; VowelSeqInfo & vInfo = VSeqList[v]; if ((c == cs_gi && vInfo.v[0] == vnl_i) || (c == cs_qu && vInfo.v[0] == vnl_u)) return false; // gi doesn't go with i, qu doesn't go with u if (c == cs_k) { // k can only go with the following vowel sequences static VowelSeq kVseq[] = {vs_e, vs_i, vs_y, vs_er, vs_eo, vs_eu, vs_eru, vs_ia, vs_ie, vs_ier, vs_ieu, vs_ieru, vs_nil}; int i; for (i=0; kVseq[i] != vs_nil && kVseq[i] != v; i++); return (kVseq[i] != vs_nil); } //More checks return true; } //---------------------------------------------------------- bool isValidVC(VowelSeq v, ConSeq c) { if (v == vs_nil || c == cs_nil) return true; VowelSeqInfo & vInfo = VSeqList[v]; if (!vInfo.conSuffix) return false; ConSeqInfo & cInfo = CSeqList[c]; if (!cInfo.suffix) return false; VCPair p; p.v = v; p.c = c; if (bsearch(&p, VCPairList, VCPairCount, sizeof(VCPair), VCPairCompare)) return true; return false; } //---------------------------------------------------------- bool isValidCVC(ConSeq c1, VowelSeq v, ConSeq c2) { if (v == vs_nil) return (c1 == cs_nil || c2 != cs_nil); if (c1 == cs_nil) return isValidVC(v, c2); if (c2 == cs_nil) return isValidCV(c1, v); bool okCV = isValidCV(c1, v); bool okVC = isValidVC(v, c2); if (okCV && okVC) return true; if (!okVC) { //check some exceptions: vc fails but cvc passes // quyn, quynh if (c1 == cs_qu && v == vs_y && (c2 == cs_n || c2 == cs_nh)) return true; // gieng, gie^ng if (c1 == cs_gi && (v == vs_e || v == vs_er) && (c2 == cs_n || c2 == cs_ng)) return true; } return false; } //------------------------------------------------ void engineClassInit() { int i, j; for (i=0; i < VSeqCount; i++) { for (j=0; j<3; j++) SortedVSeqList[i].v[j] = VSeqList[i].v[j]; SortedVSeqList[i].vs = (VowelSeq)i; } for (i=0; i < CSeqCount; i++) { for (j=0; j<3; j++) SortedCSeqList[i].c[j] = CSeqList[i].c[j]; SortedCSeqList[i].cs = (ConSeq)i; } qsort(SortedVSeqList, VSeqCount, sizeof(VSeqPair), tripleVowelCompare); qsort(SortedCSeqList, CSeqCount, sizeof(CSeqPair), tripleConCompare); qsort(VCPairList, VCPairCount, sizeof(VCPair), VCPairCompare); for (i=0; ivs; } //------------------------------------------------ ConSeq lookupCSeq(VnLexiName c1, VnLexiName c2, VnLexiName c3) { CSeqPair key; key.c[0] = c1; key.c[1] = c2; key.c[2] = c3; CSeqPair *pInfo = (CSeqPair *)bsearch(&key, SortedCSeqList, CSeqCount, sizeof(CSeqPair), tripleConCompare); if (pInfo == 0) return cs_nil; return pInfo->cs; } //------------------------------------------------------------------ int UkEngine::processRoof(UkKeyEvent & ev) { if (!m_pCtrl->vietKey || m_current < 0 || m_buffer[m_current].vOffset < 0) return processAppend(ev); VnLexiName target; switch (ev.evType) { case vneRoof_a: target = vnl_ar; break; case vneRoof_e: target = vnl_er; break; case vneRoof_o: target = vnl_or; break; default: target = vnl_nonVnChar; } VowelSeq vs, newVs; int i, vStart, vEnd; int curTonePos, newTonePos, tone; int changePos; bool roofRemoved = false; vEnd = m_current - m_buffer[m_current].vOffset; vs = m_buffer[vEnd].vseq; vStart = vEnd - (VSeqList[vs].len - 1); curTonePos = vStart + getTonePosition(vs, vEnd == m_current); tone = m_buffer[curTonePos].tone; bool doubleChangeUO = false; if (vs == vs_uho || vs == vs_uhoh || vs == vs_uhoi || vs == vs_uhohi) { //special cases: u+o+ -> uo^, u+o -> uo^, u+o+i -> uo^i, u+oi -> uo^i newVs = lookupVSeq(vnl_u, vnl_or, VSeqList[vs].v[2]); doubleChangeUO = true; } else { newVs = VSeqList[vs].withRoof; } VowelSeqInfo *pInfo; if (newVs == vs_nil) { if (VSeqList[vs].roofPos == -1) return processAppend(ev); //roof is not applicable //a roof already exists -> undo roof VnLexiName curCh = m_buffer[vStart + VSeqList[vs].roofPos].vnSym; if (target != vnl_nonVnChar && curCh != target) return processAppend(ev); //specific roof and the roof character don't match VnLexiName newCh = (curCh == vnl_ar)? vnl_a : ((curCh == vnl_er)? vnl_e : vnl_o); changePos = vStart + VSeqList[vs].roofPos; if (!m_pCtrl->options.freeMarking && changePos != m_current) return processAppend(ev); markChange(changePos); m_buffer[changePos].vnSym = newCh; if (VSeqList[vs].len == 3) newVs = lookupVSeq(m_buffer[vStart].vnSym, m_buffer[vStart+1].vnSym, m_buffer[vStart+2].vnSym); else if (VSeqList[vs].len == 2) newVs = lookupVSeq(m_buffer[vStart].vnSym, m_buffer[vStart+1].vnSym); else newVs = lookupVSeq(m_buffer[vStart].vnSym); pInfo = &VSeqList[newVs]; roofRemoved = true; } else { pInfo = &VSeqList[newVs]; if (target != vnl_nonVnChar && pInfo->v[pInfo->roofPos] != target) return processAppend(ev); //check validity of new VC and CV bool valid = true; ConSeq c1 = cs_nil; ConSeq c2 = cs_nil; if (m_buffer[m_current].c1Offset != -1) c1 = m_buffer[m_current-m_buffer[m_current].c1Offset].cseq; if (m_buffer[m_current].c2Offset != -1) c2 = m_buffer[m_current-m_buffer[m_current].c2Offset].cseq; valid = isValidCVC(c1, newVs, c2); if (!valid) return processAppend(ev); if (doubleChangeUO) { changePos = vStart; } else { changePos = vStart + pInfo->roofPos; } if (!m_pCtrl->options.freeMarking && changePos != m_current) return processAppend(ev); markChange(changePos); if (doubleChangeUO) { m_buffer[vStart].vnSym = vnl_u; m_buffer[vStart+1].vnSym = vnl_or; } else { m_buffer[changePos].vnSym = pInfo->v[pInfo->roofPos]; } } for (i=0; i < pInfo->len; i++) { //update sub-sequences m_buffer[vStart+i].vseq = pInfo->sub[i]; } //check if tone re-position is needed newTonePos = vStart + getTonePosition(newVs, vEnd == m_current); /* //For now, users don't seem to like the following processing, thus commented out if (roofRemoved && tone != 0 && (!pInfo->complete || changePos == curTonePos)) { //remove tone if the vowel sequence becomes incomplete as a result of roof removal OR //if removed roof is at the same position as the current tone markChange(curTonePos); m_buffer[curTonePos].tone = 0; } else */ if (curTonePos != newTonePos && tone != 0) { markChange(newTonePos); m_buffer[newTonePos].tone = tone; markChange(curTonePos); m_buffer[curTonePos].tone = 0; } if (roofRemoved) { m_singleMode = false; processAppend(ev); m_reverted = true; } return 1; } //------------------------------------------------------------------ // can only be called from processHook //------------------------------------------------------------------ int UkEngine::processHookWithUO(UkKeyEvent & ev) { VowelSeq vs, newVs; int i, vStart, vEnd; int curTonePos, newTonePos, tone; bool hookRemoved = false; bool removeWithUndo = true; bool toneRemoved = false; (void)toneRemoved; // fix warning VnLexiName *v; if (!m_pCtrl->options.freeMarking && m_buffer[m_current].vOffset != 0) return processAppend(ev); vEnd = m_current - m_buffer[m_current].vOffset; vs = m_buffer[vEnd].vseq; vStart = vEnd - (VSeqList[vs].len - 1); v = VSeqList[vs].v; curTonePos = vStart + getTonePosition(vs, vEnd == m_current); tone = m_buffer[curTonePos].tone; switch (ev.evType) { case vneHook_u: if (v[0] == vnl_u) { newVs = VSeqList[vs].withHook; markChange(vStart); m_buffer[vStart].vnSym = vnl_uh; } else {// v[0] = vnl_uh, -> uo newVs = lookupVSeq(vnl_u, vnl_o, v[2]); markChange(vStart); m_buffer[vStart].vnSym = vnl_u; m_buffer[vStart+1].vnSym = vnl_o; hookRemoved = true; toneRemoved = (m_buffer[vStart].tone != 0); } break; case vneHook_o: if (v[1] == vnl_o || v[1] == vnl_or) { if (vEnd == m_current && VSeqList[vs].len == 2 && m_buffer[m_current].form == vnw_cv && m_buffer[m_current-2].cseq == cs_th) { // o|o^ -> o+ newVs = VSeqList[vs].withHook; markChange(vStart+1); m_buffer[vStart+1].vnSym = vnl_oh; } else { newVs = lookupVSeq(vnl_uh, vnl_oh, v[2]); if (v[0] == vnl_u) { markChange(vStart); m_buffer[vStart].vnSym = vnl_uh; m_buffer[vStart+1].vnSym = vnl_oh; } else { markChange(vStart+1); m_buffer[vStart+1].vnSym = vnl_oh; } } } else {// v[1] = vnl_oh, -> uo newVs = lookupVSeq(vnl_u, vnl_o, v[2]); if (v[0] == vnl_uh) { markChange(vStart); m_buffer[vStart].vnSym = vnl_u; m_buffer[vStart+1].vnSym = vnl_o; } else { markChange(vStart+1); m_buffer[vStart+1].vnSym = vnl_o; } hookRemoved = true; toneRemoved = (m_buffer[vStart+1].tone != 0); } break; default: //vneHookAll, vneHookUO: if (v[0] == vnl_u) { if (v[1] == vnl_o || v[1] == vnl_or) { //uo -> uo+ if prefixed by "th" if ((vs == vs_uo || vs == vs_uor) && vEnd == m_current && m_buffer[m_current].form == vnw_cv && m_buffer[m_current-2].cseq == cs_th) { newVs = vs_uoh; markChange(vStart+1); m_buffer[vStart+1].vnSym = vnl_oh; } else { //uo -> u+o+ newVs = VSeqList[vs].withHook; markChange(vStart); m_buffer[vStart].vnSym = vnl_uh; newVs = VSeqList[newVs].withHook; m_buffer[vStart+1].vnSym = vnl_oh; } } else {//uo+ -> u+o+ newVs = VSeqList[vs].withHook; markChange(vStart); m_buffer[vStart].vnSym = vnl_uh; } } else {//v[0] == vnl_uh if (v[1] == vnl_o) { // u+o -> u+o+ newVs = VSeqList[vs].withHook; markChange(vStart+1); m_buffer[vStart+1].vnSym = vnl_oh; } else { //v[1] == vnl_oh, u+o+ -> uo newVs = lookupVSeq(vnl_u, vnl_o, v[2]); //vs_uo; markChange(vStart); m_buffer[vStart].vnSym = vnl_u; m_buffer[vStart+1].vnSym = vnl_o; hookRemoved = true; toneRemoved = (m_buffer[vStart].tone != 0 || m_buffer[vStart+1].tone != 0); } } break; } VowelSeqInfo *p = &VSeqList[newVs]; for (i=0; i < p->len; i++) { //update sub-sequences m_buffer[vStart+i].vseq = p->sub[i]; } //check if tone re-position is needed newTonePos = vStart + getTonePosition(newVs, vEnd == m_current); /* //For now, users don't seem to like the following processing, thus commented out if (hookRemoved && tone != 0 && (!p->complete || toneRemoved)) { //remove tone if the vowel sequence becomes incomplete as a result of hook removal //OR if a removed hook is at the same position as the current tone markChange(curTonePos); m_buffer[curTonePos].tone = 0; } else */ if (curTonePos != newTonePos && tone != 0) { markChange(newTonePos); m_buffer[newTonePos].tone = tone; markChange(curTonePos); m_buffer[curTonePos].tone = 0; } if (hookRemoved && removeWithUndo) { m_singleMode = false; processAppend(ev); m_reverted = true; } return 1; } //------------------------------------------------------------------ int UkEngine::processHook(UkKeyEvent & ev) { if (!m_pCtrl->vietKey || m_current < 0 || m_buffer[m_current].vOffset < 0) return processAppend(ev); VowelSeq vs, newVs; int i, vStart, vEnd; int curTonePos, newTonePos, tone; int changePos; bool hookRemoved = false; VowelSeqInfo *pInfo; VnLexiName *v; vEnd = m_current - m_buffer[m_current].vOffset; vs = m_buffer[vEnd].vseq; v = VSeqList[vs].v; if (VSeqList[vs].len > 1 && ev.evType != vneBowl && (v[0] == vnl_u || v[0] == vnl_uh) && (v[1] == vnl_o || v[1] == vnl_oh || v[1] == vnl_or)) return processHookWithUO(ev); vStart = vEnd - (VSeqList[vs].len - 1); curTonePos = vStart + getTonePosition(vs, vEnd == m_current); tone = m_buffer[curTonePos].tone; newVs = VSeqList[vs].withHook; if (newVs == vs_nil) { if (VSeqList[vs].hookPos == -1) return processAppend(ev); //hook is not applicable //a hook already exists -> undo hook VnLexiName curCh = m_buffer[vStart + VSeqList[vs].hookPos].vnSym; VnLexiName newCh = (curCh == vnl_ab)? vnl_a : ((curCh == vnl_uh)? vnl_u : vnl_o); changePos = vStart + VSeqList[vs].hookPos; if (!m_pCtrl->options.freeMarking && changePos != m_current) return processAppend(ev); switch (ev.evType) { case vneHook_u: if (curCh != vnl_uh) return processAppend(ev); break; case vneHook_o: if (curCh != vnl_oh) return processAppend(ev); break; case vneBowl: if (curCh != vnl_ab) return processAppend(ev); break; default: if (ev.evType == vneHook_uo && curCh == vnl_ab) return processAppend(ev); } markChange(changePos); m_buffer[changePos].vnSym = newCh; if (VSeqList[vs].len == 3) newVs = lookupVSeq(m_buffer[vStart].vnSym, m_buffer[vStart+1].vnSym, m_buffer[vStart+2].vnSym); else if (VSeqList[vs].len == 2) newVs = lookupVSeq(m_buffer[vStart].vnSym, m_buffer[vStart+1].vnSym); else newVs = lookupVSeq(m_buffer[vStart].vnSym); pInfo = &VSeqList[newVs]; hookRemoved = true; } else { pInfo = &VSeqList[newVs]; switch (ev.evType) { case vneHook_u: if (pInfo->v[pInfo->hookPos] != vnl_uh) return processAppend(ev); break; case vneHook_o: if (pInfo->v[pInfo->hookPos] != vnl_oh) return processAppend(ev); break; case vneBowl: if (pInfo->v[pInfo->hookPos] != vnl_ab) return processAppend(ev); break; default: //vneHook_uo, vneHookAll if (ev.evType == vneHook_uo && pInfo->v[pInfo->hookPos] == vnl_ab) return processAppend(ev); } //check validity of new VC and CV bool valid = true; ConSeq c1 = cs_nil; ConSeq c2 = cs_nil; if (m_buffer[m_current].c1Offset != -1) c1 = m_buffer[m_current-m_buffer[m_current].c1Offset].cseq; if (m_buffer[m_current].c2Offset != -1) c2 = m_buffer[m_current-m_buffer[m_current].c2Offset].cseq; valid = isValidCVC(c1, newVs, c2); if (!valid) return processAppend(ev); changePos = vStart + pInfo->hookPos; if (!m_pCtrl->options.freeMarking && changePos != m_current) return processAppend(ev); markChange(changePos); m_buffer[changePos].vnSym = pInfo->v[pInfo->hookPos]; } for (i=0; i < pInfo->len; i++) { //update sub-sequences m_buffer[vStart+i].vseq = pInfo->sub[i]; } //check if tone re-position is needed newTonePos = vStart + getTonePosition(newVs, vEnd == m_current); /* //For now, users don't seem to like the following processing, thus commented out if (hookRemoved && tone != 0 && (!pInfo->complete || (hookRemoved && curTonePos == changePos))) { //remove tone if the vowel sequence becomes incomplete as a result of hook removal //OR if a removed hook was at the same position as the current tone markChange(curTonePos); m_buffer[curTonePos].tone = 0; } else */ if (curTonePos != newTonePos && tone != 0) { markChange(newTonePos); m_buffer[newTonePos].tone = tone; markChange(curTonePos); m_buffer[curTonePos].tone = 0; } if (hookRemoved) { m_singleMode = false; processAppend(ev); m_reverted = true; } return 1; } //---------------------------------------------------------- int UkEngine::getTonePosition(VowelSeq vs, bool terminated) { VowelSeqInfo & info = VSeqList[vs]; if (info.len == 1) return 0; if (info.roofPos != -1) return info.roofPos; if (info.hookPos != -1) { if (vs == vs_uhoh || vs == vs_uhohi || vs == vs_uhohu) //u+o+, u+o+u, u+o+i return 1; return info.hookPos; } if (info.len == 3) return 1; if (m_pCtrl->options.modernStyle && (vs == vs_oa || vs == vs_oe ||vs == vs_uy)) return 1; return terminated ? 0 : 1; } //---------------------------------------------------------- int UkEngine::processTone(UkKeyEvent & ev) { if (m_current < 0 || !m_pCtrl->vietKey) return processAppend(ev); if (m_buffer[m_current].form == vnw_c && (m_buffer[m_current].cseq == cs_gi || m_buffer[m_current].cseq == cs_gin)) { int p = (m_buffer[m_current].cseq == cs_gi)? m_current : m_current - 1; if (m_buffer[p].tone == 0 && ev.tone == 0) return processAppend(ev); markChange(p); if (m_buffer[p].tone == ev.tone) { m_buffer[p].tone = 0; m_singleMode = false; processAppend(ev); m_reverted = true; return 1; } m_buffer[p].tone = ev.tone; return 1; } if (m_buffer[m_current].vOffset < 0) return processAppend(ev); int vEnd; VowelSeq vs; vEnd = m_current - m_buffer[m_current].vOffset; vs = m_buffer[vEnd].vseq; VowelSeqInfo & info = VSeqList[vs]; if (m_pCtrl->options.spellCheckEnabled && !m_pCtrl->options.freeMarking && !info.complete) return processAppend(ev); if (m_buffer[m_current].form == vnw_vc || m_buffer[m_current].form == vnw_cvc) { ConSeq cs = m_buffer[m_current].cseq; if ((cs == cs_c || cs == cs_ch || cs == cs_p || cs == cs_t) && (ev.tone == 2 || ev.tone == 3 || ev.tone == 4)) return processAppend(ev); // c, ch, p, t suffixes don't allow ` ? ~ } int toneOffset = getTonePosition(vs, vEnd == m_current); int tonePos = vEnd - (info.len -1 ) + toneOffset; if (m_buffer[tonePos].tone == 0 && ev.tone == 0) return processAppend(ev); if (m_buffer[tonePos].tone == ev.tone) { markChange(tonePos); m_buffer[tonePos].tone = 0; m_singleMode = false; processAppend(ev); m_reverted = true; return 1; } markChange(tonePos); m_buffer[tonePos].tone = ev.tone; return 1; } //---------------------------------------------------------- int UkEngine::processDd(UkKeyEvent & ev) { if (!m_pCtrl->vietKey || m_current < 0) return processAppend(ev); int pos; // we want to allow dd even in non-vn sequence, because dd is used a lot in abbreviation // we allow dd only if preceding character is not a vowel if (m_buffer[m_current].form == vnw_nonVn && m_buffer[m_current].vnSym == vnl_d && (m_buffer[m_current-1].vnSym == vnl_nonVnChar ||!IsVnVowel[m_buffer[m_current-1].vnSym])) { m_singleMode = true; pos = m_current; markChange(pos); m_buffer[pos].cseq = cs_dd; m_buffer[pos].vnSym = vnl_dd; m_buffer[pos].form = vnw_c; m_buffer[pos].c1Offset = 0; m_buffer[pos].c2Offset = -1; m_buffer[pos].vOffset = -1; return 1; } if (m_buffer[m_current].c1Offset < 0) { return processAppend(ev); } pos = m_current - m_buffer[m_current].c1Offset; if (!m_pCtrl->options.freeMarking && pos != m_current) return processAppend(ev); if (m_buffer[pos].cseq == cs_d) { markChange(pos); m_buffer[pos].cseq = cs_dd; m_buffer[pos].vnSym = vnl_dd; //never spellcheck a word which starts with dd, because it's used alot in abbreviation m_singleMode = true; return 1; } if (m_buffer[pos].cseq == cs_dd) { //undo dd markChange(pos); m_buffer[pos].cseq = cs_d; m_buffer[pos].vnSym = vnl_d; m_singleMode = false; processAppend(ev); m_reverted = true; return 1; } return processAppend(ev); } //---------------------------------------------------------- VnLexiName changeCase(VnLexiName x) { if (x == vnl_nonVnChar) return x; if (!(x & 0x01)) return (VnLexiName)(x+1); return (VnLexiName)(x-1); } //---------------------------------------------------------- inline VnLexiName vnToLower(VnLexiName x) { if (x == vnl_nonVnChar) return x; if (!(x & 0x01)) //even return (VnLexiName)(x+1); return x; } //---------------------------------------------------------- int UkEngine::processMapChar(UkKeyEvent & ev) { int capsLockOn = 0; int shiftPressed = 0; if (m_keyCheckFunc) m_keyCheckFunc(&shiftPressed, &capsLockOn); if (capsLockOn) ev.vnSym = changeCase(ev.vnSym); int ret = processAppend(ev); if (!m_pCtrl->vietKey) return ret; if (m_current >= 0 && m_buffer[m_current].form != vnw_empty && m_buffer[m_current].form != vnw_nonVn) { return 1; } if (m_current < 0) return 0; // mapChar doesn't apply m_current--; WordInfo & entry = m_buffer[m_current]; bool undo = false; // test if undo is needed if (entry.form != vnw_empty && entry.form != vnw_nonVn) { VnLexiName prevSym = entry.vnSym; if (entry.caps) { prevSym = (VnLexiName)(prevSym - 1); } if (prevSym == ev.vnSym) { if (entry.form != vnw_c) { int vStart, vEnd, curTonePos, newTonePos, tone; VowelSeq vs, newVs; vEnd = m_current - entry.vOffset; vs = m_buffer[vEnd].vseq; vStart = vEnd - VSeqList[vs].len +1; curTonePos = vStart + getTonePosition(vs, vEnd == m_current); tone = m_buffer[curTonePos].tone; markChange(m_current); m_current--; //check if tone position is needed if (tone != 0 && m_current >= 0 && (m_buffer[m_current].form == vnw_v || m_buffer[m_current].form == vnw_cv)) { newVs = m_buffer[m_current].vseq; newTonePos = vStart + getTonePosition(newVs, true); if (newTonePos != curTonePos) { markChange(newTonePos); m_buffer[newTonePos].tone = tone; markChange(curTonePos); m_buffer[curTonePos].tone = 0; } } } else { markChange(m_current); m_current--; } undo = true; } } ev.evType = vneNormal; ev.chType = m_pCtrl->input.getCharType(ev.keyCode); ev.vnSym = IsoToVnLexi(ev.keyCode); ret = processAppend(ev); if (undo) { m_singleMode = false; m_reverted = true; return 1; } return ret; } //---------------------------------------------------------- int UkEngine::processTelexW(UkKeyEvent & ev) { if (!m_pCtrl->vietKey) return processAppend(ev); int ret; static bool usedAsMapChar = false; int capsLockOn = 0; int shiftPressed = 0; if (m_keyCheckFunc) m_keyCheckFunc(&shiftPressed, &capsLockOn); if (usedAsMapChar) { ev.evType = vneMapChar; ev.vnSym = isupper(ev.keyCode)? vnl_Uh : vnl_uh; if (capsLockOn) ev.vnSym = changeCase(ev.vnSym); ev.chType = ukcVn; ret = processMapChar(ev); if (ret == 0) { if (m_current >= 0) m_current--; usedAsMapChar = false; ev.evType = vneHookAll; return processHook(ev); } return ret; } ev.evType = vneHookAll; usedAsMapChar = false; ret = processHook(ev); if (ret == 0) { if (m_current >= 0) m_current--; ev.evType = vneMapChar; ev.vnSym = isupper(ev.keyCode)? vnl_Uh : vnl_uh; if (capsLockOn) ev.vnSym = changeCase(ev.vnSym); ev.chType = ukcVn; usedAsMapChar = true; return processMapChar(ev); } return ret; } //---------------------------------------------------------- int UkEngine::checkEscapeVIQR(UkKeyEvent & ev) { if (m_current < 0) return 0; WordInfo & entry = m_buffer[m_current]; int escape = 0; if (entry.form == vnw_v || entry.form == vnw_cv) { switch (ev.keyCode) { case '^': escape = (entry.vnSym == vnl_a || entry.vnSym == vnl_o || entry.vnSym == vnl_e); break; case '(': escape = (entry.vnSym == vnl_a); break; case '+': escape = (entry.vnSym == vnl_o || entry.vnSym == vnl_u); break; case '\'': case '`': case '?': case '~': case '.': escape = (entry.tone == 0); break; } } else if (entry.form == vnw_nonVn) { unsigned char ch = toupper(entry.keyCode); switch (ev.keyCode) { case '^': escape = (ch == 'A' || ch == 'O' || ch == 'E'); break; case '(': escape = (ch == 'A'); break; case '+': escape = (ch == 'O' || ch == 'U'); break; case '\'': case '`': case '?': case '~': case '.': escape = (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' || ch == 'Y'); break; } } if (escape) { m_current++; WordInfo *p = &m_buffer[m_current]; p->form = (ev.chType == ukcWordBreak) ? vnw_empty : vnw_nonVn; p->c1Offset = p->c2Offset = p->vOffset = -1; p->keyCode = '?'; p->vnSym = vnl_nonVnChar; m_current++; p++; p->form = (ev.chType == ukcWordBreak) ? vnw_empty : vnw_nonVn; p->c1Offset = p->c2Offset = p->vOffset = -1; p->keyCode = ev.keyCode; p->vnSym = vnl_nonVnChar; //write output m_pOutBuf[0] = '\\'; m_pOutBuf[1] = ev.keyCode; *m_pOutSize = 2; m_outputWritten = true; } return escape; } //---------------------------------------------------------- int UkEngine::processAppend(UkKeyEvent & ev) { int ret = 0; switch (ev.chType) { case ukcReset: #if defined(_WIN32) if (ev.keyCode == ENTER_CHAR) { if (m_pCtrl->options.macroEnabled && macroMatch(ev)) return 1; } #endif reset(); return 0; case ukcWordBreak: m_singleMode = false; return processWordEnd(ev); case ukcNonVn: { if (m_pCtrl->vietKey && m_pCtrl->charsetId == CONV_CHARSET_VIQR && checkEscapeVIQR(ev)) return 1; m_current++; WordInfo & entry = m_buffer[m_current]; entry.form = (ev.chType == ukcWordBreak) ? vnw_empty : vnw_nonVn; entry.c1Offset = entry.c2Offset = entry.vOffset = -1; entry.keyCode = ev.keyCode; entry.vnSym = vnToLower(ev.vnSym); entry.tone = 0; entry.caps = (entry.vnSym != ev.vnSym); if (!m_pCtrl->vietKey || m_pCtrl->charsetId != CONV_CHARSET_UNI_CSTRING) return 0; markChange(m_current); return 1; } case ukcVn: { if (IsVnVowel[ev.vnSym]) { VnLexiName v = (VnLexiName)StdVnNoTone[vnToLower(ev.vnSym)]; if (m_current >= 0 && m_buffer[m_current].form == vnw_c && ((m_buffer[m_current].cseq == cs_q && v == vnl_u) || (m_buffer[m_current].cseq == cs_g && v == vnl_i))) { return appendConsonnant(ev); //process u after q, i after g as consonnants } return appendVowel(ev); } return appendConsonnant(ev); } break; } return ret; } //---------------------------------------------------------- int UkEngine::appendVowel(UkKeyEvent & ev) { bool autoCompleted = false; m_current++; WordInfo & entry = m_buffer[m_current]; VnLexiName lowerSym = vnToLower(ev.vnSym); VnLexiName canSym = (VnLexiName)StdVnNoTone[lowerSym]; entry.vnSym = canSym; entry.caps = (lowerSym != ev.vnSym); entry.tone = (lowerSym - canSym)/2; entry.keyCode = ev.keyCode; if (m_current == 0 || !m_pCtrl->vietKey) { entry.form = vnw_v; entry.c1Offset = entry.c2Offset = -1; entry.vOffset = 0; entry.vseq = lookupVSeq(canSym); if (!m_pCtrl->vietKey || ((m_pCtrl->charsetId != CONV_CHARSET_UNI_CSTRING) && isalpha(entry.keyCode)) ) { return 0; } markChange(m_current); return 1; } WordInfo & prev = m_buffer[m_current-1]; VowelSeq vs, newVs; ConSeq cs; int prevTonePos; int tone, newTone, tonePos, newTonePos; switch (prev.form) { case vnw_empty: entry.form = vnw_v; entry.c1Offset = entry.c2Offset = -1; entry.vOffset = 0; entry.vseq = newVs = lookupVSeq(canSym); break; case vnw_nonVn: case vnw_cvc: case vnw_vc: entry.form = vnw_nonVn; entry.c1Offset = entry.c2Offset = entry.vOffset = -1; break; case vnw_v: case vnw_cv: vs = prev.vseq; prevTonePos = (m_current - 1) - (VSeqList[vs].len - 1) + getTonePosition(vs, true); tone = m_buffer[prevTonePos].tone; if (lowerSym != canSym && tone != 0) //new sym has a tone, but there's is already a preceeding tone newVs = vs_nil; else { if (VSeqList[vs].len == 3) newVs = vs_nil; else if (VSeqList[vs].len == 2) newVs = lookupVSeq(VSeqList[vs].v[0], VSeqList[vs].v[1], canSym); else newVs = lookupVSeq(VSeqList[vs].v[0], canSym); } if (newVs != vs_nil && prev.form == vnw_cv) { cs = m_buffer[m_current - 1 - prev.c1Offset].cseq; if (!isValidCV(cs, newVs)) newVs = vs_nil; } if (newVs == vs_nil) { entry.form = vnw_nonVn; entry.c1Offset = entry.c2Offset = entry.vOffset = -1; break; } entry.form = prev.form; if (prev.form == vnw_cv) entry.c1Offset = prev.c1Offset + 1; else entry.c1Offset = -1; entry.c2Offset = -1; entry.vOffset = 0; entry.vseq = newVs; entry.tone = 0; newTone = (lowerSym - canSym)/2; if (tone == 0) { if (newTone != 0) { tone = newTone; tonePos = getTonePosition(newVs, true) + ((m_current - 1) - VSeqList[vs].len + 1); markChange(tonePos); m_buffer[tonePos].tone = tone; return 1; } } else { newTonePos = getTonePosition(newVs, true) + ((m_current - 1) - VSeqList[vs].len + 1); if (newTonePos != prevTonePos) { markChange(prevTonePos); m_buffer[prevTonePos].tone = 0; markChange(newTonePos); if (newTone != 0) tone = newTone; m_buffer[newTonePos].tone = tone; return 1; } if (newTone != 0 && newTone != tone) { tone = newTone; markChange(prevTonePos); m_buffer[prevTonePos].tone = tone; return 1; } } break; case vnw_c: newVs = lookupVSeq(canSym); cs = prev.cseq; if (!isValidCV(cs, newVs)) { entry.form = vnw_nonVn; entry.c1Offset = entry.c2Offset = entry.vOffset = -1; break; } entry.form = vnw_cv; entry.c1Offset = 1; entry.c2Offset = -1; entry.vOffset = 0; entry.vseq = newVs; if (cs == cs_gi && prev.tone != 0) { if (entry.tone == 0) entry.tone = prev.tone; markChange(m_current - 1); prev.tone = 0; return 1; } break; } if (!autoCompleted && (m_pCtrl->charsetId != CONV_CHARSET_UNI_CSTRING) && isalpha(entry.keyCode)) { return 0; } markChange(m_current); return 1; } //---------------------------------------------------------- int UkEngine::appendConsonnant(UkKeyEvent & ev) { bool complexEvent = false; m_current++; WordInfo & entry = m_buffer[m_current]; VnLexiName lowerSym = vnToLower(ev.vnSym); entry.vnSym = lowerSym; entry.caps = (lowerSym != ev.vnSym); entry.keyCode = ev.keyCode; entry.tone = 0; if (m_current == 0 || !m_pCtrl->vietKey) { entry.form = vnw_c; entry.c1Offset = 0; entry.c2Offset = -1; entry.vOffset = -1; entry.cseq = lookupCSeq(lowerSym); if (!m_pCtrl->vietKey || m_pCtrl->charsetId != CONV_CHARSET_UNI_CSTRING) return 0; markChange(m_current); return 1; } ConSeq cs, newCs, c1; VowelSeq vs, newVs; bool isValid; WordInfo & prev = m_buffer[m_current-1]; switch (prev.form) { case vnw_nonVn: entry.form = vnw_nonVn; entry.c1Offset = entry.c2Offset = entry.vOffset = -1; if (m_pCtrl->charsetId != CONV_CHARSET_UNI_CSTRING) return 0; markChange(m_current); return 1; case vnw_empty: entry.form = vnw_c; entry.c1Offset = 0; entry.c2Offset = -1; entry.vOffset = -1; entry.cseq = lookupCSeq(lowerSym); if (m_pCtrl->charsetId != CONV_CHARSET_UNI_CSTRING) return 0; markChange(m_current); return 1; case vnw_v: case vnw_cv: vs = prev.vseq; newVs = vs; if (vs == vs_uoh || vs == vs_uho) { newVs = vs_uhoh; } c1 = cs_nil; if (prev.c1Offset != -1) c1 = m_buffer[m_current-1-prev.c1Offset].cseq; newCs = lookupCSeq(lowerSym); isValid = isValidCVC(c1, newVs, newCs); if (isValid) { //check u+o -> u+o+ if (vs == vs_uho) { markChange(m_current-1); prev.vnSym = vnl_oh; prev.vseq = vs_uhoh; complexEvent = true; } else if (vs == vs_uoh) { markChange(m_current-2); m_buffer[m_current-2].vnSym = vnl_uh; m_buffer[m_current-2].vseq = vs_uh; prev.vseq = vs_uhoh; complexEvent = true; } if (prev.form == vnw_v) { entry.form = vnw_vc; entry.c1Offset = -1; entry.c2Offset = 0; entry.vOffset = 1; } else { //prev == vnw_cv entry.form = vnw_cvc; entry.c1Offset = prev.c1Offset + 1; entry.c2Offset = 0; entry.vOffset = 1; } entry.cseq = newCs; //reposition tone if needed int oldIdx = (m_current-1) - (VSeqList[vs].len - 1) + getTonePosition(vs, true); if (m_buffer[oldIdx].tone != 0) { int newIdx = (m_current-1) - (VSeqList[newVs].len - 1) + getTonePosition(newVs, false); if (newIdx != oldIdx) { markChange(newIdx); m_buffer[newIdx].tone = m_buffer[oldIdx].tone; markChange(oldIdx); m_buffer[oldIdx].tone = 0; return 1; } } } else { entry.form = vnw_nonVn; entry.c1Offset = entry.c2Offset = entry.vOffset = -1; } if (complexEvent) { return 1; } if (m_pCtrl->charsetId != CONV_CHARSET_UNI_CSTRING) return 0; markChange(m_current); return 1; case vnw_c: case vnw_vc: case vnw_cvc: cs = prev.cseq; if (CSeqList[cs].len == 3) newCs = cs_nil; else if (CSeqList[cs].len == 2) newCs = lookupCSeq(CSeqList[cs].c[0], CSeqList[cs].c[1], lowerSym); else newCs = lookupCSeq(CSeqList[cs].c[0], lowerSym); if (newCs != cs_nil && (prev.form == vnw_vc || prev.form == vnw_cvc)) { // Check CVC combination c1 = cs_nil; if (prev.c1Offset != -1) c1 = m_buffer[m_current-1-prev.c1Offset].cseq; int vIdx = (m_current - 1) - prev.vOffset; vs = m_buffer[vIdx].vseq; isValid = isValidCVC(c1, vs, newCs); if (!isValid) newCs = cs_nil; } if (newCs == cs_nil) { entry.form = vnw_nonVn; entry.c1Offset = entry.c2Offset = entry.vOffset = -1; } else { if (prev.form == vnw_c) { entry.form = vnw_c; entry.c1Offset = 0; entry.c2Offset = -1; entry.vOffset = -1; } else if (prev.form == vnw_vc) { entry.form = vnw_vc; entry.c1Offset = -1; entry.c2Offset = 0; entry.vOffset = prev.vOffset + 1; } else { //vnw_cvc entry.form = vnw_cvc; entry.c1Offset = prev.c1Offset + 1; entry.c2Offset = 0; entry.vOffset = prev.vOffset + 1; } entry.cseq = newCs; } if (m_pCtrl->charsetId != CONV_CHARSET_UNI_CSTRING) return 0; markChange(m_current); return 1; } if (m_pCtrl->charsetId != CONV_CHARSET_UNI_CSTRING) return 0; markChange(m_current); return 1; } //---------------------------------------------------------- int UkEngine::processEscChar(UkKeyEvent & ev) { if (m_pCtrl->vietKey && m_current >=0 && m_buffer[m_current].form != vnw_empty && m_buffer[m_current].form != vnw_nonVn) { m_toEscape = true; } return processAppend(ev); } //---------------------------------------------------------- void UkEngine::pass(int keyCode) { UkKeyEvent ev; m_pCtrl->input.keyCodeToEvent(keyCode, ev); processAppend(ev); } //--------------------------------------------- // This can be called only after other processing have been done. // The new event is supposed to be put into m_buffer already //--------------------------------------------- int UkEngine::processNoSpellCheck(UkKeyEvent & ev) { WordInfo & entry = m_buffer[m_current]; if (IsVnVowel[entry.vnSym]) { entry.form = vnw_v; entry.vOffset = 0; entry.vseq = lookupVSeq(entry.vnSym); entry.c1Offset = entry.c2Offset = -1; } else { entry.form = vnw_c; entry.c1Offset = 0; entry.c2Offset = -1; entry.vOffset = -1; entry.cseq = lookupCSeq(entry.vnSym); } if (ev.evType == vneNormal && ((entry.keyCode >= 'a' && entry.keyCode <= 'z') || (entry.keyCode >= 'A' && entry.keyCode <= 'Z') ) ) return 0; markChange(m_current); return 1; } //---------------------------------------------------------- int UkEngine::process(unsigned int keyCode, int & backs, unsigned char *outBuf, int & outSize, UkOutputType & outType) { UkKeyEvent ev; prepareBuffer(); m_backs = 0; m_changePos = m_current+1; m_pOutBuf = outBuf; m_pOutSize = &outSize; m_outputWritten = false; m_reverted = false; m_keyRestored = false; m_keyRestoring = false; m_outType = UkCharOutput; m_pCtrl->input.keyCodeToEvent(keyCode, ev); int ret; if (!m_toEscape) { ret = (this->*UkKeyProcList[ev.evType])(ev); } else { m_toEscape = false; if (m_current < 0 || ev.evType == vneNormal || ev.evType == vneEscChar) { ret = processAppend(ev); } else { m_current--; processAppend(ev); markChange(m_current); //this will assign m_backs to 1 and mark the character for output ret = 1; } } if ( m_pCtrl->vietKey && m_current >= 0 && m_buffer[m_current].form == vnw_nonVn && ev.chType == ukcVn && (!m_pCtrl->options.spellCheckEnabled || m_singleMode) ) { //The spell check has failed, but because we are in non-spellcheck mode, //we consider the new character as the beginning of a new word ret = processNoSpellCheck(ev); /* if ((!m_pCtrl->options.spellCheckEnabled || m_singleMode) || ( !m_reverted && (m_current < 1 || m_buffer[m_current-1].form != vnw_nonVn)) ) { ret = processNoSpellCheck(ev); } */ } //we add key to key buffer only if that key has not caused a reset if (m_current >= 0) { ev.chType = m_pCtrl->input.getCharType(ev.keyCode); m_keyCurrent++; m_keyStrokes[m_keyCurrent].ev = ev; m_keyStrokes[m_keyCurrent].converted = (ret && !m_keyRestored); } if (ret == 0) { backs = 0; outSize = 0; outType = m_outType; return 0; } backs = m_backs; if (!m_outputWritten) { writeOutput(outBuf, outSize); } outType = m_outType; return ret; } //---------------------------------------------------------- // Returns 0 on success // error code otherwise // outBuf: buffer to write // outSize: [in] size of buffer in bytes // [out] bytes written to buffer //---------------------------------------------------------- int UkEngine::writeOutput(unsigned char *outBuf, int & outSize) { StdVnChar stdChar; int i, bytesWritten; int ret = 1; StringBOStream os(outBuf, outSize); VnCharset *pCharset = VnCharsetLibObj.getVnCharset(m_pCtrl->charsetId); pCharset->startOutput(); for (i = m_changePos; i <= m_current; i++) { if (m_buffer[i].vnSym != vnl_nonVnChar) { //process vn symbol stdChar = m_buffer[i].vnSym + VnStdCharOffset; if (m_buffer[i].caps) stdChar--; if (m_buffer[i].tone != 0) stdChar += m_buffer[i].tone * 2; } else { stdChar = IsoToStdVnChar(m_buffer[i].keyCode); } if (stdChar != INVALID_STD_CHAR) ret = pCharset->putChar(os, stdChar, bytesWritten); } outSize = os.getOutBytes(); return (ret? 0 : VNCONV_OUT_OF_MEMORY); } //--------------------------------------------- // Returns the number of backspaces needed to // go back from last to first //--------------------------------------------- int UkEngine::getSeqSteps(int first, int last) { StdVnChar stdChar; if (last < first) return 0; if (m_pCtrl->charsetId == CONV_CHARSET_XUTF8 || m_pCtrl->charsetId == CONV_CHARSET_UNICODE) return (last - first + 1); StringBOStream os(0, 0); int i, bytesWritten; VnCharset *pCharset = VnCharsetLibObj.getVnCharset(m_pCtrl->charsetId); pCharset->startOutput(); for (i = first; i <= last; i++) { if (m_buffer[i].vnSym != vnl_nonVnChar) { //process vn symbol stdChar = m_buffer[i].vnSym + VnStdCharOffset; if (m_buffer[i].caps) stdChar--; if (m_buffer[i].tone != 0) stdChar += m_buffer[i].tone*2; } else { stdChar = m_buffer[i].keyCode; } if (stdChar != INVALID_STD_CHAR) pCharset->putChar(os, stdChar, bytesWritten); } int len = os.getOutBytes(); if (m_pCtrl->charsetId == CONV_CHARSET_UNIDECOMPOSED) len = len / 2; return len; } //--------------------------------------------- void UkEngine::markChange(int pos) { if (pos < m_changePos) { m_backs += getSeqSteps(pos, m_changePos-1); m_changePos = pos; } } //---------------------------------------------------------------- // Called from processBackspace to keep // character buffer (m_buffer) and key stroke buffer in synch //---------------------------------------------------------------- void UkEngine::synchKeyStrokeBuffer() { //synchronize with key-stroke buffer if (m_keyCurrent >= 0) m_keyCurrent--; if (m_current >= 0 && m_buffer[m_current].form == vnw_empty) { //in character buffer, we have reached a word break, //so we also need to move key stroke pointer backward to corresponding word break while (m_keyCurrent >= 0 && m_keyStrokes[m_keyCurrent].ev.chType != ukcWordBreak) { m_keyCurrent--; } } } //--------------------------------------------- int UkEngine::processBackspace(int & backs, unsigned char *outBuf, int & outSize, UkOutputType & outType) { outType = UkCharOutput; if (!m_pCtrl->vietKey || m_current < 0) { backs = 0; outSize = 0; return 0; } m_backs = 0; m_changePos = m_current + 1; markChange(m_current); if (m_current == 0 || m_buffer[m_current].form == vnw_empty || m_buffer[m_current].form == vnw_nonVn || m_buffer[m_current].form == vnw_c || m_buffer[m_current-1].form == vnw_c || m_buffer[m_current-1].form == vnw_cvc || m_buffer[m_current-1].form == vnw_vc) { m_current--; backs = m_backs; outSize = 0; synchKeyStrokeBuffer(); return (backs > 1); } VowelSeq vs, newVs; int curTonePos, newTonePos, tone, vStart, vEnd; vEnd = m_current - m_buffer[m_current].vOffset; vs = m_buffer[vEnd].vseq; vStart = vEnd - VSeqList[vs].len + 1; newVs = m_buffer[m_current-1].vseq; curTonePos = vStart + getTonePosition(vs, vEnd == m_current); newTonePos = vStart + getTonePosition(newVs, true); tone = m_buffer[curTonePos].tone; if (tone == 0 || curTonePos == newTonePos || (curTonePos == m_current && m_buffer[m_current].tone != 0)) { m_current--; backs = m_backs; outSize = 0; synchKeyStrokeBuffer(); return (backs > 1); } markChange(newTonePos); m_buffer[newTonePos].tone = tone; markChange(curTonePos); m_buffer[curTonePos].tone = 0; m_current--; synchKeyStrokeBuffer(); backs = m_backs; writeOutput(outBuf, outSize); return 1; } //------------------------------------------------ void UkEngine::reset() { m_current = -1; m_keyCurrent = -1; m_singleMode = false; m_toEscape = false; } //------------------------------------------------ void UkEngine::resetKeyBuf() { m_keyCurrent = -1; } //------------------------------------------------ UkEngine::UkEngine() { if (!m_classInit) { engineClassInit(); m_classInit = true; } m_pCtrl = 0; m_bufSize = MAX_UK_ENGINE; m_keyBufSize = MAX_UK_ENGINE; m_current = -1; m_keyCurrent = -1; m_singleMode = false; m_keyCheckFunc = 0; m_reverted = false; m_toEscape = false; m_keyRestored = false; } //---------------------------------------------------- // make sure there are at least 10 entries available //---------------------------------------------------- void UkEngine::prepareBuffer() { int rid; //prepare symbol buffer if (m_current >= 0 && m_current + 10 >= m_bufSize) { // Get rid of at least half of the current entries // don't get rid from the middle of a word. for (rid = m_current/2; m_buffer[rid].form != vnw_empty && rid < m_current; rid++); if (rid == m_current) { m_current = -1; } else { rid++; memmove(m_buffer, m_buffer+rid, (m_current-rid+1)*sizeof(WordInfo)); m_current -= rid; } } //prepare key stroke buffer if (m_keyCurrent > 0 && m_keyCurrent + 1 >= m_keyBufSize) { // Get rid of at least half of the current entries rid = m_keyCurrent/2; memmove(m_keyStrokes, m_keyStrokes + rid, (m_keyCurrent-rid+1)*sizeof(m_keyStrokes[0])); m_keyCurrent -= rid; } } #define ENTER_CHAR 13 enum VnCaseType {VnCaseNoChange, VnCaseAllCapital, VnCaseAllSmall}; //---------------------------------------------------- int UkEngine::macroMatch(UkKeyEvent & ev) { int capsLockOn = 0; int shiftPressed = 0; if (m_keyCheckFunc) m_keyCheckFunc(&shiftPressed, &capsLockOn); if (shiftPressed && (ev.keyCode ==' ' || ev.keyCode == ENTER_CHAR)) return 0; const StdVnChar *pMacText = NULL; StdVnChar key[MAX_MACRO_KEY_LEN+1]; StdVnChar *pKeyStart; // Use static macro text so we can gain a bit of performance // by avoiding memory allocation each time this function is called static StdVnChar macroText[MAX_MACRO_TEXT_LEN+1]; int i, j; i = m_current; while (i >= 0 && (m_current-i + 1) < MAX_MACRO_KEY_LEN) { while (i>=0 && m_buffer[i].form != vnw_empty && (m_current-i + 1) < MAX_MACRO_KEY_LEN) i--; if (i>=0 && m_buffer[i].form != vnw_empty) return 0; if (i>=0) { if (m_buffer[i].vnSym != vnl_nonVnChar) { key[0] = m_buffer[i].vnSym + VnStdCharOffset; if (m_buffer[i].caps) key[0]--; key[0] += m_buffer[i].tone*2; } else key[0] = m_buffer[i].keyCode; } for (j=i+1; j<=m_current; j++) { if (m_buffer[j].vnSym != vnl_nonVnChar) { key[j-i] = m_buffer[j].vnSym + VnStdCharOffset; if (m_buffer[j].caps) key[j-i]--; key[j-i] += m_buffer[j].tone*2; } else key[j-i] = m_buffer[j].keyCode; } key[m_current-i+1] = 0; //search macro table pMacText = m_pCtrl->macStore.lookup(key+1); if (pMacText) { i++; //mark the position where change is needed pKeyStart = key + 1; break; } if (i>=0) { pMacText = m_pCtrl->macStore.lookup(key); if (pMacText) { pKeyStart = key; break; } } i--; } if (!pMacText) { return 0; } markChange(i); // determine the form of macro replacements: ALL CAPITALS, First Character Capital, or no change VnCaseType macroCase; if (IS_STD_VN_LOWER(*pKeyStart)) { macroCase = VnCaseAllSmall; } else if (IS_STD_VN_UPPER(*pKeyStart)) { macroCase = VnCaseAllCapital; for (i=1; pKeyStart[i]; i++) { if (IS_STD_VN_LOWER(pKeyStart[i])) { macroCase = VnCaseNoChange; } } } else macroCase = VnCaseNoChange; // Convert case of macro text according to macroCase int charCount = 0; while (pMacText[charCount] != 0) charCount++; for (i = 0; i < charCount; i++) { if (macroCase == VnCaseAllCapital) macroText[i] = StdVnToUpper(pMacText[i]); else if (macroCase == VnCaseAllSmall) macroText[i] = StdVnToLower(pMacText[i]); else macroText[i] = pMacText[i]; } // Convert to target output charset int outSize; int maxOutSize = *m_pOutSize; int inLen = charCount * sizeof(StdVnChar); VnConvert(CONV_CHARSET_VNSTANDARD, m_pCtrl->charsetId, (UKBYTE *) macroText, (UKBYTE *)m_pOutBuf, &inLen, &maxOutSize); outSize = maxOutSize; //write the last input character StdVnChar vnChar; if (outSize < *m_pOutSize) { maxOutSize = *m_pOutSize - outSize; if (ev.vnSym != vnl_nonVnChar) vnChar = ev.vnSym + VnStdCharOffset; else vnChar = ev.keyCode; inLen = sizeof(StdVnChar); VnConvert(CONV_CHARSET_VNSTANDARD, m_pCtrl->charsetId, (UKBYTE *) &vnChar, ((UKBYTE *)m_pOutBuf) + outSize, &inLen, &maxOutSize); outSize += maxOutSize; } int backs = m_backs; //store m_backs before calling reset reset(); m_outputWritten = true; m_backs = backs; *m_pOutSize = outSize; return 1; } //---------------------------------------------------- int UkEngine::restoreKeyStrokes(int & backs, unsigned char *outBuf, int & outSize, UkOutputType & outType) { outType = UkKeyOutput; if (!lastWordHasVnMark()) { backs = 0; outSize = 0; return 0; } m_backs = 0; m_changePos = m_current+1; int keyStart; bool converted = false; for (keyStart = m_keyCurrent; keyStart >= 0 && m_keyStrokes[keyStart].ev.chType != ukcWordBreak; keyStart--) { if (m_keyStrokes[keyStart].converted) { converted = true; } } keyStart++; if (!converted) { //no key stroke has been converted, so it doesn't make sense to restore key strokes backs = 0; outSize = 0; return 0; } //int i = m_current; while (m_current >=0 && m_buffer[m_current].form != vnw_empty) m_current--; markChange(m_current+1); backs = m_backs; int count; int i; UkKeyEvent ev; m_keyRestoring = true; for (i=keyStart, count = 0; i <= m_keyCurrent; i++) { if (countinput.keyCodeToSymbol(m_keyStrokes[i].ev.keyCode, ev); m_keyStrokes[i].converted = false; processAppend(ev); } outSize = count; m_keyRestoring = false; return 1; } //-------------------------------------------------- void UkEngine::setSingleMode() { m_singleMode = true; } //-------------------------------------------------- void SetupUnikeyEngine() { SetupInputClassifierTable(); int i; VnLexiName lexi; //Calculate IsoStdVnCharMap for (i=0; i < 256; i++) { IsoStdVnCharMap[i] = i; } for (i=0; SpecialWesternChars[i]; i++) { IsoStdVnCharMap[SpecialWesternChars[i]] = (vnl_lastChar + i) + VnStdCharOffset; } for (i=0; i < 256; i++) { if ((lexi = IsoToVnLexi(i)) != vnl_nonVnChar) { IsoStdVnCharMap[i] = lexi + VnStdCharOffset; } } } //-------------------------------------------------- bool UkEngine::atWordBeginning() { return (m_current < 0 || m_buffer[m_current].form == vnw_empty); } //-------------------------------------------------- // Check for macro first, if there's a match, expand macro. If not: // Spell-check, if is valid Vietnamese, return normally, if not: // restore key strokes if auto-restore is enabled //-------------------------------------------------- int UkEngine::processWordEnd(UkKeyEvent & ev) { if (m_pCtrl->options.macroEnabled && macroMatch(ev)) return 1; if (!m_pCtrl->options.spellCheckEnabled || m_singleMode || m_current < 0 || m_keyRestoring) { m_current++; WordInfo & entry = m_buffer[m_current]; entry.form = vnw_empty; entry.c1Offset = entry.c2Offset = entry.vOffset = -1; entry.keyCode = ev.keyCode; entry.vnSym = vnToLower(ev.vnSym); entry.caps = (entry.vnSym != ev.vnSym); return 0; } int outSize = 0; if (m_pCtrl->options.autoNonVnRestore && lastWordIsNonVn()) { outSize = *m_pOutSize; if (restoreKeyStrokes(m_backs, m_pOutBuf, outSize, m_outType)) { m_keyRestored = true; m_outputWritten = true; } } m_current++; WordInfo & entry = m_buffer[m_current]; entry.form = vnw_empty; entry.c1Offset = entry.c2Offset = entry.vOffset = -1; entry.keyCode = ev.keyCode; entry.vnSym = vnToLower(ev.vnSym); entry.caps = (entry.vnSym != ev.vnSym); if (m_keyRestored && outSize < *m_pOutSize) { m_pOutBuf[outSize] = ev.keyCode; outSize++; *m_pOutSize = outSize; return 1; } return 0; } //--------------------------------------------------------------------------- // Test if last word is a non-Vietnamese word, so that // the engine can restore key strokes if it is indeed not a Vietnamese word //--------------------------------------------------------------------------- bool UkEngine::lastWordIsNonVn() { if (m_current < 0) return false; switch (m_buffer[m_current].form) { case vnw_nonVn: return true; case vnw_empty: case vnw_c: return false; case vnw_v: case vnw_cv: return !VSeqList[m_buffer[m_current].vseq].complete; case vnw_vc: case vnw_cvc: { int vIndex = m_current - m_buffer[m_current].vOffset; VowelSeq vs = m_buffer[vIndex].vseq; if (!VSeqList[vs].complete) return true; ConSeq cs = m_buffer[m_current].cseq; ConSeq c1 = cs_nil; if (m_buffer[m_current].c1Offset != -1) c1 = m_buffer[m_current-m_buffer[m_current].c1Offset].cseq; if (!isValidCVC(c1, vs, cs)) { return true; } int tonePos = (vIndex - VSeqList[vs].len + 1) + getTonePosition(vs, false); int tone = m_buffer[tonePos].tone; if ((cs == cs_c || cs == cs_ch || cs == cs_p || cs == cs_t) && (tone == 2 || tone == 3 || tone == 4)) { return true; } } } return false; } //--------------------------------------------------------------------------- // Test if last word has a Vietnamese mark, that is tones, decorators //--------------------------------------------------------------------------- bool UkEngine::lastWordHasVnMark() { for (int i=m_current; i>=0 && m_buffer[i].form != vnw_empty; i--) { VnLexiName sym = m_buffer[i].vnSym; if (sym != vnl_nonVnChar) { if (IsVnVowel[sym]) { if (m_buffer[i].tone) return true; } if (sym != StdVnRootChar[sym] ) return true; } } return false; } ibus-unikey-0.7.0~beta1/ukengine/ukengine.h0000664000175000017500000001067713441506611020244 0ustar gunnargunnar// -*- mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /* Unikey Vietnamese Input Method * Copyright (C) 2000-2005 Pham Kim Long * Contact: * unikey@gmail.com * UniKey project: http://unikey.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __UKENGINE_H #define __UKENGINE_H #include "charset.h" #include "vnlexi.h" #include "inputproc.h" #include "mactab.h" //This is a shared object among processes, do not put any pointer in it struct UkSharedMem { //states int initialized; int vietKey; UnikeyOptions options; UkInputProcessor input; int usrKeyMapLoaded; int usrKeyMap[256]; int charsetId; CMacroTable macStore; }; #define MAX_UK_ENGINE 128 enum VnWordForm {vnw_nonVn, vnw_empty, vnw_c, vnw_v, vnw_cv, vnw_vc, vnw_cvc}; typedef void (* CheckKeyboardCaseCb)(int *pShiftPressed, int *pCapslockOn); struct KeyBufEntry { UkKeyEvent ev; bool converted; }; class UkEngine { public: UkEngine(); void setCtrlInfo(UkSharedMem *p) { m_pCtrl = p; } void setCheckKbCaseFunc(CheckKeyboardCaseCb pFunc) { m_keyCheckFunc = pFunc; } bool atWordBeginning(); int process(unsigned int keyCode, int & backs, unsigned char *outBuf, int & outSize, UkOutputType & outType); void pass(int keyCode); //just pass through without filtering void setSingleMode(); int processBackspace(int & backs, unsigned char *outBuf, int & outSize, UkOutputType & outType); void reset(); int restoreKeyStrokes(int & backs, unsigned char *outBuf, int & outSize, UkOutputType & outType); //following methods must be public just to enable the use of pointers to them //they should not be called from outside. int processTone(UkKeyEvent & ev); int processRoof(UkKeyEvent & ev); int processHook(UkKeyEvent & ev); int processAppend(UkKeyEvent & ev); int appendVowel(UkKeyEvent & ev); int appendConsonnant(UkKeyEvent & ev); int processDd(UkKeyEvent & ev); int processMapChar(UkKeyEvent & ev); int processTelexW(UkKeyEvent & ev); int processEscChar(UkKeyEvent & ev); protected: static bool m_classInit; CheckKeyboardCaseCb m_keyCheckFunc; UkSharedMem *m_pCtrl; int m_changePos; int m_backs; int m_bufSize; int m_current; int m_singleMode; int m_keyBufSize; //unsigned int m_keyStrokes[MAX_UK_ENGINE]; KeyBufEntry m_keyStrokes[MAX_UK_ENGINE]; int m_keyCurrent; bool m_toEscape; //varables valid in one session unsigned char *m_pOutBuf; int *m_pOutSize; bool m_outputWritten; bool m_reverted; bool m_keyRestored; bool m_keyRestoring; UkOutputType m_outType; struct WordInfo { //info for word ending at this position VnWordForm form; int c1Offset, vOffset, c2Offset; union { VowelSeq vseq; ConSeq cseq; }; //info for current symbol int caps, tone; //canonical symbol, after caps, tone are removed //for non-Vn, vnSym == -1 VnLexiName vnSym; int keyCode; }; WordInfo m_buffer[MAX_UK_ENGINE]; int processHookWithUO(UkKeyEvent & ev); int macroMatch(UkKeyEvent & ev); void markChange(int pos); void prepareBuffer(); //make sure we have a least 10 entries available int writeOutput(unsigned char *outBuf, int & outSize); //int getSeqLength(int first, int last); int getSeqSteps(int first, int last); int getTonePosition(VowelSeq vs, bool terminated); void resetKeyBuf(); int checkEscapeVIQR(UkKeyEvent & ev); int processNoSpellCheck(UkKeyEvent & ev); int processWordEnd(UkKeyEvent & ev); void synchKeyStrokeBuffer(); bool lastWordHasVnMark(); bool lastWordIsNonVn(); }; void SetupUnikeyEngine(); #endif ibus-unikey-0.7.0~beta1/ukengine/mactab.h0000664000175000017500000000410213441506611017650 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /* Unikey Vietnamese Input Method * Copyright (C) 2000-2005 Pham Kim Long * Contact: * unikey@gmail.com * UniKey project: http://unikey.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __MACRO_TABLE_H #define __MACRO_TABLE_H #include "keycons.h" #include "charset.h" #if defined(_WIN32) #if defined(UNIKEYHOOK) #define DllInterface __declspec( dllexport ) #else #define DllInterface __declspec( dllimport ) #endif #else #define DllInterface //not used #define DllExport #define DllImport #endif struct MacroDef { int keyOffset; int textOffset; }; #if !defined(WIN32) typedef char TCHAR; #endif class DllInterface CMacroTable { public: void init(); int loadFromFile(const char *fname); int writeToFile(const char *fname); const StdVnChar *lookup(StdVnChar *key); const StdVnChar *getKey(int idx); const StdVnChar *getText(int idx); int getCount() { return m_count; } void resetContent(); int addItem(const char *item, int charset); int addItem(const void *key, const void *text, int charset); protected: bool readHeader(FILE *f, int & version); void writeHeader(FILE *f); MacroDef m_table[MAX_MACRO_ITEMS]; char m_macroMem[MACRO_MEM_SIZE]; int m_count; int m_memSize, m_occupied; }; #endif ibus-unikey-0.7.0~beta1/ukengine/charset.cpp0000664000175000017500000007762413441506611020430 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /*------------------------------------------------------------------------------ VnConv: Vietnamese Encoding Converter Library UniKey Project: http://unikey.sourceforge.net Copyleft (C) 1998-2002 Pham Kim Long Contact: longp@cslab.felk.cvut.cz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --------------------------------------------------------------------------------*/ #include #include #include #include #include #include "charset.h" #include "data.h" int LoVowel['z'-'a'+1]; int HiVowel['Z'-'A'+1]; #define IS_VOWEL(x) ((x >= 'a' && x <= 'z' && LoVowel[x-'a']) || (x >= 'A' && x <= 'Z' && HiVowel[x-'A'])) SingleByteCharset *SgCharsets[CONV_TOTAL_SINGLE_CHARSETS]; DoubleByteCharset *DbCharsets[CONV_TOTAL_DOUBLE_CHARSETS]; DllExport CVnCharsetLib VnCharsetLibObj; ////////////////////////////////////////////////////// // Generic VnCharset class ////////////////////////////////////////////////////// int VnCharset::elementSize() { return 1; } //------------------------------------------- int VnInternalCharset::nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead) { if (!is.getNextDW(stdChar)) { bytesRead = 0; return 0; } bytesRead = sizeof(UKDWORD); return 1; } //------------------------------------------- int VnInternalCharset::putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen) { outLen = sizeof(StdVnChar); os.putW((UKWORD)stdChar); return os.putW((UKWORD)(stdChar>>(sizeof(UKWORD)*8))); } //------------------------------------------- int VnInternalCharset::elementSize() { return 4; } //------------------------------------------- SingleByteCharset::SingleByteCharset(unsigned char * vnChars) { int i; m_vnChars = vnChars; memset(m_stdMap, 0, 256*sizeof(UKWORD)); for (i=0; i= VnStdCharOffset) { outLen = 1; ch = m_vnChars[stdChar - VnStdCharOffset]; if (ch == 0) ch = (stdChar == StdStartQuote)? PadStartQuote : ((stdChar == StdEndQuote)? PadEndQuote : ((stdChar == StdEllipsis)? PadEllipsis: PadChar) ); ret = os.putB(ch); } else { if (stdChar > 255 || m_stdMap[stdChar]) { //this character is missing in the charset // output padding character outLen = 1; ret = os.putB(PadChar); } else { outLen = 1; ret = os.putB((UKBYTE)stdChar); } } return ret; } //------------------------------------------- int wideCharCompare(const void *ele1, const void *ele2) { UKWORD ch1 = LOWORD(*((UKDWORD *)ele1)); UKWORD ch2 = LOWORD(*((UKDWORD *)ele2)); return (ch1 == ch2)? 0 : ((ch1 > ch2)? 1 : -1); } //------------------------------------------- UnicodeCharset::UnicodeCharset(UnicodeChar *vnChars) { UKDWORD i; m_toUnicode = vnChars; for (i=0; i= VnStdCharOffset)? m_toUnicode[stdChar-VnStdCharOffset] : (UnicodeChar)stdChar); } //------------------------------------------- int UnicodeCharset::elementSize() { return 2; } //////////////////////////////////////// // Unicode decomposed //////////////////////////////////////// //------------------------------------------- int uniCompInfoCompare(const void *ele1, const void *ele2) { UKDWORD ch1 = ((UniCompCharInfo *)ele1)->compChar; UKDWORD ch2 = ((UniCompCharInfo *)ele2)->compChar; return (ch1 == ch2)? 0 : ((ch1 > ch2)? 1 : -1); } UnicodeCompCharset::UnicodeCompCharset(UnicodeChar *uniChars, UKDWORD *uniCompChars) { int i,k; m_uniCompChars = uniCompChars; m_totalChars = 0; for (i=0; istdIndex + VnStdCharOffset; if (is.peekNextW(w)) { UKDWORD hi = w; if (hi > 0) { key.compChar += hi << 16; pInfo = (UniCompCharInfo *)bsearch(&key, m_info, m_totalChars, sizeof(UniCompCharInfo), uniCompInfoCompare); if (pInfo) { stdChar = pInfo->stdIndex + VnStdCharOffset; bytesRead += 2; is.getNextW(w); } } } } return 1; } //--------------------------------------------- int UnicodeCompCharset::putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen) { int ret; if (stdChar >= VnStdCharOffset) { UKDWORD uniCompCh = m_uniCompChars[stdChar-VnStdCharOffset]; UKWORD lo = LOWORD(uniCompCh); UKWORD hi = HIWORD(uniCompCh); outLen = 2; ret = os.putW(lo); if (hi > 0) { outLen += 2; ret = os.putW(hi); } } else { outLen = 2; ret = os.putW((UKWORD)stdChar); } return ret; } //------------------------------------------- int UnicodeCompCharset::elementSize() { return 2; } //////////////////////////////// // Unicode UTF-8 // //////////////////////////////// int UnicodeUTF8Charset::nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead) { UKWORD w1, w2, w3; UKBYTE first, second, third; UnicodeChar uniCh; bytesRead = 0; if (!is.getNext(first)) return 0; bytesRead = 1; if (first < 0x80) uniCh = first; // 1-byte sequence else if ((first & 0xE0) == 0xC0) { //2-byte sequence if (!is.peekNext(second)) return 0; if ((second & 0xC0) != 0x80) { stdChar = INVALID_STD_CHAR; return 1; } is.getNext(second); bytesRead = 2; w1 = first; w2 = second; uniCh = ((w1 & 0x001F) << 6) | (w2 & 0x3F); } else if ((first & 0xF0) == 0xE0) { //3-byte sequence if (!is.peekNext(second)) return 0; if ((second & 0xC0) != 0x80) { stdChar = INVALID_STD_CHAR; return 1; } is.getNext(second); bytesRead = 2; if (!is.peekNext(third)) return 0; if ((third & 0xC0) != 0x80) { stdChar = INVALID_STD_CHAR; return 1; } is.getNext(third); bytesRead = 3; w1 = first; w2 = second; w3 = third; uniCh = ((w1 & 0x000F) << 12) | ((w2 & 0x003F) << 6) | (w3 & 0x003F); } else { stdChar = INVALID_STD_CHAR; return 1; } // translate to StdVnChar UKDWORD key = uniCh; UKDWORD *pChar = (UKDWORD *)bsearch(&key, m_vnChars, TOTAL_VNCHARS, sizeof(UKDWORD), wideCharCompare); if (pChar) stdChar = VnStdCharOffset + HIWORD(*pChar); else stdChar = uniCh; return 1; } //------------------------------------------- int UnicodeUTF8Charset::putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen) { UnicodeChar uChar = (stdChar < VnStdCharOffset)? (UnicodeChar)stdChar : m_toUnicode[stdChar-VnStdCharOffset]; int ret; if (uChar < 0x0080) { outLen = 1; ret = os.putB((UKBYTE)uChar); } else if (uChar < 0x0800) { outLen = 2; os.putB(0xC0 | (UKBYTE)(uChar >> 6)); ret = os.putB(0x80 | (UKBYTE)(uChar & 0x003F)); } else { outLen = 3; os.putB(0xE0 | (UKBYTE)(uChar >> 12)); os.putB(0x80 | (UKBYTE)((uChar >> 6) & 0x003F)); ret = os.putB(0x80 | (UKBYTE)(uChar & 0x003F)); } return ret; } //////////////////////////////////////// // Unicode character reference &#D; // //////////////////////////////////////// int hexDigitValue(unsigned char digit) { if (digit >= 'a' && digit <= 'f') return digit-'a'+10; if (digit >= 'A' && digit <= 'F') return digit-'A'+10; if (digit >= '0' && digit <= '9') return digit-'0'; return 0; } //-------------------------------------- int UnicodeRefCharset::nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead) { unsigned char ch; UnicodeChar uniCh; bytesRead = 0; if (!is.getNext(ch)) return 0; bytesRead = 1; uniCh = ch; if (ch == '&') { if (is.peekNext(ch) && ch == '#') { is.getNext(ch); bytesRead++; if (!is.eos()) { is.peekNext(ch); if (ch != 'x' && ch != 'X') { UKWORD code = 0; int digits = 0; while (is.peekNext(ch) && isdigit(ch) && digits < 5) { is.getNext(ch); bytesRead++; code = code*10 + (ch - '0'); digits++; } if (is.peekNext(ch) && ch == ';') { is.getNext(ch); bytesRead++; uniCh = code; } } else { is.getNext(ch); bytesRead++; UKWORD code = 0; int digits = 0; while (is.peekNext(ch) && isxdigit(ch) && digits < 4) { is.getNext(ch); bytesRead++; code = (code << 4) + hexDigitValue(ch); digits++; } if (is.peekNext(ch) && ch == ';') { is.getNext(ch); bytesRead++; uniCh = code; } } // hex digits } } } // translate to StdVnChar UKDWORD key = uniCh; UKDWORD *pChar = (UKDWORD *)bsearch(&key, m_vnChars, TOTAL_VNCHARS, sizeof(UKDWORD), wideCharCompare); if (pChar) stdChar = VnStdCharOffset + HIWORD(*pChar); else stdChar = uniCh; return 1; } //-------------------------------- int UnicodeRefCharset::putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen) { UnicodeChar uChar = (stdChar < VnStdCharOffset)? (UnicodeChar)stdChar : m_toUnicode[stdChar-VnStdCharOffset]; int ret; if (uChar < 128) { outLen = 1; ret = os.putB((UKBYTE)uChar); } else { outLen = 2; os.putB((UKBYTE)'&'); os.putB((UKBYTE)'#'); int i, digit, prev, base; prev = 0; base = 10000; for (i=0; i < 5; i++) { digit = uChar / base; if (digit || prev) { prev = 1; outLen++; os.putB('0' + (unsigned char)digit); } uChar %= base; base /= 10; } ret = os.putB((UKBYTE)';'); outLen++; } return ret; } #define HEX_DIGIT(x) ((x < 10)? ('0'+x) : ('A'+x-10)) //-------------------------------- int UnicodeHexCharset::putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen) { UnicodeChar uChar = (stdChar < VnStdCharOffset)? (UnicodeChar)stdChar : m_toUnicode[stdChar-VnStdCharOffset]; int ret; if (uChar < 256) { outLen = 1; ret = os.putB((UKBYTE)uChar); } else { outLen = 3; os.putB('&'); os.putB('#'); os.putB('x'); int i, digit; int prev = 0; int shifts = 12; for (i=0; i < 4; i++) { digit = ((uChar >> shifts) & 0x000F); if (digit > 0 || prev) { prev = 1; outLen++; os.putB((UKBYTE)HEX_DIGIT(digit)); } shifts -= 4; } ret = os.putB(';'); outLen++; } return ret; } ///////////////////////////////// // Class UnicodeCStringCharset / ///////////////////////////////// void UnicodeCStringCharset::startInput() { m_prevIsHex = 0; } //---------------------------------------- int UnicodeCStringCharset::nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead) { unsigned char ch; UnicodeChar uniCh; bytesRead = 0; if (!is.getNext(ch)) return 0; bytesRead = 1; uniCh = ch; if (ch == '\\') { if (is.peekNext(ch) && (ch=='x' || ch=='X')) { is.getNext(ch); bytesRead++; UKWORD code = 0; int digits = 0; while (is.peekNext(ch) && isxdigit(ch) && digits < 4) { is.getNext(ch); bytesRead++; code = (code << 4) + hexDigitValue(ch); digits++; } uniCh = code; } } // translate to StdVnChar UKDWORD key = uniCh; UKDWORD *pChar = (UKDWORD *)bsearch(&key, m_vnChars, TOTAL_VNCHARS, sizeof(UKDWORD), wideCharCompare); if (pChar) stdChar = VnStdCharOffset + HIWORD(*pChar); else stdChar = uniCh; return 1; } //------------------------------------ int UnicodeCStringCharset::putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen) { UnicodeChar uChar = (stdChar < VnStdCharOffset)? (UnicodeChar)stdChar : m_toUnicode[stdChar-VnStdCharOffset]; int ret; if (uChar < 128 && !isxdigit(uChar) && uChar != 'x' && uChar != 'X') { outLen = 1; ret = os.putB((UKBYTE)uChar); } else { outLen = 2; os.putB('\\'); os.putB('x'); int i, digit; int prev = 0; int shifts = 12; for (i=0; i < 4; i++) { digit = ((uChar >> shifts) & 0x000F); if (digit > 0 || prev) { prev = 1; outLen++; os.putB((UKBYTE)HEX_DIGIT(digit)); } shifts -= 4; } ret = os.isOK(); m_prevIsHex = 1; } return ret; } ///////////////////////////////// // Double-byte charsets // ///////////////////////////////// DoubleByteCharset::DoubleByteCharset(UKWORD *vnChars) { m_toDoubleChar = vnChars; memset(m_stdMap, 0, 256*sizeof(UKWORD)); for (int i=0; i> 8) // a 2-byte character m_stdMap[vnChars[i] >> 8] = 0xFFFF; //INVALID_STD_CHAR; else if (m_stdMap[vnChars[i]] == 0) m_stdMap[vnChars[i]] = i+1; m_vnChars[i] = (i << 16) + vnChars[i]; // high word is used for StdChar index } qsort(m_vnChars, TOTAL_VNCHARS, sizeof(UKDWORD), wideCharCompare); } //--------------------------------------------- int DoubleByteCharset::nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead) { unsigned char ch; // read first byte bytesRead = 0; if (!is.getNext(ch)) return 0; bytesRead = 1; stdChar = m_stdMap[ch]; if (stdChar == 0) stdChar = ch; else if (stdChar == 0xFFFF) stdChar = INVALID_STD_CHAR; else { stdChar += VnStdCharOffset - 1; UKBYTE hi; if (is.peekNext(hi) && hi > 0) { //test if a double-byte character is encountered UKDWORD key = MAKEWORD(ch,hi); UKDWORD *pChar = (UKDWORD *)bsearch(&key, m_vnChars, TOTAL_VNCHARS, sizeof(UKDWORD), wideCharCompare); if (pChar) { stdChar = VnStdCharOffset + HIWORD(*pChar); bytesRead = 2; is.getNext(hi); } } } return 1; } //--------------------------------------------- int DoubleByteCharset::putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen) { int ret; if (stdChar >= VnStdCharOffset) { UKWORD wCh = m_toDoubleChar[stdChar-VnStdCharOffset]; if (wCh & 0xFF00) { outLen = 2; os.putB((UKBYTE)(wCh & 0x00FF)); ret = os.putB((UKBYTE)(wCh >> 8)); } else { unsigned char b = (unsigned char)wCh; if (m_stdMap[b] == 0xFFFF) b = PadChar; outLen = 1; ret = os.putB(b); } /* outLen = 1; ret = os.putB((UKBYTE)(wCh & 0x00FF)); if (wCh & 0xFF00) { outLen = 2; ret = os.putB((UKBYTE)(wCh >> 8)); } */ } else { if (stdChar > 255 || m_stdMap[stdChar]) { outLen = 1; ret = os.putB((UKBYTE)PadChar); } else { outLen = 1; ret = os.putB((UKBYTE)stdChar); } } return ret; } ///////////////////////////////////////////// // Class: VIQRCharset // ///////////////////////////////////////////// unsigned char VIQRTones[] = {'\'','`','?','~','.'}; const char *VIQREscapes[] = { "://", "/", "@", "mailto:", "email:", "news:", "www", "ftp" }; const int VIQREscCount = sizeof(VIQREscapes) / sizeof(char*); VIQRCharset::VIQRCharset(UKDWORD *vnChars) { memset(m_stdMap, 0, 256*sizeof(UKWORD)); int i; UKDWORD dw; m_vnChars = vnChars; for (i=0; i 0 && (!m_gotTone || (index!=6 && index!=10)) ) || (index == 12 && (upper == 'A' || upper == 'E' || upper == 'O')) || (m_stdMap[ch2] == 24 && upper== 'A') || (m_stdMap[ch2] == 26 && (upper == 'O' || upper == 'U')) ); if (cond) { if (index > 0) m_gotTone = 1; //we have a tone/breve/hook in the current word // ok, take this byte is.getNext(ch2); bytesRead++; int offset = m_stdMap[ch2]; if (offset == 26) offset = 24; if (offset == 24 && (ch1 == 'u' || ch1 == 'U')) offset = 12; stdChar += offset; // check next byte if (is.peekNext(ch2)) { if (index > 10 && m_stdMap[ch2] > 0 && m_stdMap[ch2] <= 10) { // ok, take one more byte is.getNext(ch2); bytesRead++; stdChar += m_stdMap[ch2]; } } } } } m_atWordBeginning = (stdChar < 256); if (stdChar < 256) { m_gotTone = 0; //reset this flag because we are at the beginning of a new word } // adjust stdChar if (stdChar >= 256) stdChar += VnStdCharOffset - 256; return 1; } //--------------------------------------------------- void VIQRCharset::startOutput() { m_escapeBowl = 0; m_escapeRoof = 0; m_escapeHook = 0; m_escapeTone = 0; m_noOutEsc = 0; VnCharsetLibObj.m_VIQROutEscPatterns.reset(); } //--------------------------------------------------- int VIQRCharset::putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen) { int ret; UKBYTE b; if (stdChar >= VnStdCharOffset) { outLen = 1; UKDWORD dw = m_vnChars[stdChar-VnStdCharOffset]; unsigned char first = (unsigned char)dw; unsigned char firstUpper = toupper(first); b = (UKBYTE)dw; ret = os.putB(b); if (VnCharsetLibObj.m_VIQROutEscPatterns.foundAtNextChar(b) != -1) m_noOutEsc = 1; if (m_noOutEsc && (b==' ' || b=='\t' || b=='\r' || b=='\n')) m_noOutEsc = 0; if (dw & 0x0000FF00) { // second byte is present unsigned char second = (UKBYTE)(dw >> 8); outLen++; ret = os.putB(second); if (dw & 0x00FF0000) { //third byte is present outLen++; ret = os.putB((UKBYTE)(dw >> 16)); m_escapeTone = 0; } else { UKWORD index = m_stdMap[second]; m_escapeTone = (index == 12 || index == 24 || index == 26); } VnCharsetLibObj.m_VIQROutEscPatterns.reset(); m_escapeBowl = 0; m_escapeHook = 0; m_escapeRoof = 0; } else { m_escapeTone = IS_VOWEL(first); m_escapeBowl = (firstUpper == 'A'); m_escapeHook = (firstUpper == 'U' || firstUpper == 'O'); m_escapeRoof = (firstUpper == 'A' || firstUpper == 'E' || firstUpper == 'O'); } } else { if (stdChar > 255) { outLen = 1; ret = os.putB((UKBYTE)PadChar); if (VnCharsetLibObj.m_VIQROutEscPatterns.foundAtNextChar((UKBYTE)PadChar) != -1) m_noOutEsc = 1; } else { outLen = 1; UKWORD index = m_stdMap[stdChar]; if (!VnCharsetLibObj.m_options.viqrMixed && !m_noOutEsc && (stdChar=='\\' || (index > 0 && index <= 10 && m_escapeTone) || (index == 12 && m_escapeRoof) || (index == 24 && m_escapeBowl) || (index == 26 && m_escapeHook))) { //(m_stdMap[stdChar] > 0 && m_stdMap[stdChar] <= 26)) { // tone mark, needs an escape character outLen++; ret = os.putB('\\'); if (VnCharsetLibObj.m_VIQROutEscPatterns.foundAtNextChar('\\') != -1) m_noOutEsc = 1; } b = (UKBYTE)stdChar; ret = os.putB(b); if (VnCharsetLibObj.m_VIQROutEscPatterns.foundAtNextChar(b) != -1) m_noOutEsc = 1; if (m_noOutEsc && (b==' ' || b=='\t' || b=='\r' || b=='\n')) m_noOutEsc = 0; } // reset escape marks m_escapeBowl = 0; m_escapeRoof = 0; m_escapeHook = 0; m_escapeTone = 0; } return ret; } ///////////////////////////////////////////// // Class: UTF8VIQRCharset // ///////////////////////////////////////////// //----------------------------------------- UTF8VIQRCharset::UTF8VIQRCharset(UnicodeUTF8Charset *pUtf, VIQRCharset *pViqr) { m_pUtf = pUtf; m_pViqr = pViqr; } //----------------------------------------- void UTF8VIQRCharset::startInput() { m_pUtf->startInput(); m_pViqr->startInput(); } //----------------------------------------- void UTF8VIQRCharset::startOutput() { m_pUtf->startOutput(); m_pViqr->startOutput(); } //----------------------------------------- int UTF8VIQRCharset::nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead) { UKBYTE ch; if (!is.peekNext(ch)) return 0; if (ch > 0xBF && ch < 0xFE) { m_pViqr->startInput(); // just to reset the VIQR object state m_pViqr->m_suspicious = 1; return m_pUtf->nextInput(is, stdChar, bytesRead); } return m_pViqr->nextInput(is, stdChar, bytesRead); } //----------------------------------------- int UTF8VIQRCharset::putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen) { return m_pViqr->putChar(os, stdChar, outLen); } //----------------------------------------- CVnCharsetLib::CVnCharsetLib() { unsigned char ch; for (ch = 'a'; ch < 'z'; ch++) LoVowel[ch-'a'] = 0; LoVowel['a'-'a'] = 1; LoVowel['e'-'a'] = 1; LoVowel['i'-'a'] = 1; LoVowel['o'-'a'] = 1; LoVowel['u'-'a'] = 1; LoVowel['y'-'a'] = 1; for (ch = 'A'; ch < 'Z'; ch++) HiVowel[ch-'A'] = 0; HiVowel['A'-'A'] = 1; HiVowel['E'-'A'] = 1; HiVowel['I'-'A'] = 1; HiVowel['O'-'A'] = 1; HiVowel['U'-'A'] = 1; HiVowel['Y'-'A'] = 1; m_pUniCharset = NULL; m_pUniCompCharset = NULL; m_pUniUTF8 = NULL; m_pUniRef = NULL; m_pUniHex = NULL; m_pVIQRCharObj = NULL; m_pUVIQRCharObj = NULL; m_pWinCP1258 = NULL; m_pVnIntCharset = NULL; int i; for (i = 0; i < CONV_TOTAL_SINGLE_CHARSETS; i++) m_sgCharsets[i] = NULL; for (i = 0; i < CONV_TOTAL_DOUBLE_CHARSETS; i++) m_dbCharsets[i] = NULL; VnConvResetOptions(&m_options); m_VIQREscPatterns.init((char**)VIQREscapes, VIQREscCount); m_VIQROutEscPatterns.init((char**)VIQREscapes, VIQREscCount); } //----------------------------------------- CVnCharsetLib::~CVnCharsetLib() { if (m_pUniCharset) delete m_pUniCharset; if (m_pUniUTF8) delete m_pUniUTF8; if (m_pUniRef) delete m_pUniRef; if (m_pUniHex) delete m_pUniHex; if (m_pVIQRCharObj) delete m_pVIQRCharObj; if (m_pUVIQRCharObj) delete m_pUVIQRCharObj; if (m_pWinCP1258) delete m_pWinCP1258; if (m_pUniCString) delete m_pUniCString; if (m_pVnIntCharset) delete m_pVnIntCharset; int i; for (i = 0; i < CONV_TOTAL_SINGLE_CHARSETS; i++) if (m_sgCharsets[i]) delete m_sgCharsets[i]; for (i = 0; i < CONV_TOTAL_DOUBLE_CHARSETS; i++) if (m_dbCharsets[i]) delete m_dbCharsets[i]; } //----------------------------------------- VnCharset * CVnCharsetLib::getVnCharset(int charsetIdx) { switch (charsetIdx) { case CONV_CHARSET_UNICODE: if (m_pUniCharset == NULL) m_pUniCharset = new UnicodeCharset(UnicodeTable); return m_pUniCharset; case CONV_CHARSET_UNIDECOMPOSED: if (m_pUniCompCharset == NULL) m_pUniCompCharset = new UnicodeCompCharset(UnicodeTable, UnicodeComposite); return m_pUniCompCharset; case CONV_CHARSET_UNIUTF8: case CONV_CHARSET_XUTF8: if (m_pUniUTF8 == NULL) m_pUniUTF8 = new UnicodeUTF8Charset(UnicodeTable); return m_pUniUTF8; case CONV_CHARSET_UNIREF: if (m_pUniRef == NULL) m_pUniRef = new UnicodeRefCharset(UnicodeTable); return m_pUniRef; case CONV_CHARSET_UNIREF_HEX: if (m_pUniHex == NULL) m_pUniHex = new UnicodeHexCharset(UnicodeTable); return m_pUniHex; case CONV_CHARSET_UNI_CSTRING: if (m_pUniCString == NULL) m_pUniCString = new UnicodeCStringCharset(UnicodeTable); return m_pUniCString; case CONV_CHARSET_WINCP1258: if (m_pWinCP1258 == NULL) m_pWinCP1258 = new WinCP1258Charset(WinCP1258, WinCP1258Pre); return m_pWinCP1258; case CONV_CHARSET_VIQR: if (m_pVIQRCharObj == NULL) m_pVIQRCharObj = new VIQRCharset(VIQRTable); return m_pVIQRCharObj; case CONV_CHARSET_VNSTANDARD: if (m_pVnIntCharset == NULL) m_pVnIntCharset = new VnInternalCharset(); return m_pVnIntCharset; case CONV_CHARSET_UTF8VIQR: if (m_pUVIQRCharObj == NULL) { if (m_pVIQRCharObj == NULL) m_pVIQRCharObj = new VIQRCharset(VIQRTable); if (m_pUniUTF8 == NULL) m_pUniUTF8 = new UnicodeUTF8Charset(UnicodeTable); m_pUVIQRCharObj = new UTF8VIQRCharset(m_pUniUTF8, m_pVIQRCharObj); } return m_pUVIQRCharObj; default: if (IS_SINGLE_BYTE_CHARSET(charsetIdx)) { int i = charsetIdx - CONV_CHARSET_TCVN3; if (m_sgCharsets[i] == NULL) m_sgCharsets[i] = new SingleByteCharset(SingleByteTables[i]); return m_sgCharsets[i]; } else if (IS_DOUBLE_BYTE_CHARSET(charsetIdx)) { int i = charsetIdx - CONV_CHARSET_VNIWIN; if (m_dbCharsets[i] == NULL) m_dbCharsets[i] = new DoubleByteCharset(DoubleByteTables[i]); return m_dbCharsets[i]; } } return NULL; } //------------------------------------------------- DllExport void VnConvSetOptions(VnConvOptions *pOptions) { VnCharsetLibObj.m_options = *pOptions; } //------------------------------------------------- DllExport void VnConvGetOptions(VnConvOptions *pOptions) { *pOptions = VnCharsetLibObj.m_options; } //------------------------------------------------- DllExport void VnConvResetOptions(VnConvOptions *pOptions) { pOptions->viqrEsc = 1; pOptions->viqrMixed = 0; pOptions->toUpper = 0; pOptions->toLower = 0; pOptions->removeTone = 0; pOptions->smartViqr = 1; } ///////////////////////////////////////////// // Class WinCP1258Charset ///////////////////////////////////////////// WinCP1258Charset::WinCP1258Charset(UKWORD *compositeChars, UKWORD *precomposedChars) { int i,k; m_toDoubleChar = compositeChars; memset(m_stdMap, 0, 256*sizeof(UKWORD)); // encode composite chars for (i=0; i> 8) // a 2-byte character m_stdMap[compositeChars[i] >> 8] = 0xFFFF; //INVALID_STD_CHAR; else if (m_stdMap[compositeChars[i]] == 0) m_stdMap[compositeChars[i]] = i+1; m_vnChars[i] = (i << 16) + compositeChars[i]; // high word is used for StdChar index } m_totalChars = TOTAL_VNCHARS; //add precomposed chars to the table for (k=0, i=TOTAL_VNCHARS; k> 8) // a 2-byte character m_stdMap[precomposedChars[k] >> 8] = 0xFFFF; //INVALID_STD_CHAR; else if (m_stdMap[precomposedChars[k]] == 0) m_stdMap[precomposedChars[k]] = k+1; m_vnChars[i] = (k << 16) + precomposedChars[k]; m_totalChars++; i++; } qsort(m_vnChars, m_totalChars, sizeof(UKDWORD), wideCharCompare); } //--------------------------------------------------------------------- // This fuction is basically the same as that of DoubleByteCharset // with m_totalChars is used instead of constant TOTAL_VNCHARS //--------------------------------------------------------------------- int WinCP1258Charset::nextInput(ByteInStream & is, StdVnChar & stdChar, int & bytesRead) { unsigned char ch; // read first byte bytesRead = 0; if (!is.getNext(ch)) return 0; bytesRead = 1; stdChar = m_stdMap[ch]; if (stdChar == 0) stdChar = ch; else if (stdChar == 0xFFFF) stdChar = INVALID_STD_CHAR; else { stdChar += VnStdCharOffset - 1; UKBYTE hi; if (is.peekNext(hi) && hi > 0) { //test if a double-byte character is encountered UKDWORD key = MAKEWORD(ch,hi); UKDWORD *pChar = (UKDWORD *)bsearch(&key, m_vnChars, m_totalChars, sizeof(UKDWORD), wideCharCompare); if (pChar) { stdChar = VnStdCharOffset + HIWORD(*pChar); bytesRead = 2; is.getNext(hi); } } } return 1; } //--------------------------------------------------------------------- // This fuction is exactly the same as that of DoubleByteCharset //--------------------------------------------------------------------- int WinCP1258Charset::putChar(ByteOutStream & os, StdVnChar stdChar, int & outLen) { int ret; if (stdChar >= VnStdCharOffset) { UKWORD wCh = m_toDoubleChar[stdChar-VnStdCharOffset]; if (wCh & 0xFF00) { outLen = 2; os.putB((UKBYTE)(wCh & 0x00FF)); ret = os.putB((UKBYTE)(wCh >> 8)); } else { unsigned char b = (unsigned char)wCh; if (m_stdMap[b] == 0xFFFF) b = PadChar; outLen = 1; ret = os.putB(b); } } else { if (stdChar > 255 || m_stdMap[stdChar]) { outLen = 1; ret = os.putB((UKBYTE)PadChar); } else { outLen = 1; ret = os.putB((UKBYTE)stdChar); } } return ret; } #define IS_ODD(x) (x & 1) #define IS_EVEN(x) (!(x & 1)) StdVnChar StdVnToUpper(StdVnChar ch) { if (ch >= VnStdCharOffset && ch<(VnStdCharOffset + TOTAL_ALPHA_VNCHARS) && IS_ODD(ch)) ch -= 1; return ch; } //---------------------------------------- StdVnChar StdVnToLower(StdVnChar ch) { if (ch >= VnStdCharOffset && ch<(VnStdCharOffset + TOTAL_ALPHA_VNCHARS) && IS_EVEN(ch)) ch += 1; return ch; } //---------------------------------------- StdVnChar StdVnGetRoot(StdVnChar ch) { if (ch >= VnStdCharOffset && ch a 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, //a( -> a 36, 37, 38, 39, 40, 41, // bcd [D=40, d=41] 40, 41, // DD dd [mapped to D, d] 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, // 3: e [E = 44] 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, // 4: e^ -> e 68, 69, 70, 71, 72, 73, // fgh 74, 75, 74, 75, 74, 75, 74, 75, 74, 75, 74, 75, // 5: i 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, //jklmn 96, 97, 96, 97, 96, 97, 96, 97, 96, 97, 96, 97, // 6: o [o=96] 96, 97, 96, 97, 96, 97, 96, 97, 96, 97, 96, 97, // 7: o^ -> o 96, 97, 96, 97, 96, 97, 96, 97, 96, 97, 96, 97, // 8: o+ -> o 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, // pqrst 142, 143, 142, 143, 142, 143, 142, 143, 142, 143, 142, 143, // 9: u [U=142] 142, 143, 142, 143, 142, 143, 142, 143, 142, 143, 142, 143, //10: u+ -> u 166, 167, 168, 169, 170, 171, //vwx 172, 173, 172, 173, 172, 173, 172, 173, 172, 173, 172, 173, //11: y [Y=172] 184, 185, // z 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212 }; int StdVnNoTone[TOTAL_VNCHARS] = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, //a [A=0] 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, //a^ 24, 25, 24, 25, 24, 25, 24, 25, 24, 25, 24, 25, //a( 36, 37, 38, 39, 40, 41, // bcd [D=40, d=41] 42, 43, // DD dd 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, 44, 45, // 3: e [E = 44] 56, 57, 56, 57, 56, 57, 56, 57, 56, 57, 56, 57, // 4: e^ 68, 69, 70, 71, 72, 73, // fgh 74, 75, 74, 75, 74, 75, 74, 75, 74, 75, 74, 75, // 5: i 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, //jklmn 96, 97, 96, 97, 96, 97, 96, 97, 96, 97, 96, 97, // 6: o [o=96] 108, 109, 108, 109, 108, 109, 108, 109, 108, 109, 108, 109, // 7: o^ 120, 121, 120, 121, 120, 121, 120, 121, 120, 121, 120, 121, // 8: o+ 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, // pqrst 142, 143, 142, 143, 142, 143, 142, 143, 142, 143, 142, 143, // 9: u [U=142] 154, 155, 154, 155, 154, 155, 154, 155, 154, 155, 154, 155, //10: u+ 166, 167, 168, 169, 170, 171, //vwx 172, 173, 172, 173, 172, 173, 172, 173, 172, 173, 172, 173, //11: y [Y=172] 184, 185, // z 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212 }; ibus-unikey-0.7.0~beta1/ukengine/pattern.h0000664000175000017500000000362713441506611020111 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /*------------------------------------------------------------------------------ VnConv: Vietnamese Encoding Converter Library UniKey Project: http://unikey.sourceforge.net Copyleft (C) 1998-2002 Pham Kim Long Contact: longp@cslab.felk.cvut.cz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --------------------------------------------------------------------------------*/ #ifndef __PATTERN_H #define __PATTERN_H #if defined(_WIN32) #if defined(UNIKEYHOOK) #define DllInterface __declspec( dllexport ) #else #define DllInterface __declspec( dllimport ) #endif #else #define DllInterface //not used #endif #define MAX_PATTERN_LEN 40 class DllInterface PatternState { public: char *m_pattern; int m_border[MAX_PATTERN_LEN+1]; int m_pos; int m_found; void init(char *pattern); void reset(); int foundAtNextChar(char ch); //get next input char, returns 1 if pattern is found. }; class DllInterface PatternList { public: PatternState *m_patterns; int m_count; void init(char **patterns, int count); int foundAtNextChar(char ch); void reset(); PatternList() { m_count = 0; m_patterns = 0; } ~PatternList() { if (m_patterns) delete [] m_patterns; } }; #endif ibus-unikey-0.7.0~beta1/ukengine/byteio.h0000664000175000017500000000754713441506611017734 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- #ifndef BYTE_IO_STREAM_H #define BYTE_IO_STREAM_H //#include "vnconv.h" #include typedef unsigned char UKBYTE; typedef unsigned short UKWORD; typedef unsigned int UKDWORD; //---------------------------------------------------- class ByteStream { public: virtual ~ByteStream(){}; }; //---------------------------------------------------- class ByteInStream: public ByteStream { public: virtual int getNext(UKBYTE &b) = 0; virtual int peekNext(UKBYTE &b) = 0; virtual int unget(UKBYTE b) = 0; virtual int getNextW(UKWORD &w) = 0; virtual int peekNextW(UKWORD &w) = 0; virtual int getNextDW(UKDWORD &dw) = 0; virtual int bookmark() //no support for bookmark by default { return 0; } virtual int gotoBookmark() { return 0; } virtual int eos() = 0; //end of stream virtual int close() = 0; }; //---------------------------------------------------- class ByteOutStream: public ByteStream { public: virtual int putB(UKBYTE b) = 0; virtual int putW(UKWORD w) = 0; virtual int puts(const char *s, int size = -1) = 0; // write an 8-bit string virtual int isOK() = 0;// get current stream state }; //---------------------------------------------------- class StringBIStream : public ByteInStream { protected: int m_eos; UKBYTE *m_data, *m_current; int m_len, m_left; struct { int eos; UKBYTE *data, *current; int len, left; } m_bookmark; int m_didBookmark; public: StringBIStream(UKBYTE *data, int len, int elementSize = 1); virtual int getNext(UKBYTE &b); virtual int peekNext(UKBYTE &b); virtual int unget(UKBYTE b); virtual int getNextW(UKWORD &w); virtual int peekNextW(UKWORD &w); virtual int getNextDW(UKDWORD &dw); virtual int eos(); //end of stream virtual int close(); virtual int bookmark(); virtual int gotoBookmark(); void reopen(); int left() { return m_left; } }; //---------------------------------------------------- class FileBIStream : public ByteInStream { protected: FILE *m_file; int m_bufSize; char *m_buf; int m_own; int m_didBookmark; struct { long pos; } m_bookmark; //some systems don't have wide char IO functions //we have to use this variables to implement that UKBYTE m_readByte; int m_readAhead; int m_lastIsAhead; public: FileBIStream(int bufsize = 8192, char *buf = NULL); // FileBIStream(char *fileName, int bufsize = 8192, void *buf = NULL); int open(const char *fileName); void attach(FILE *f); virtual int close(); virtual int getNext(UKBYTE &b); virtual int peekNext(UKBYTE &b); virtual int unget(UKBYTE b); virtual int getNextW(UKWORD &w); virtual int peekNextW(UKWORD &w); virtual int getNextDW(UKDWORD &dw); virtual int eos(); //end of stream virtual int bookmark(); virtual int gotoBookmark(); virtual ~FileBIStream(); }; //---------------------------------------------------- class StringBOStream : public ByteOutStream { protected: UKBYTE *m_buf, *m_current; int m_out; int m_len; int m_bad; public: StringBOStream(UKBYTE *buf, int len); virtual int putB(UKBYTE b); virtual int putW(UKWORD w); virtual int puts(const char *s, int size = -1); virtual int isOK(); // get current stream state virtual int close() { return 1; }; void reopen(); int getOutBytes() { return m_out; } }; //---------------------------------------------------- class FileBOStream : public ByteOutStream { protected: FILE *m_file; int m_bufSize; char *m_buf; int m_own; int m_bad; public: FileBOStream(int bufsize = 8192, char *buf = NULL); // FileBOStream(char *fileName, int bufsize = 8192, void *buf = NULL); int open(const char *fileName); void attach(FILE *); virtual int close(); virtual int putB(UKBYTE b); virtual int putW(UKWORD w); virtual int puts(const char *s, int size = -1); virtual int isOK(); // get current stream state virtual ~FileBOStream(); }; #endif ibus-unikey-0.7.0~beta1/ukengine/vnconv.h0000664000175000017500000000677413441506611017753 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /*------------------------------------------------------------------------------ VnConv: Vietnamese Encoding Converter Library UniKey Project: http://unikey.sourceforge.net Copyleft (C) 1998-2002 Pham Kim Long Contact: longp@cslab.felk.cvut.cz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --------------------------------------------------------------------------------*/ // #ifndef __VN_CONVERT_H #define __VN_CONVERT_H #if defined(_WIN32) #if defined(UNIKEYHOOK) #define DllInterface __declspec( dllexport ) #else #define DllInterface __declspec( dllimport ) #endif #define DllExport __declspec( dllexport ) #define DllImport __declspec( dllimport ) #else #define DllInterface //not used #define DllExport #define DllImport #endif #define CONV_CHARSET_UNICODE 0 #define CONV_CHARSET_UNIUTF8 1 #define CONV_CHARSET_UNIREF 2 //&#D; #define CONV_CHARSET_UNIREF_HEX 3 #define CONV_CHARSET_UNIDECOMPOSED 4 #define CONV_CHARSET_WINCP1258 5 #define CONV_CHARSET_UNI_CSTRING 6 #define CONV_CHARSET_VNSTANDARD 7 #define CONV_CHARSET_VIQR 10 #define CONV_CHARSET_UTF8VIQR 11 #define CONV_CHARSET_XUTF8 12 #define CONV_CHARSET_TCVN3 20 #define CONV_CHARSET_VPS 21 #define CONV_CHARSET_VISCII 22 #define CONV_CHARSET_BKHCM1 23 #define CONV_CHARSET_VIETWAREF 24 #define CONV_CHARSET_ISC 25 #define CONV_CHARSET_VNIWIN 40 #define CONV_CHARSET_BKHCM2 41 #define CONV_CHARSET_VIETWAREX 42 #define CONV_CHARSET_VNIMAC 43 #define CONV_TOTAL_SINGLE_CHARSETS 6 #define CONV_TOTAL_DOUBLE_CHARSETS 4 #define IS_SINGLE_BYTE_CHARSET(x) (x >= CONV_CHARSET_TCVN3 && x < CONV_CHARSET_TCVN3+CONV_TOTAL_SINGLE_CHARSETS) #define IS_DOUBLE_BYTE_CHARSET(x) (x >= CONV_CHARSET_VNIWIN && x < CONV_CHARSET_VNIWIN+CONV_TOTAL_DOUBLE_CHARSETS) typedef unsigned char UKBYTE; #if defined(__cplusplus) extern "C" { #endif DllInterface int VnConvert(int inCharset, int outCharset, UKBYTE *input, UKBYTE *output, int * pInLen, int * pMaxOutLen); DllInterface int VnFileConvert(int inCharset, int outCharset, const char *inFile, const char *outFile); #if defined(__cplusplus) } #endif DllInterface const char * VnConvErrMsg(int errCode); enum VnConvError { VNCONV_NO_ERROR, VNCONV_UNKNOWN_ERROR, VNCONV_INVALID_CHARSET, VNCONV_ERR_INPUT_FILE, VNCONV_ERR_OUTPUT_FILE, VNCONV_OUT_OF_MEMORY, VNCONV_ERR_WRITING, VNCONV_LAST_ERROR }; typedef struct _CharsetNameId CharsetNameId; struct _CharsetNameId { const char *name; int id; }; typedef struct _VnConvOptions VnConvOptions; struct _VnConvOptions { int viqrMixed; int viqrEsc; int toUpper; int toLower; int removeTone; int smartViqr; }; DllInterface void VnConvSetOptions(VnConvOptions *pOptions); DllInterface void VnConvGetOptions(VnConvOptions *pOptions); DllInterface void VnConvResetOptions(VnConvOptions *pOptions); #endif ibus-unikey-0.7.0~beta1/ukengine/unikey.cpp0000664000175000017500000001302613441506611020265 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /*------------------------------------------------------------------------------ UniKey - Open-source Vietnamese Keyboard Copyright (C) 1998-2004 Pham Kim Long Contact: longcz@yahoo.com http://unikey.sf.net This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --------------------------------------------------------------------------------*/ #include #include #include #include #include "unikey.h" #include "ukengine.h" #include "usrkeymap.h" using namespace std; //---- exported variables for use in UkEnginge class ---- UkSharedMem *pShMem = 0; UkEngine MyKbEngine; int UnikeyCapsLockOn = 0; int UnikeyShiftPressed = 0; //---------------------------------------------------- unsigned char UnikeyBuf[1024]; int UnikeyBackspaces; int UnikeyBufChars; UkOutputType UnikeyOutput; //-------------------------------------------- void UnikeySetInputMethod(UkInputMethod im) { if (im == UkTelex || im == UkVni || im == UkSimpleTelex || im == UkSimpleTelex2) { pShMem->input.setIM(im); MyKbEngine.reset(); } else if (im == UkUsrIM && pShMem->usrKeyMapLoaded) { //cout << "Switched to user mode\n"; //DEBUG pShMem->input.setIM(pShMem->usrKeyMap); MyKbEngine.reset(); } //cout << "IM changed to: " << im << endl; //DEBUG } //-------------------------------------------- void UnikeySetCapsState(int shiftPressed, int CapsLockOn) { //UnikeyCapsAll = (shiftPressed && !CapsLockOn) || (!shiftPressed && CapsLockOn); UnikeyCapsLockOn = CapsLockOn; UnikeyShiftPressed = shiftPressed; } //-------------------------------------------- int UnikeySetOutputCharset(int charset) { pShMem->charsetId = charset; MyKbEngine.reset(); return 1; } //-------------------------------------------- void UnikeySetOptions(UnikeyOptions *pOpt) { pShMem->options.freeMarking = pOpt->freeMarking; pShMem->options.modernStyle = pOpt->modernStyle; pShMem->options.macroEnabled = pOpt->macroEnabled; pShMem->options.useUnicodeClipboard = pOpt->useUnicodeClipboard; pShMem->options.alwaysMacro = pOpt->alwaysMacro; pShMem->options.spellCheckEnabled = pOpt->spellCheckEnabled; pShMem->options.autoNonVnRestore = pOpt->autoNonVnRestore; } //-------------------------------------------- void UnikeyGetOptions(UnikeyOptions *pOpt) { *pOpt = pShMem->options; } //-------------------------------------------- void CreateDefaultUnikeyOptions(UnikeyOptions *pOpt) { pOpt->freeMarking = 1; pOpt->modernStyle = 0; pOpt->macroEnabled = 0; pOpt->useUnicodeClipboard = 0; pOpt->alwaysMacro = 0; pOpt->spellCheckEnabled = 1; pOpt->autoNonVnRestore = 0; } //-------------------------------------------- void UnikeyCheckKbCase(int *pShiftPressed, int *pCapsLockOn) { *pShiftPressed = UnikeyShiftPressed; *pCapsLockOn = UnikeyCapsLockOn; } //-------------------------------------------- void UnikeySetup() { SetupUnikeyEngine(); pShMem = new UkSharedMem; pShMem->input.init(); pShMem->macStore.init(); pShMem->vietKey = 1; pShMem->usrKeyMapLoaded = 0; MyKbEngine.setCtrlInfo(pShMem); MyKbEngine.setCheckKbCaseFunc(&UnikeyCheckKbCase); UnikeySetInputMethod(UkTelex); UnikeySetOutputCharset(CONV_CHARSET_XUTF8); pShMem->initialized = 1; CreateDefaultUnikeyOptions(&pShMem->options); } //-------------------------------------------- void UnikeyCleanup() { delete pShMem; } //-------------------------------------------- void UnikeyFilter(unsigned int ch) { UnikeyBufChars = sizeof(UnikeyBuf); MyKbEngine.process(ch, UnikeyBackspaces, UnikeyBuf, UnikeyBufChars, UnikeyOutput); } //-------------------------------------------- void UnikeyPutChar(unsigned int ch) { MyKbEngine.pass(ch); UnikeyBufChars = 0; UnikeyBackspaces = 0; } //-------------------------------------------- void UnikeyResetBuf() { MyKbEngine.reset(); } //-------------------------------------------- void UnikeySetSingleMode() { MyKbEngine.setSingleMode(); } //-------------------------------------------- void UnikeyBackspacePress() { UnikeyBufChars = sizeof(UnikeyBuf); MyKbEngine.processBackspace(UnikeyBackspaces, UnikeyBuf, UnikeyBufChars, UnikeyOutput); // printf("Backspaces: %d\n",UnikeyBackspaces); } //-------------------------------------------- int UnikeyLoadMacroTable(const char *fileName) { return pShMem->macStore.loadFromFile(fileName); } //-------------------------------------------- int UnikeyLoadUserKeyMap(const char *fileName) { if (UkLoadKeyMap(fileName, pShMem->usrKeyMap)) { //cout << "User key map loaded!\n"; //DEBUG pShMem->usrKeyMapLoaded = 1; return 1; } return 0; } //-------------------------------------------- void UnikeyRestoreKeyStrokes() { UnikeyBufChars = sizeof(UnikeyBuf); MyKbEngine.restoreKeyStrokes(UnikeyBackspaces, UnikeyBuf, UnikeyBufChars, UnikeyOutput); } bool UnikeyAtWordBeginning() { return MyKbEngine.atWordBeginning(); } ibus-unikey-0.7.0~beta1/ukengine/README0000664000175000017500000000020113441506611017124 0ustar gunnargunnarThis folder contains ukengine (with changes for better use in my project) taking from project x-unikey (http://www.unikey.org). ibus-unikey-0.7.0~beta1/ukengine/error.cpp0000664000175000017500000000317613441506611020117 0ustar gunnargunnar// -*- coding:unix; mode:c++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- /*------------------------------------------------------------------------------ VnConv: Vietnamese Encoding Converter Library UniKey Project: http://unikey.sourceforge.net Copyleft (C) 1998-2002 Pham Kim Long Contact: longp@cslab.felk.cvut.cz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --------------------------------------------------------------------------------*/ // For some unknown reasons, the functions in this file cannot be exported // We had to move them to convert.cpp. // TODO: inspect this problem later! /* #include "stdafx.h" #include "vnconv.h" char *ErrTable[VNCONV_LAST_ERROR] = {"No error", "Unknown error", "Invalid charset", "Error opening input file", "Error opening output file", "Error writing to output stream", "Not enough memory", }; DllExport const char * VnConvErrMsg(int errCode) { if (errCode < 0 || errCode >= VNCONV_LAST_ERROR) errCode = VNCONV_UNKNOWN_ERROR; return ErrTable[errCode]; } */