Add src
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- src/README.rstAdded+6
- src/hwp5/COPYINGAdded+661
- src/hwp5/READMEAdded+73
- src/hwp5/VERSION.txtAdded+1
- src/hwp5/__init__.pyAdded+26
- src/hwp5/binmodel/__init__.pyAdded+549
- src/hwp5/binmodel/_shared.pyAdded+265
- src/hwp5/binmodel/controlchar.pyAdded+215
- src/hwp5/binmodel/controls/__init__.pyAdded+94
- src/hwp5/binmodel/controls/_shared.pyAdded+59
- src/hwp5/binmodel/controls/bookmark_control.pyAdded+50
- src/hwp5/binmodel/controls/columns_def.pyAdded+84
- src/hwp5/binmodel/controls/common_controls.pyAdded+81
- src/hwp5/binmodel/controls/dutmal.pyAdded+48
- src/hwp5/binmodel/controls/field.pyAdded+185
- src/hwp5/binmodel/controls/gshape_object_control.pyAdded+28
- src/hwp5/binmodel/controls/header_footer.pyAdded+48
- src/hwp5/binmodel/controls/hidden_comment.pyAdded+34
- src/hwp5/binmodel/controls/index_marker.pyAdded+37
- src/hwp5/binmodel/controls/note.pyAdded+47
- src/hwp5/binmodel/controls/numbering.pyAdded+69
- src/hwp5/binmodel/controls/page_hide.pyAdded+42
- src/hwp5/binmodel/controls/page_number_position.pyAdded+49
- src/hwp5/binmodel/controls/page_odd_even.pyAdded+39
- src/hwp5/binmodel/controls/section_def.pyAdded+73
- src/hwp5/binmodel/controls/table_control.pyAdded+36
- src/hwp5/binmodel/controls/tcps_control.pyAdded+38
- src/hwp5/binmodel/tagid16_document_properties.pyAdded+47
- src/hwp5/binmodel/tagid17_id_mappings.pyAdded+60
- src/hwp5/binmodel/tagid18_bin_data.pyAdded+77
- src/hwp5/binmodel/tagid19_face_name.pyAdded+136
- src/hwp5/binmodel/tagid20_border_fill.pyAdded+89
- src/hwp5/binmodel/tagid21_char_shape.pyAdded+90
- src/hwp5/binmodel/tagid22_tab_def.pyAdded+60
- src/hwp5/binmodel/tagid23_numbering.pyAdded+72
- src/hwp5/binmodel/tagid24_bullet.pyAdded+52
- src/hwp5/binmodel/tagid25_para_shape.pyAdded+97
- src/hwp5/binmodel/tagid26_style.pyAdded+55
- src/hwp5/binmodel/tagid27_doc_data.pyAdded+31
- src/hwp5/binmodel/tagid28_distribute_doc_data.pyAdded+29
- src/hwp5/binmodel/tagid30_compatible_document.pyAdded+42
- src/hwp5/binmodel/tagid31_layout_compatibility.pyAdded+39
- src/hwp5/binmodel/tagid32_unknown.pyAdded+29
- src/hwp5/binmodel/tagid50_para_header.pyAdded+61
- src/hwp5/binmodel/tagid51_para_text.pyAdded+61
- src/hwp5/binmodel/tagid52_para_char_shape.pyAdded+64
- src/hwp5/binmodel/tagid53_para_line_seg.pyAdded+95
- src/hwp5/binmodel/tagid54_para_range_tag.pyAdded+54
- src/hwp5/binmodel/tagid55_ctrl_header.pyAdded+44
- src/hwp5/binmodel/tagid56_list_header.pyAdded+157
123456``pyhwp/`` - the main source code---------------------------------
``hwp5/`` The main source package. For now, there is not much documentation about the source code.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license forsoftware and other kinds of works, specifically designed to ensurecooperation with the community in the case of network server software.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,our General Public Licenses are intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rightswith two steps: (1) assert copyright on the software, and (2) offeryou this License which gives you legal permission to copy, distributeand/or modify the software.
A secondary benefit of defending all users' freedom is thatimprovements made in alternate versions of the program, if theyreceive widespread use, become available for other developers toincorporate. Many developers of free software are heartened andencouraged by the resulting cooperation. However, in the case ofsoftware used on network servers, this result may fail to come about.The GNU General Public License permits making a modified version andletting the public access it on a server without ever releasing itssource code to the public.
The GNU Affero General Public License is designed specifically toensure that, in such cases, the modified source code becomes availableto the community. It requires the operator of a network server toprovide the source code of the modified version running there to theusers of that server. Therefore, public use of a modified version, ona publicly accessible server, gives the public access to the sourcecode of the modified version.
An older license, called the Affero General Public License andpublished by Affero, was designed to accomplish similar goals. This isa different license, not a version of the Affero GPL, but Affero hasreleased a new version of the Affero GPL which permits relicensing underthis license.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. 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 workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha 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 visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation 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 toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients 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 toproduce it from the Program, in the form of source code under theterms 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 independentworks, 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 notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-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 excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe 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 installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional 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 youadd to a covered work, you may (if authorized by the copyright holders ofthat 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 "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform 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 expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered 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 automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent 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 anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain 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 limitingany implied license or other defenses to infringement that mayotherwise 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 orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify theProgram, your modified version must prominently offer all usersinteracting with it remotely through a computer network (if your versionsupports such interaction) an opportunity to receive the CorrespondingSource of your version by providing access to the Corresponding Sourcefrom a network server at no charge, through some standard or customarymeans of facilitating copying of software. This Corresponding Sourceshall include the Corresponding Source for any work covered by version 3of the GNU General Public License that is incorporated pursuant to thefollowing paragraph.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the work with which it is combined will remain governed by version3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU Affero General Public License from time to time. Such new versionswill be similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU Affero GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU Affero General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU Affero General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES 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 OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy 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 greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computernetwork, you should also make sure that it provides a way for users toget its source. For example, if your program is a web application, itsinterface could display a "Source" link that leads users to an archiveof the code. There are many ways you could offer source, and differentsolutions will be better for different programs; see section 13 for thespecific requirements.
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 AGPL, see<http://www.gnu.org/licenses/>.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273pyhwp=====
HWP Document Format v5 parser & processor.
Features--------
- Analyze and extract internal streams out from a HWP Document Format v5 file- (*Experimental*) Conversion to OpenDocument format (.odt) or plain text (.txt)
Installation------------
from `pypi <http://pypi.org/project/pyhwp>`_::
virtualenv pyhwp pyhwp/bin/pip install --pre pyhwp # Install pyhwp into a virtualenv directory
Or::
pip install --user --pre pyhwp # Install pyhwp into user's home directory
Requirements------------
- Python 2.7, 3.5, 3.6, 3.7 or 3.8- `cryptography <https://pypi.org/project/cryptography>`_- `lxml <https://pypi.org/project/lxml>`_- `olefile <https://pypi.org/project/olefile>`_
Documentation & Development---------------------------
- Documentation: `https://pyhwp.readthedocs.io <https://pyhwp.readthedocs.io>`_ [`한국/조선어 <https://pyhwp.readthedocs.io/ko/latest>`_]- Distribution: `https://pypi.org/project/pyhwp/ <https://pypi.org/project/pyhwp/>`_- Development: `https://github.com/mete0r/pyhwp <https://github.com/mete0r/pyhwp>`_- Issue tracker: `https://github.com/mete0r/pyhwp/issues <https://github.com/mete0r/pyhwp/issues>`_- Feedbacks & contributions are welcome!
Contributors------------
Maintainer: `mete0r <https://github.com/mete0r>`_
License-------
Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>
.. image:: http://www.gnu.org/graphics/agplv3-155x51.png
`GNU Affero General Public License v3.0 <http://www.gnu.org/licenses/agpl-3.0.html>`_`(text version) <http://www.gnu.org/licenses/agpl-3.0.txt>`_
This program is free software: you can redistribute it and/or modifyit under the terms of the GNU Affero General Public License as published bythe 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 ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.
Disclosure----------
This program has been developed in accordance with a public document named "HWPBinary Specification 1.1" published by `Hancom Inc. <http://www.hancom.co.kr>`_11.0.21234567891011121314151617181920212223242526# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.from __future__ import with_statementimport os.path
try: with open(os.path.join(os.path.dirname(__file__), 'VERSION.txt')) as f: __version__ = f.read().strip() del fexcept Exception: __version__ = '0.0-unknown'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literalsfrom io import BytesIOfrom itertools import takewhileimport jsonimport loggingimport inspect
from .. import recordstreamfrom ..bintype import ERROREVENTfrom ..bintype import resolve_type_eventsfrom ..bintype import resolve_values_from_streamfrom ..dataio import ParseErrorfrom ..dataio import dumpbytesfrom ..recordstream import nthfrom ..tagids import tagnamesfrom ..treeop import STARTEVENTfrom ..treeop import ENDEVENTfrom ..treeop import prefix_ancestors_from_levelfrom ..utils import JsonObjects
from ._shared import tag_modelsfrom ._shared import RecordModelfrom ._shared import BinStorageIdfrom ._shared import COLORREFfrom ._shared import Marginfrom .controlchar import CHIDfrom .controlchar import ControlCharfrom .tagid16_document_properties import DocumentPropertiesfrom .tagid17_id_mappings import IdMappingsfrom .tagid18_bin_data import BinDatafrom .tagid20_border_fill import BorderFillfrom .tagid19_face_name import FaceNamefrom .tagid21_char_shape import CharShapefrom .tagid21_char_shape import LanguageStructfrom .tagid22_tab_def import TabDeffrom .tagid23_numbering import Numberingfrom .tagid24_bullet import Bulletfrom .tagid25_para_shape import ParaShapefrom .tagid26_style import Stylefrom .tagid27_doc_data import DocDatafrom .tagid28_distribute_doc_data import DistributeDocDatafrom .tagid30_compatible_document import CompatibleDocumentfrom .tagid31_layout_compatibility import LayoutCompatibilityfrom .tagid32_unknown import TagModel32from .tagid50_para_header import Paragraphfrom .tagid51_para_text import ParaTextfrom .tagid51_para_text import ParaTextChunksfrom .tagid52_para_char_shape import ParaCharShapefrom .tagid53_para_line_seg import ParaLineSegfrom .tagid53_para_line_seg import ParaLineSegListfrom .tagid53_para_line_seg import LineSegfrom .tagid54_para_range_tag import ParaRangeTagfrom .tagid55_ctrl_header import Controlfrom .controls.bookmark_control import BookmarkControlfrom .controls.columns_def import ColumnsDeffrom .controls.common_controls import CommonControlfrom .controls.dutmal import Dutmalfrom .controls.field import Fieldfrom .controls.field import FieldUnknownfrom .controls.field import FieldDatefrom .controls.field import FieldDocDatefrom .controls.field import FieldPathfrom .controls.field import FieldBookmarkfrom .controls.field import FieldMailMergefrom .controls.field import FieldCrossReffrom .controls.field import FieldFormulafrom .controls.field import FieldClickHerefrom .controls.field import FieldClickHereDatafrom .controls.field import FieldSummaryfrom .controls.field import FieldUserInfofrom .controls.field import FieldHyperLinkfrom .controls.field import FieldMemofrom .controls.field import FieldPrivateInfoSecurityfrom .controls.gshape_object_control import GShapeObjectControlfrom .controls.header_footer import HeaderFooterfrom .controls.header_footer import Headerfrom .controls.header_footer import Footerfrom .controls.hidden_comment import HiddenCommentfrom .controls.index_marker import IndexMarkerfrom .controls.note import Notefrom .controls.note import FootNotefrom .controls.note import EndNotefrom .controls.numbering import AutoNumberingfrom .controls.numbering import NewNumberingfrom .controls.page_hide import PageHidefrom .controls.page_number_position import PageNumberPositionfrom .controls.page_odd_even import PageOddEvenfrom .controls.section_def import SectionDeffrom .controls.table_control import TableControlfrom .controls.tcps_control import TCPSControlfrom .tagid56_list_header import ListHeaderfrom .tagid56_list_header import TableCaptionfrom .tagid56_list_header import TableCellfrom .tagid56_list_header import TextboxParagraphListfrom .tagid56_list_header import HeaderParagraphListfrom .tagid56_list_header import FooterParagraphListfrom .tagid57_page_def import PageDeffrom .tagid58_footnote_shape import FootnoteShapefrom .tagid59_page_border_fill import PageBorderFillfrom .tagid60_shape_component import ShapeComponentfrom .tagid61_table import TableBodyfrom .tagid62_shape_component_line import ShapeLinefrom .tagid63_shape_component_rectangle import ShapeRectanglefrom .tagid64_shape_component_ellipse import ShapeEllipsefrom .tagid65_shape_component_arc import ShapeArcfrom .tagid66_shape_component_polygon import ShapePolygonfrom .tagid67_shape_component_curve import ShapeCurvefrom .tagid68_shape_component_ole import ShapeOLEfrom .tagid69_shape_component_picture import ShapePicturefrom .tagid70_shape_component_container import ShapeContainerfrom .tagid71_ctrl_data import ControlDatafrom .tagid72_ctrl_eqedit import EqEditfrom .tagid74_shape_component_textart import ShapeTextArtfrom .tagid75_form_object import FormObjectfrom .tagid76_memo_shape import MemoShapefrom .tagid77_memo_list import MemoListfrom .tagid78_forbidden_char import ForbiddenCharfrom .tagid79_chart_data import ChartDatafrom .tagid99_shape_component_unknown import ShapeUnknown
# to suppress pyflake8 warning 'imported but not used'RecordModelBinStorageIdCOLORREFMarginDocumentPropertiesBinDataBorderFillCharShapeLanguageStructTabDefNumberingBulletParaShapeStyleDocDataDistributeDocDataCompatibleDocumentLayoutCompatibilityTagModel32ParagraphParaTextParaTextChunksParaCharShapeParaLineSegParaLineSegListLineSegParaRangeTagControlListHeaderTableCaptionTableCellTextboxParagraphListPageDefFootnoteShapePageBorderFillShapeComponentTableBodyShapeLineShapeRectangleShapeEllipseShapeArcShapePolygonShapeCurveShapeOLEShapePictureShapeContainerControlDataEqEditShapeTextArtFormObjectMemoShapeMemoListForbiddenCharChartDataShapeUnknownCHIDControlCharBookmarkControlColumnsDefCommonControlDutmalFieldFieldUnknownFieldDateFieldDocDateFieldPathFieldBookmarkFieldMailMergeFieldCrossRefFieldFormulaFieldClickHereFieldClickHereDataFieldSummaryFieldUserInfoFieldHyperLinkFieldMemoFieldPrivateInfoSecurityGShapeObjectControlHeaderFooterHeaderHeaderParagraphListFooterFooterParagraphListHiddenCommentIndexMarkerNoteFootNoteEndNoteAutoNumberingNewNumberingPageHidePageNumberPositionPageOddEvenSectionDefTableControlTCPSControl
logger = logging.getLogger(__name__)
class UnknownTagModel(RecordModel): pass
class Text(object): pass
def _check_tag_models(): for tagid, name in tagnames.items(): assert tagid in tag_models, 'RecordModel for %s is missing!' % name
_check_tag_models()
def init_record_parsing_context(base, record): ''' Initialize a context to parse the given record
the initializations includes followings: - context = dict(base) - context['record'] = record - context['stream'] = record payload stream
:param base: the base context to be shallow-copied into the new one :param record: to be parsed :returns: new context '''
return dict(base, record=record, stream=BytesIO(record['payload']))
def parse_models(context, records): for context, model in parse_models_intern(context, records): yield model
def parse_models_intern(context, records): context_models = ((init_record_parsing_context(context, record), record) for record in records) context_models = parse_models_with_parent(context_models) for context, model in context_models: stream = context['stream'] unparsed = stream.read() if unparsed: model['unparsed'] = unparsed yield context, model
def parse_models_with_parent(context_models): level_prefixed = ((model['level'], (context, model)) for context, model in context_models) root_item = (dict(), dict()) ancestors_prefixed = prefix_ancestors_from_level(level_prefixed, root_item) for ancestors, (context, model) in ancestors_prefixed: context['parent'] = ancestors[-1] parse_model(context, model) yield context, model
def parse_model(context, model): ''' HWPTAG로 모델 결정 후 기본 파싱 '''
stream = context['stream'] context['resolve_values'] = resolve_values_from_stream(stream) events = resolve_model_events(context, model) events = raise_on_errorevent(context, events) model['binevents'] = list(events)
logger.debug('model: %s', model['type'].__name__) logger.debug('%s', model['content'])
def raise_on_errorevent(context, events): binevents = list() for ev, item in events: yield ev, item binevents.append((ev, item)) if ev is ERROREVENT: e = item['exception'] msg = 'can\'t parse %s' % item['type'] pe = ParseError(msg) pe.cause = e pe.path = context.get('path') pe.treegroup = context.get('treegroup') pe.record = context.get('record') pe.offset = item.get('bin_offset') pe.binevents = binevents raise pe
def resolve_models(context, records): model_contexts = (dict(context, record=record, model=dict(record)) for record in records)
level_prefixed = ((context['model']['level'], context) for context in model_contexts) root_item = {} ancestors_prefixed = prefix_ancestors_from_level(level_prefixed, root_item) for ancestors, context in ancestors_prefixed: parent = ancestors[-1] context['parent'] = parent, parent.get('model', {})
record_frame = context['record'] context['type'] = RecordModel context['name'] = record_frame['tagname'] yield STARTEVENT, context for x in resolve_model_events(context, context['model']): yield x event, item = x context['value'] = item yield ENDEVENT, context
def resolve_model_events(context, model):
resolve_values = context['resolve_values']
model['type'] = model_type = tag_models.get(model['tagid'], UnknownTagModel)
for ev, item in resolve_type_events(model_type, context, resolve_values): yield ev, item
model['content'] = item['value']
extension_types = getattr(model['type'], 'extension_types', None) if extension_types: key = model['type'].get_extension_key(context, model) extension = extension_types.get(key) if extension is not None: # 예: Control -> TableControl로 바뀌는 경우, # Control의 member들은 이미 읽은 상태이고 # CommonControl, TableControl에서 각각 정의한 # 멤버들을 읽어들여야 함 for cls in get_extension_mro(extension, model['type']): extension_type_events = resolve_type_events(cls, context, resolve_values) for ev, item in extension_type_events: yield ev, item content = item['value'] model['content'].update(content) model['type'] = extension
if 'parent' in context: parent = context['parent'] parent_context, parent_model = parent parent_type = parent_model.get('type') parent_content = parent_model.get('content')
on_child = getattr(parent_type, 'on_child', None) if on_child: on_child(parent_content, parent_context, (context, model))
def get_extension_mro(cls, up_to_cls=None): mro = inspect.getmro(cls) mro = takewhile(lambda cls: cls is not up_to_cls, mro) mro = list(cls for cls in mro if 'attributes' in cls.__dict__) mro = reversed(mro) return mro
class ModelJsonEncoder(json.JSONEncoder):
def default(self, obj): if isinstance(obj, bytes): return obj.decode('latin1') return json.JSONEncoder.default(self, obj)
def model_to_json(model, *args, **kwargs): ''' convert a model to json ''' kwargs['cls'] = ModelJsonEncoder model = dict(model) model['type'] = model['type'].__name__ record = model record['payload'] = list(dumpbytes(record['payload'])) if 'unparsed' in model: model['unparsed'] = list(dumpbytes(model['unparsed'])) if 'binevents' in model: del model['binevents'] return json.dumps(model, *args, **kwargs)
def chain_iterables(iterables): for iterable in iterables: for item in iterable: yield item
class ModelStream(recordstream.RecordStream):
def models(self, **kwargs): # prepare binmodel parsing context kwargs.setdefault('version', self.version) try: kwargs.setdefault('path', self.path) except AttributeError: pass treegroup = kwargs.get('treegroup', None) if treegroup is not None: records = self.records_treegroup(treegroup) # TODO: kwargs models = parse_models(kwargs, records) else: groups = self.models_treegrouped(**kwargs) models = chain_iterables(groups) return models
def models_treegrouped(self, **kwargs): ''' iterable of iterable of the models, grouped by the top-level tree ''' kwargs.setdefault('version', self.version) for group_idx, records in enumerate(self.records_treegrouped()): kwargs['treegroup'] = group_idx yield parse_models(kwargs, records)
def model(self, idx): return nth(self.models(), idx)
def models_json(self, **kwargs): models = self.models(**kwargs) return JsonObjects(models, model_to_json)
def other_formats(self): d = super(ModelStream, self).other_formats() d['.models'] = self.models_json().open return d
def parse_model_events(self): context = dict(version=self.version)
def resolve_values_from_record(record): stream = BytesIO(record['payload']) return resolve_values_from_stream(stream)
for group_idx, records in enumerate(self.records_treegrouped()): context['treegroup'] = group_idx for x in resolve_models(context, records): event, item = x if item['type'] is RecordModel: if event is STARTEVENT: record_frame = item['record'] stream = BytesIO(record_frame['payload']) resolve_values = resolve_values_from_stream(stream) item['stream'] = stream item['resolve_values'] = resolve_values elif event is ENDEVENT: stream = item['stream'] item['leftover'] = { 'offset': stream.tell(), 'bytes': stream.read() } yield x
class DocInfo(ModelStream):
@property def idmappings(self): for model in self.models(): if model['type'] is IdMappings: return model
@property def facenames_by_lang(self): facenames = list(m for m in self.models() if m['type'] is FaceName) languages = 'ko', 'en', 'cn', 'jp', 'other', 'symbol', 'user' facenames_by_lang = dict() offset = 0 for lang in languages: n_fonts = self.idmappings['content'][lang + '_fonts'] facenames_by_lang[lang] = facenames[offset:offset + n_fonts] offset += n_fonts return facenames_by_lang
@property def charshapes(self): return (m for m in self.models() if m['type'] is CharShape)
def get_charshape(self, charshape_id): return nth(self.charshapes, charshape_id)
def charshape_lang_facename(self, charshape_id, lang): charshape = self.get_charshape(charshape_id) lang_facename_offset = charshape['content']['font_face'][lang] return self.facenames_by_lang[lang][lang_facename_offset]
class Sections(recordstream.Sections):
section_class = ModelStream
class Hwp5File(recordstream.Hwp5File):
docinfo_class = DocInfo bodytext_class = Sections
def create_context(file=None, **context): if file is not None: context['version'] = file.fileheader.version assert 'version' in context return context123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
import logging
from hwp5.dataio import StructTypefrom hwp5.dataio import Structfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import PrimitiveTypefrom hwp5.dataio import UINT32from hwp5.dataio import UINT16from hwp5.dataio import UINT8from hwp5.dataio import INT32from hwp5.dataio import INT8from hwp5.dataio import BYTEfrom hwp5.dataio import HWPUNIT16from hwp5.dataio import SHWPUNITfrom hwp5.dataio import N_ARRAY
logger = logging.getLogger(__name__)
tag_models = dict()
class RecordModelType(StructType):
def __new__(mcs, name, bases, attrs): cls = StructType.__new__(mcs, name, bases, attrs) if 'tagid' in attrs: tagid = attrs['tagid'] assert tagid not in tag_models tag_models[tagid] = cls return cls
class RecordModel(object, metaclass=RecordModelType): pass
class BinStorageId(UINT16): pass
class COLORREF(int, metaclass=PrimitiveType): binfmt = INT32.binfmt never_instantiate = False
def __getattr__(self, name): if name == 'r': return self & 0xff elif name == 'g': return (self & 0xff00) >> 8 elif name == 'b': return (self & 0xff0000) >> 16 elif name == 'a': return int((self & 0xff000000) >> 24) elif name == 'rgb': return self.r, self.g, self.b
def __str__(self): return '#%02x%02x%02x' % (self.r, self.g, self.b)
def __repr__(self): class_name = self.__class__.__name__ value = '(0x%02x, 0x%02x, 0x%02x)' % self.rgb return class_name + value
class Margin(Struct): def attributes(): yield HWPUNIT16, 'left' yield HWPUNIT16, 'right' yield HWPUNIT16, 'top' yield HWPUNIT16, 'bottom' attributes = staticmethod(attributes)
class Coord(Struct): def attributes(): yield SHWPUNIT, 'x' yield SHWPUNIT, 'y' attributes = staticmethod(attributes)
class Border(Struct):
# 표 20 테두리선 종류 StrokeEnum = Enum('none', 'solid', 'dashed', 'dotted', 'dash-dot', 'dash-dot-dot', 'long-dash', 'large-dot', 'double', 'double-2', 'double-3', 'triple', 'wave', 'double-wave', 'inset', 'outset', 'groove', 'ridge') StrokeType = Flags(UINT8, 0, 4, StrokeEnum, 'stroke_type')
# 표 21 테두리선 굵기 widths = {'0.1mm': 0, '0.12mm': 1, '0.15mm': 2, '0.2mm': 3, '0.25mm': 4, '0.3mm': 5, '0.4mm': 6, '0.5mm': 7, '0.6mm': 8, '0.7mm': 9, '1.0mm': 10, '1.5mm': 11, '2.0mm': 12, '3.0mm': 13, '4.0mm': 14, '5.0mm': 15} WidthEnum = Enum(**widths) Width = Flags(UINT8, 0, 4, WidthEnum, 'width')
def attributes(cls): yield cls.StrokeType, 'stroke_flags', yield cls.Width, 'width_flags', yield COLORREF, 'color', attributes = classmethod(attributes)
class BorderLine(Struct): ''' 표 81 테두리 선 정보 '''
LineEnd = Enum('round', 'flat') ArrowShape = Enum('none', 'arrow', 'arrow2', 'diamond', 'circle', 'rect', 'diamondfilled', 'disc', 'rectfilled') ArrowSize = Enum('smallest', 'smaller', 'small', 'abitsmall', 'normal', 'abitlarge', 'large', 'larger', 'largest')
''' 표 82 테두리 선 정보 속성 ''' Flags = Flags(UINT32, 0, 5, Border.StrokeEnum, 'stroke', 6, 9, LineEnd, 'line_end', 10, 15, ArrowShape, 'arrow_start', 16, 21, ArrowShape, 'arrow_end', 22, 25, ArrowSize, 'arrow_start_size', 26, 29, ArrowSize, 'arrow_end_size', 30, 'arrow_start_fill', 31, 'arrow_end_fill')
def attributes(cls): yield COLORREF, 'color' yield INT32, 'width' yield cls.Flags, 'flags' attributes = classmethod(attributes)
class Fill(Struct): pass
class FillNone(Fill): def attributes(): yield UINT32, 'size', # SPEC is confusing attributes = staticmethod(attributes)
class FillColorPattern(Fill): ''' 표 23 채우기 정보 ''' PatternTypeEnum = Enum(NONE=255, HORIZONTAL=0, VERTICAL=1, BACKSLASH=2, SLASH=3, GRID=4, CROSS=5) PatternTypeFlags = Flags(UINT32, 0, 7, PatternTypeEnum, 'pattern_type')
def attributes(cls): yield COLORREF, 'background_color', yield COLORREF, 'pattern_color', yield cls.PatternTypeFlags, 'pattern_type_flags', attributes = classmethod(attributes)
class FillImage(Fill): FillImageEnum = Enum(TILE_ALL=0, TILE_HORIZONTAL_TOP=1, TILE_HORIZONTAL_BOTTOM=2, TILE_VERTICAL_LEFT=3, TILE_VERTICAL_RIGHT=4, RESIZE=5, CENTER=6, CENTER_TOP=7, CENTER_BOTTOM=8, LEFT_MIDDLE=9, LEFT_TOP=10, LEFT_BOTTOM=11, RIGHT_MIDDLE=12, RIGHT_TOP=13, RIGHT_BOTTOM=14, NONE=15) FillImageFlags = Flags(BYTE, 0, 16, FillImageEnum, 'fillimage_type')
EffectEnum = Enum(REAL_PIC=0, GRAY_SCALE=1, BLACK_WHITE=2, PATTERN8x8=3) EffectFlags = Flags(UINT8, 0, 8, EffectEnum, 'effect_type')
def attributes(cls): yield cls.FillImageFlags, 'flags' yield INT8, 'brightness' yield INT8, 'contrast' yield cls.EffectFlags, 'effect' yield UINT16, 'bindata_id' attributes = classmethod(attributes)
class Coord32(Struct): def attributes(): yield UINT32, 'x' yield UINT32, 'y' attributes = staticmethod(attributes)
GradationTypeEnum = Enum(LINEAR=1, CIRCULAR=2, CONICAL=3, RECTANGULAR=4)GradationTypeFlags = Flags(BYTE, 0, 8, GradationTypeEnum, 'gradation_type')
class FillGradation(Fill): def attributes(): yield GradationTypeFlags, 'type', yield UINT32, 'shear', # 기울임 각 (도) yield Coord32, 'center', yield UINT32, 'blur', # 번짐 정도: 0-100 # TODO: 스펙 1.2에 따르면 색상 수 > 2인 경우 # 색상이 바뀌는 위치 배열이 온다고 함 yield N_ARRAY(UINT32, COLORREF), 'colors', attributes = staticmethod(attributes)
def ref_parent_member(member_name): def f(context, values): context, model = context['parent'] return model['content'][member_name] f.__doc__ = 'PARENTREC.' + member_name return f123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literalsimport reimport sys
from hwp5.dataio import PrimitiveTypefrom hwp5.dataio import UINT32from hwp5.dataio import UINT16from hwp5.dataio import UINT8
PY3 = sys.version_info.major == 3if PY3: unichr = chr
class CHID(str, metaclass=PrimitiveType):
fixed_size = 4
# Common controls GSO = 'gso ' TBL = 'tbl ' LINE = '$lin' RECT = '$rec' ELLI = '$ell' ARC = '$arc' POLY = '$pol' CURV = '$cur' EQED = 'eqed' PICT = '$pic' OLE = '$ole' CONTAINER = '$con'
# Controls SECD = 'secd' COLD = 'cold' HEADER = 'head' FOOTER = 'foot' FN = 'fn ' EN = 'en ' ATNO = 'atno' NWNO = 'nwno' PGHD = 'pghd' PGCT = 'pgct' PGNP = 'pgnp' IDXM = 'idxm' BOKM = 'bokm' TCPS = 'tcps' TDUT = 'tdut' TCMT = 'tcmt'
# Field starts FIELD_UNK = '%unk' FIELD_DTE = '%dte' FIELD_DDT = '%ddt' FIELD_PAT = '%pat' FIELD_BMK = '%bmk' FIELD_MMG = '%mmg' FIELD_XRF = '%xrf' FIELD_FMU = '%fmu' FIELD_CLK = '%clk' FIELD_SMR = '%smr' FIELD_USR = '%usr' FIELD_HLK = '%hlk' FIELD_REVISION_SIGN = '%sig' FIELD_REVISION_DELETE = '%%*d' FIELD_REVISION_ATTACH = '%%*a' FIELD_REVISION_CLIPPING = '%%*C' FIELD_REVISION_SAWTOOTH = '%%*S' FIELD_REVISION_THINKING = '%%*T' FIELD_REVISION_PRAISE = '%%*P' FIELD_REVISION_LINE = '%%*L' FIELD_REVISION_SIMPLECHANGE = '%%*c' FIELD_REVISION_HYPERLINK = '%%*h' FIELD_REVISION_LINEATTACH = '%%*A' FIELD_REVISION_LINELINK = '%%*i' FIELD_REVISION_LINETRANSFER = '%%*t' FIELD_REVISION_RIGHTMOVE = '%%*r' FIELD_REVISION_LEFTMOVE = '%%*l' FIELD_REVISION_TRANSFER = '%%*n' FIELD_REVISION_SIMPLEINSERT = '%%*e' FIELD_REVISION_SPLIT = '%spl' FIELD_REVISION_CHANGE = '%%mr' FIELD_MEMO = '%%me' FIELD_PRIVATE_INFO_SECURITY = '%cpr'
def decode(bytes, context=None): if PY3: return ( chr(bytes[3]) + chr(bytes[2]) + chr(bytes[1]) + chr(bytes[0]) ) else: return bytes[3] + bytes[2] + bytes[1] + bytes[0] decode = staticmethod(decode)
class ControlChar(object): class CHAR(object): size = 1
class INLINE(object): size = 8
class EXTENDED(object): size = 8 chars = {0x00: ('NULL', CHAR), 0x01: ('CTLCHR01', EXTENDED), 0x02: ('SECTION_COLUMN_DEF', EXTENDED), 0x03: ('FIELD_START', EXTENDED), 0x04: ('FIELD_END', INLINE), 0x05: ('CTLCHR05', INLINE), 0x06: ('CTLCHR06', INLINE), 0x07: ('CTLCHR07', INLINE), 0x08: ('TITLE_MARK', INLINE), 0x09: ('TAB', INLINE), 0x0a: ('LINE_BREAK', CHAR), 0x0b: ('DRAWING_TABLE_OBJECT', EXTENDED), 0x0c: ('CTLCHR0C', EXTENDED), 0x0d: ('PARAGRAPH_BREAK', CHAR), 0x0e: ('CTLCHR0E', EXTENDED), 0x0f: ('HIDDEN_EXPLANATION', EXTENDED), 0x10: ('HEADER_FOOTER', EXTENDED), 0x11: ('FOOT_END_NOTE', EXTENDED), 0x12: ('AUTO_NUMBER', EXTENDED), 0x13: ('CTLCHR13', INLINE), 0x14: ('CTLCHR14', INLINE), 0x15: ('PAGE_CTLCHR', EXTENDED), 0x16: ('BOOKMARK', EXTENDED), 0x17: ('CTLCHR17', EXTENDED), 0x18: ('HYPHEN', CHAR), 0x1e: ('NONBREAK_SPACE', CHAR), 0x1f: ('FIXWIDTH_SPACE', CHAR)} names = dict((unichr(code), name) for code, (name, kind) in chars.items()) kinds = dict((unichr(code), kind) for code, (name, kind) in chars.items())
def _populate(cls): for ch, name in cls.names.items(): setattr(cls, name, ch) _populate = classmethod(_populate) REGEX_CONTROL_CHAR = re.compile(b'[\x00-\x1f]\x00')
def find(cls, data, start_idx): while True: m = cls.REGEX_CONTROL_CHAR.search(data, start_idx) if m is not None: i = m.start() if i & 1 == 1: start_idx = i + 1 continue if PY3: char = unichr(data[i]) else: char = unichr(ord(data[i])) size = cls.kinds[char].size return i, i + (size * 2) data_len = len(data) return data_len, data_len find = classmethod(find)
def decode(cls, bytes): code = UINT16.decode(bytes[0:2]) ch = unichr(code) if cls.kinds[ch].size == 8: bytes = bytes[2:2 + 12] if ch == ControlChar.TAB: param = dict(width=UINT32.decode(bytes[0:4]), unknown0=UINT8.decode(bytes[4:5]), unknown1=UINT8.decode(bytes[5:6]), unknown2=bytes[6:]) return dict(code=code, param=param) else: chid = CHID.decode(bytes[0:4]) param = bytes[4:12] return dict(code=code, chid=chid, param=param) else: return dict(code=code) decode = classmethod(decode)
def get_kind_by_code(cls, code): ch = unichr(code) return cls.kinds[ch] get_kind_by_code = classmethod(get_kind_by_code)
def get_name_by_code(cls, code): ch = unichr(code) return cls.names.get(ch, 'CTLCHR%02x' % code) get_name_by_code = classmethod(get_name_by_code)
ControlChar._populate()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controls.bookmark_control import BookmarkControlfrom hwp5.binmodel.controls.columns_def import ColumnsDeffrom hwp5.binmodel.controls.common_controls import CommonControlfrom hwp5.binmodel.controls.dutmal import Dutmalfrom hwp5.binmodel.controls.field import Fieldfrom hwp5.binmodel.controls.field import FieldUnknownfrom hwp5.binmodel.controls.field import FieldDatefrom hwp5.binmodel.controls.field import FieldDocDatefrom hwp5.binmodel.controls.field import FieldPathfrom hwp5.binmodel.controls.field import FieldBookmarkfrom hwp5.binmodel.controls.field import FieldMailMergefrom hwp5.binmodel.controls.field import FieldCrossReffrom hwp5.binmodel.controls.field import FieldFormulafrom hwp5.binmodel.controls.field import FieldClickHerefrom hwp5.binmodel.controls.field import FieldClickHereDatafrom hwp5.binmodel.controls.field import FieldSummaryfrom hwp5.binmodel.controls.field import FieldUserInfofrom hwp5.binmodel.controls.field import FieldHyperLinkfrom hwp5.binmodel.controls.field import FieldMemofrom hwp5.binmodel.controls.field import FieldPrivateInfoSecurityfrom hwp5.binmodel.controls.gshape_object_control import GShapeObjectControlfrom hwp5.binmodel.controls.header_footer import HeaderFooterfrom hwp5.binmodel.controls.hidden_comment import HiddenCommentfrom hwp5.binmodel.controls.index_marker import IndexMarkerfrom hwp5.binmodel.controls.note import Notefrom hwp5.binmodel.controls.note import FootNotefrom hwp5.binmodel.controls.note import EndNotefrom hwp5.binmodel.controls.numbering import AutoNumberingfrom hwp5.binmodel.controls.numbering import NewNumberingfrom hwp5.binmodel.controls.page_hide import PageHidefrom hwp5.binmodel.controls.page_number_position import PageNumberPositionfrom hwp5.binmodel.controls.page_odd_even import PageOddEvenfrom hwp5.binmodel.controls.section_def import SectionDeffrom hwp5.binmodel.controls.table_control import TableControlfrom hwp5.binmodel.controls.tcps_control import TCPSControl
# suppress pyflake8 warning 'imported but not used'BookmarkControlColumnsDefCommonControlDutmalFieldFieldUnknownFieldDateFieldDocDateFieldPathFieldBookmarkFieldMailMergeFieldCrossRefFieldFormulaFieldClickHereFieldClickHereDataFieldSummaryFieldUserInfoFieldHyperLinkFieldMemoFieldPrivateInfoSecurityGShapeObjectControlHeaderFooterHiddenCommentIndexMarkerNoteFootNoteEndNoteAutoNumberingNewNumberingPageHidePageNumberPositionPageOddEvenSectionDefTableControlTCPSControl1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelTypefrom hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_CTRL_HEADERfrom hwp5.binmodel.controlchar import CHID
control_models = dict()
class ControlType(RecordModelType):
def __new__(mcs, name, bases, attrs): cls = RecordModelType.__new__(mcs, name, bases, attrs) if 'chid' in attrs: chid = attrs['chid'] assert chid not in control_models control_models[chid] = cls return cls
class Control(RecordModel, metaclass=ControlType): ''' 4.2.6. 컨트롤 헤더 '''
tagid = HWPTAG_CTRL_HEADER
def attributes(): yield CHID, 'chid' attributes = staticmethod(attributes)
extension_types = control_models
def get_extension_key(cls, context, model): ''' chid ''' return model['content']['chid'] get_extension_key = classmethod(get_extension_key)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.dataio import UINT32from hwp5.dataio import UINT16from hwp5.dataio import BSTRfrom hwp5.binmodel.tagid71_ctrl_data import ControlDatafrom hwp5.binmodel.controls._shared import Control
class BookmarkControl(Control): ''' 4.2.10.11. 책갈피 ''' chid = CHID.BOKM
def attributes(): if False: yield attributes = staticmethod(attributes)
class BookmarkControlData(ControlData):
parent_model_type = BookmarkControl
def attributes(): yield UINT32, 'unknown1' yield UINT32, 'unknown2' yield UINT16, 'unknown3' yield BSTR, 'name' attributes = staticmethod(attributes)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import Structfrom hwp5.dataio import UINT16from hwp5.dataio import WORDfrom hwp5.dataio import HWPUNIT16from hwp5.dataio import X_ARRAYfrom hwp5.dataio import ref_member_flagfrom hwp5.binmodel.controls._shared import Controlfrom hwp5.binmodel._shared import Border
class Column0(Struct):
@staticmethod def attributes(): yield WORD, 'width'
class Column(Struct): @staticmethod def attributes(): yield WORD, 'spacing' yield WORD, 'width'
class ColumnsDef(Control): ''' 4.2.10.2. 단 정의 ''' chid = CHID.COLD
Kind = Enum('normal', 'distribute', 'parallel') Direction = Enum('l2r', 'r2l', 'both') Flags = Flags(UINT16, 0, 1, Kind, 'kind', 2, 9, 'count', 10, 11, Direction, 'direction', 12, 'same_widths')
def attributes(cls): yield cls.Flags, 'flags' yield HWPUNIT16, 'spacing'
def not_same_widths(context, values): ''' flags.same_widths == 0 ''' return not values['flags'].same_widths
def n_entries(member_ref): def n_entries(context, values): n_columns = member_ref(context, values) return n_columns - 1 return n_entries
yield dict(name='column0', type=Column0, condition=not_same_widths) yield dict(name='columns', type=X_ARRAY(Column, n_entries(ref_member_flag('flags', 'count'))), condition=not_same_widths) yield UINT16, 'attr2' yield Border, 'splitter' attributes = classmethod(attributes)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controls._shared import Controlfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT32from hwp5.dataio import SHWPUNITfrom hwp5.dataio import HWPUNITfrom hwp5.dataio import INT16from hwp5.dataio import BSTRfrom hwp5.binmodel._shared import Margin
class CommonControl(Control):
# 표 65 개체 공통 속성의 속성 Flow = Enum(FLOAT=0, BLOCK=1, BACK=2, FRONT=3) TextSide = Enum(BOTH=0, LEFT=1, RIGHT=2, LARGER=3) VRelTo = Enum(PAPER=0, PAGE=1, PARAGRAPH=2) HRelTo = Enum(PAPER=0, PAGE=1, COLUMN=2, PARAGRAPH=3) VAlign = Enum(TOP=0, MIDDLE=1, BOTTOM=2) HAlign = Enum(LEFT=0, CENTER=1, RIGHT=2, INSIDE=3, OUTSIDE=4) WidthRelTo = Enum(PAPER=0, PAGE=1, COLUMN=2, PARAGRAPH=3, ABSOLUTE=4) HeightRelTo = Enum(PAPER=0, PAGE=1, ABSOLUTE=2) NumberCategory = Enum(NONE=0, FIGURE=1, TABLE=2, EQUATION=3)
CommonControlFlags = Flags(UINT32, 0, 'inline', 2, 'affect_line_spacing', 3, 4, VRelTo, 'vrelto', 5, 7, VAlign, 'valign', 8, 9, HRelTo, 'hrelto', 10, 12, HAlign, 'halign', 13, 'restrict_in_page', 14, 'overlap_others', 15, 17, WidthRelTo, 'width_relto', 18, 19, HeightRelTo, 'height_relto', 20, 'protect_size_when_vrelto_paragraph', 21, 23, Flow, 'flow', 24, 25, TextSide, 'text_side', 26, 27, NumberCategory, 'number_category')
MARGIN_LEFT = 0 MARGIN_RIGHT = 1 MARGIN_TOP = 2 MARGIN_BOTTOM = 3
def attributes(cls): ''' 표 64 개체 공통 속성 ''' yield cls.CommonControlFlags, 'flags', yield SHWPUNIT, 'y', # DIFFSPEC yield SHWPUNIT, 'x', # DIFFSPEC yield HWPUNIT, 'width', yield HWPUNIT, 'height', yield INT16, 'z_order', yield INT16, 'unknown1', yield Margin, 'margin', yield UINT32, 'instance_id', yield dict(type=INT16, name='unknown2', version=(5, 0, 0, 5)) yield dict(type=BSTR, name='description', version=(5, 0, 0, 5)) attributes = classmethod(attributes)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT32from hwp5.dataio import BSTRfrom hwp5.binmodel.controls._shared import Control
class Dutmal(Control): ''' 4.2.10.13. 덧말 ''' chid = CHID.TDUT Position = Enum(ABOVE=0, BELOW=1, CENTER=2) Align = Enum(BOTH=0, LEFT=1, RIGHT=2, CENTER=3, DISTRIBUTE=4, DISTRIBUTE_SPACE=5)
def attributes(cls): yield BSTR, 'maintext' yield BSTR, 'subtext' yield Flags(UINT32, 0, 31, cls.Position, 'position'), 'position-flags' yield UINT32, 'fsizeratio' yield UINT32, 'option' yield UINT32, 'stylenumber' yield Flags(UINT32, 0, 31, cls.Align, 'align'), 'align-flags' attributes = classmethod(attributes)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT32from hwp5.dataio import BSTRfrom hwp5.dataio import BYTEfrom hwp5.binmodel.tagid71_ctrl_data import ControlDatafrom hwp5.binmodel.controls._shared import Control
class Field(Control): ''' 4.2.10.15 필드 시작 '''
Flags = Flags(UINT32, 0, 'editableInReadOnly', 11, 14, 'visitedType', 15, 'modified')
def attributes(cls): yield cls.Flags, 'flags', yield BYTE, 'extra_attr', yield BSTR, 'command', yield UINT32, 'id', attributes = classmethod(attributes)
class FieldUnknown(Field): chid = CHID.FIELD_UNK
class FieldDate(Field): chid = CHID.FIELD_DTE
class FieldDocDate(Field): chid = CHID.FIELD_DDT
class FieldPath(Field): chid = CHID.FIELD_PAT
class FieldBookmark(Field): chid = CHID.FIELD_BMK
class FieldMailMerge(Field): chid = CHID.FIELD_MMG
class FieldCrossRef(Field): chid = CHID.FIELD_XRF
class FieldFormula(Field): chid = CHID.FIELD_FMU
class FieldClickHere(Field): chid = CHID.FIELD_CLK
class FieldClickHereData(ControlData): parent_model_type = FieldClickHere
class FieldSummary(Field): chid = CHID.FIELD_SMR
class FieldUserInfo(Field): chid = CHID.FIELD_USR
class FieldHyperLink(Field): chid = CHID.FIELD_HLK
def geturl(self): s = self.command.split(';') return s[0].replace('\\:', ':')
class FieldRevisionSign(Field): chid = CHID.FIELD_REVISION_SIGN
class FieldRevisionDelete(Field): chid = CHID.FIELD_REVISION_DELETE
class FieldRevisionAttach(Field): chid = CHID.FIELD_REVISION_ATTACH
class FieldRevisionClipping(Field): chid = CHID.FIELD_REVISION_CLIPPING
class FieldRevisionSawtooth(Field): chid = CHID.FIELD_REVISION_SAWTOOTH
class FieldRevisionThinking(Field): chid = CHID.FIELD_REVISION_THINKING
class FieldRevisionPraise(Field): chid = CHID.FIELD_REVISION_PRAISE
class FieldRevisionLine(Field): chid = CHID.FIELD_REVISION_LINE
class FieldRevisionSimpleChange(Field): chid = CHID.FIELD_REVISION_SIMPLECHANGE
class FieldRevisionHyperlink(Field): chid = CHID.FIELD_REVISION_HYPERLINK
class FieldRevisionLineAttach(Field): chid = CHID.FIELD_REVISION_LINEATTACH
class FieldRevisionLineLink(Field): chid = CHID.FIELD_REVISION_LINELINK
class FieldRevisionLineTransfer(Field): chid = CHID.FIELD_REVISION_LINETRANSFER
class FieldRevisionRightMove(Field): chid = CHID.FIELD_REVISION_RIGHTMOVE
class FieldRevisionLeftMove(Field): chid = CHID.FIELD_REVISION_LEFTMOVE
class FieldRevisionTransfer(Field): chid = CHID.FIELD_REVISION_TRANSFER
class FieldRevisionSimpleInsert(Field): chid = CHID.FIELD_REVISION_SIMPLEINSERT
class FieldRevisionSplit(Field): chid = CHID.FIELD_REVISION_SPLIT
class FieldRevisionChange(Field): chid = CHID.FIELD_REVISION_CHANGE
class FieldMemo(Field): chid = CHID.FIELD_MEMO
class FieldPrivateInfoSecurity(Field): chid = CHID.FIELD_PRIVATE_INFO_SECURITY12345678910111213141516171819202122232425262728# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controls.common_controls import CommonControlfrom hwp5.binmodel.controlchar import CHID
class GShapeObjectControl(CommonControl): chid = CHID.GSO123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT32from hwp5.binmodel.controls._shared import Control
class HeaderFooter(Control): ''' 4.2.10.3. 머리말/꼬리말 ''' Places = Enum(BOTH_PAGES=0, EVEN_PAGE=1, ODD_PAGE=2) Flags = Flags(UINT32, 0, 1, Places, 'places')
def attributes(cls): yield cls.Flags, 'flags' attributes = classmethod(attributes)
class Header(HeaderFooter): ''' 머리말 ''' chid = CHID.HEADER
class Footer(HeaderFooter): ''' 꼬리말 ''' chid = CHID.FOOTER12345678910111213141516171819202122232425262728293031323334# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.binmodel.controls._shared import Control
class HiddenComment(Control): ''' 4.2.10.14 숨은 설명 ''' chid = CHID.TCMT
def attributes(): if False: yield attributes = staticmethod(attributes)12345678910111213141516171819202122232425262728293031323334353637# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.dataio import UINT16from hwp5.dataio import BSTRfrom hwp5.binmodel.controls._shared import Control
class IndexMarker(Control): ''' 4.2.10.10. 찾아보기 표식 ''' chid = CHID.IDXM
def attributes(): yield BSTR, 'keyword1' yield BSTR, 'keyword2' yield UINT16, 'dummy' attributes = staticmethod(attributes)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.dataio import UINT32from hwp5.dataio import UINT16from hwp5.binmodel.controls._shared import Control
class Note(Control): ''' 4.2.10.4 미주/각주 ''' def attributes(): yield UINT32, 'number' yield UINT32, 'unknown0' yield UINT32, 'unknown1' yield dict(type=UINT16, name='unknown2', version=(5, 0, 3, 0)) yield dict(type=UINT16, name='unknown3', version=(5, 0, 3, 0)) attributes = staticmethod(attributes)
class FootNote(Note): ''' 각주 ''' chid = CHID.FN
class EndNote(Note): ''' 미주 ''' chid = CHID.EN123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT32from hwp5.dataio import UINT16from hwp5.dataio import WCHARfrom hwp5.binmodel.controls._shared import Control
class NumberingControl(Control): Kind = Enum( PAGE=0, FOOTNOTE=1, ENDNOTE=2, PICTURE=3, TABLE=4, EQUATION=5, UNKNOWN6=6, ) Flags = Flags(UINT32, 0, 3, Kind, 'kind', 4, 11, 'footnoteshape', 12, 'superscript')
def attributes(cls): yield cls.Flags, 'flags', yield UINT16, 'number', attributes = classmethod(attributes)
class AutoNumbering(NumberingControl): ''' 4.2.10.5. 자동 번호 ''' chid = CHID.ATNO
def attributes(cls): yield WCHAR, 'usersymbol', yield WCHAR, 'prefix', yield WCHAR, 'suffix', attributes = classmethod(attributes)
def __unicode__(self): prefix = u'' suffix = u'' if self.flags.kind == self.Kind.FOOTNOTE: if self.suffix != u'\x00': suffix = self.suffix return prefix + unicode(self.number) + suffix
class NewNumbering(NumberingControl): ''' 4.2.10.6. 새 번호 지정 ''' chid = CHID.NWNO123456789101112131415161718192021222324252627282930313233343536373839404142# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT32from hwp5.binmodel.controls._shared import Control
class PageHide(Control): ''' 4.2.10.7 감추기 ''' chid = CHID.PGHD Flags = Flags(UINT32, 0, 'header', 1, 'footer', 2, 'basepage', 3, 'pageborder', 4, 'pagefill', 5, 'pagenumber')
def attributes(cls): yield cls.Flags, 'flags' attributes = classmethod(attributes)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT32from hwp5.dataio import WCHARfrom hwp5.binmodel.controls._shared import Control
class PageNumberPosition(Control): ''' 4.2.10.9. 쪽 번호 위치 ''' chid = CHID.PGNP Position = Enum(NONE=0, TOP_LEFT=1, TOP_CENTER=2, TOP_RIGHT=3, BOTTOM_LEFT=4, BOTTOM_CENTER=5, BOTTOM_RIGHT=6, OUTSIDE_TOP=7, OUTSIDE_BOTTOM=8, INSIDE_TOP=9, INSIDE_BOTTOM=10) Flags = Flags(UINT32, 0, 7, 'shape', 8, 11, Position, 'position')
def attributes(cls): yield cls.Flags, 'flags' yield WCHAR, 'usersymbol' yield WCHAR, 'prefix' yield WCHAR, 'suffix' yield WCHAR, 'dash' attributes = classmethod(attributes)123456789101112131415161718192021222324252627282930313233343536373839# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT32from hwp5.binmodel.controls._shared import Control
class PageOddEven(Control): ''' 4.2.10.8 홀/짝수 조정 ''' chid = CHID.PGCT OddEven = Enum(BOTH_PAGES=0, EVEN_PAGE=1, ODD_PAGE=2) Flags = Flags(UINT32, 0, 1, OddEven, 'pages')
def attributes(cls): yield cls.Flags, 'flags' attributes = classmethod(attributes)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT32from hwp5.dataio import UINT16from hwp5.dataio import HWPUNITfrom hwp5.dataio import HWPUNIT16from hwp5.dataio import HexBytesfrom hwp5.binmodel.tagid71_ctrl_data import ControlDatafrom hwp5.binmodel.controls._shared import Control
class SectionDef(Control): ''' 4.2.10.1. 구역 정의 ''' chid = CHID.SECD
Flags = Flags(UINT32, 0, 'hide_header', 1, 'hide_footer', 2, 'hide_page', 3, 'hide_border', 4, 'hide_background', 5, 'hide_pagenumber', 8, 'show_border_on_first_page_only', 9, 'show_background_on_first_page_only', 16, 18, 'text_direction', 19, 'hide_blank_line', 20, 21, 'pagenum_on_split_section', 22, 'squared_manuscript_paper')
def attributes(cls): yield cls.Flags, 'flags', yield HWPUNIT16, 'columnspacing', yield HWPUNIT16, 'grid_vertical', yield HWPUNIT16, 'grid_horizontal', yield HWPUNIT, 'defaultTabStops', yield UINT16, 'numbering_shape_id', yield UINT16, 'starting_pagenum', yield UINT16, 'starting_picturenum', yield UINT16, 'starting_tablenum', yield UINT16, 'starting_equationnum', yield dict(type=UINT32, name='unknown1', version=(5, 0, 1, 7)) yield dict(type=UINT32, name='unknown2', version=(5, 0, 1, 7)) attributes = classmethod(attributes)
class SectionDefData(ControlData): parent_model_type = SectionDef
def attributes(): yield HexBytes(280), 'unknown' attributes = staticmethod(attributes)123456789101112131415161718192021222324252627282930313233343536# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controls.common_controls import CommonControlfrom hwp5.binmodel.controlchar import CHIDfrom hwp5.binmodel.tagid61_table import TableBody
class TableControl(CommonControl): chid = CHID.TBL
def on_child(cls, attributes, context, child): child_context, child_model = child if child_model['type'] is TableBody: # referenced in ListHeader parsing context['seen_table_body'] = True on_child = classmethod(on_child)1234567891011121314151617181920212223242526272829303132333435363738# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controlchar import CHIDfrom hwp5.dataio import BSTRfrom hwp5.binmodel.controls._shared import Control
class TCPSControl(Control): ''' 4.2.10.12. 글자 겹침 ''' chid = CHID.TCPS
def attributes(): yield BSTR, 'textlength' # yield UINT8, 'frameType' # yield INT8, 'internalCharacterSize' # yield UINT8, 'internalCharacterFold' # yield N_ARRAY(UINT8, UINT32), 'characterShapeIds' attributes = staticmethod(attributes)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_DOCUMENT_PROPERTIESfrom hwp5.dataio import UINT16from hwp5.dataio import UINT32
class DocumentProperties(RecordModel): ''' 4.1.1. 문서 속성 '''
tagid = HWPTAG_DOCUMENT_PROPERTIES
def attributes(): ''' 표 9 문서 속성 ''' yield UINT16, 'section_count', yield UINT16, 'page_startnum', yield UINT16, 'footnote_startnum', yield UINT16, 'endnote_startnum', yield UINT16, 'picture_startnum', yield UINT16, 'table_startnum', yield UINT16, 'math_startnum', yield UINT32, 'list_id', yield UINT32, 'paragraph_id', yield UINT32, 'character_unit_loc_in_paragraph', # yield UINT32, 'flags', # DIFFSPEC attributes = staticmethod(attributes)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_ID_MAPPINGSfrom hwp5.dataio import UINT32
class IdMappings(RecordModel): ''' 4.1.2. 아이디 매핑 헤더 '''
tagid = HWPTAG_ID_MAPPINGS
def attributes(): ''' 표 10 아이디 매핑 헤더 ''' yield UINT32, 'bindata', yield UINT32, 'ko_fonts', yield UINT32, 'en_fonts', yield UINT32, 'cn_fonts', yield UINT32, 'jp_fonts', yield UINT32, 'other_fonts', yield UINT32, 'symbol_fonts', yield UINT32, 'user_fonts', yield UINT32, 'borderfills', yield UINT32, 'charshapes', yield UINT32, 'tabdefs', yield UINT32, 'numberings', yield UINT32, 'bullets', yield UINT32, 'parashapes', yield UINT32, 'styles',
# memoshapes are found from 5.0.1.7, but not in 5.0.1.6 yield dict(type=UINT32, name='memoshapes', version=(5, 0, 1, 7))
# TODO unknown fields: # followings are found from 5.0.3.2, but not in 5.0.3.1 # but some 5.0.3.3 files do not have them: # 5.0.3.3/d6dfac424525298119de54410c3b22d74aa85511 # yield dict(type=UINT32, name='unknown1', version=(5, 0, 3, 2)) # yield dict(type=UINT32, name='unknown2', version=(5, 0, 3, 2)) attributes = staticmethod(attributes)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_BIN_DATAfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT16from hwp5.dataio import Structfrom hwp5.dataio import BSTRfrom hwp5.dataio import SelectiveTypefrom hwp5.dataio import ref_member_flagfrom hwp5.binmodel._shared import BinStorageId
class BinDataLink(Struct): def attributes(): yield BSTR, 'abspath' yield BSTR, 'relpath' attributes = staticmethod(attributes)
class BinDataEmbedding(Struct): def attributes(): yield BinStorageId, 'storage_id' yield BSTR, 'ext' attributes = staticmethod(attributes)
class BinDataStorage(Struct): def attributes(): yield BinStorageId, 'storage_id' attributes = staticmethod(attributes)
class BinData(RecordModel): ''' 4.1.3. 바이너리 데이터 '''
tagid = HWPTAG_BIN_DATA
# 표 13 바이너리 데이터 속성 StorageType = Enum(LINK=0, EMBEDDING=1, STORAGE=2) CompressionType = Enum(STORAGE_DEFAULT=0, YES=1, NO=2) AccessState = Enum(NEVER=0, OK=1, FAILED=2, FAILED_IGNORED=3) Flags = Flags(UINT16, 0, 3, StorageType, 'storage', 4, 5, CompressionType, 'compression', 16, 17, AccessState, 'access')
def attributes(cls): ''' 표 12 바이너리 데이터 ''' yield cls.Flags, 'flags' yield (SelectiveType(ref_member_flag('flags', 'storage'), {cls.StorageType.LINK: BinDataLink, cls.StorageType.EMBEDDING: BinDataEmbedding, cls.StorageType.STORAGE: BinDataStorage}), 'bindata') attributes = classmethod(attributes)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_FACE_NAMEfrom hwp5.dataio import Flagsfrom hwp5.dataio import Enumfrom hwp5.dataio import BSTRfrom hwp5.dataio import BYTEfrom hwp5.dataio import Struct
class AlternateFont(Struct): def attributes(): yield BYTE, 'kind' yield BSTR, 'name' attributes = staticmethod(attributes)
class Panose1(Struct): ''' 표 17 글꼴 유형 정보 '''
FamilyType = Enum('any', 'no_fit', 'text_display', 'script', 'decorative', 'pictorial')
SerifStyle = Enum('any', 'no_fit', 'cove', 'obtuse_cove', 'square_cove', 'obtuse_square_cove', 'square', 'thin', 'bone', 'exaggerated', 'triangle', 'normal_sans', 'obtuse_sans', 'perp_sans', 'flared', 'rounded')
Weight = Enum('any', 'no_fit', 'very_light', 'light', 'thin', 'book', 'medium', 'demi', 'bold', 'heavy', 'black', 'nord')
Proportion = Enum('any', 'no_fit', 'old_style', 'modern', 'even_width', 'expanded', 'condensed', 'very_expanded', 'very_condensed', 'monospaced')
Contrast = Enum('any', 'no_fit', 'none', 'very_low', 'low', 'medium_low', 'medium', 'medium_high', 'high', 'very_high')
StrokeVariation = Enum('any', 'no_fit', 'gradual_diag', 'gradual_tran', 'gradual_vert', 'gradual_horz', 'rapid_vert', 'rapid_horz', 'instant_vert')
ArmStyle = Enum('any', 'no_fit', 'straight_horz', 'straight_wedge', 'straight_vert', 'straight_single_serif', 'straight_double_serif', 'bent_horz', 'bent_wedge', 'bent_vert', 'bent_single_serif', 'bent_double_serif')
Letterform = Enum('any', 'no_fit', 'normal_contact', 'normal_weighted', 'normal_boxed', 'normal_flattened', 'normal_rounded', 'normal_off_center', 'normal_square', 'oblique_contact', 'oblique_weighted', 'oblique_boxed', 'oblique_flattened', 'oblique_rounded', 'oblique_off_center', 'oblique_square')
Midline = Enum('any', 'no_fit', 'standard_trimmed', 'standard_pointed', 'standard_serifed', 'high_trimmed', 'high_pointed', 'high_serifed', 'constant_trimmed', 'constant_pointed', 'constant_serifed', 'low_trimmed', 'low_pointed', 'low_serifed')
XHeight = Enum('any', 'no_fit', 'constant_small', 'constant_std', 'constant_large', 'ducking_small', 'ducking_std', 'ducking_large')
def attributes(): yield BYTE, 'family_type', yield BYTE, 'serif_style', yield BYTE, 'weight', yield BYTE, 'proportion', yield BYTE, 'contrast', yield BYTE, 'stroke_variation', yield BYTE, 'arm_style', yield BYTE, 'letterform', yield BYTE, 'midline', yield BYTE, 'x_height', attributes = staticmethod(attributes)
class FaceName(RecordModel): ''' 4.1.4. 글꼴 '''
tagid = HWPTAG_FACE_NAME
# 표 16 대체 글꼴 유형 FontFileType = Enum(UNKNOWN=0, TTF=1, HFT=2)
# 표 15 글꼴 속성 Flags = Flags(BYTE, 0, 1, FontFileType, 'font_file_type', 5, 'default', 6, 'metric', 7, 'alternate')
def attributes(cls): ''' 표 14 글꼴 ''' yield cls.Flags, 'flags' yield BSTR, 'name'
def has_alternate(context, values): ''' flags.alternate == 1 ''' return values['flags'].alternate
def has_metric(context, values): ''' flags.metric == 1 ''' return values['flags'].metric
def has_default(context, values): ''' flags.default == 1 ''' return values['flags'].default
yield dict(type=AlternateFont, name='alternate_font', condition=has_alternate) yield dict(type=Panose1, name='panose1', condition=has_metric) yield dict(type=BSTR, name='default_font', condition=has_default) attributes = classmethod(attributes)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_BORDER_FILLfrom hwp5.dataio import UINT32from hwp5.dataio import UINT16from hwp5.dataio import BYTEfrom hwp5.dataio import Flags# from hwp5.dataio import N_ARRAYfrom hwp5.binmodel._shared import Borderfrom hwp5.binmodel._shared import FillColorPatternfrom hwp5.binmodel._shared import FillGradationfrom hwp5.binmodel._shared import FillImage
class BorderFill(RecordModel): ''' 4.1.5. 테두리/배경 '''
tagid = HWPTAG_BORDER_FILL
# 표 19 테두리/배경 속성 BorderFlags = Flags(UINT16, 0, 'effect_3d', 1, 'effect_shadow', 2, 4, 'slash', 5, 6, 'backslash')
# 표 23 채우기 정보 FillFlags = Flags(UINT32, 0, 'colorpattern', 1, 'image', 2, 'gradation')
def attributes(cls): ''' 표 18 테두리/배경 속성 ''' yield cls.BorderFlags, 'borderflags' yield Border, 'left', yield Border, 'right', yield Border, 'top', yield Border, 'bottom', yield Border, 'diagonal' yield cls.FillFlags, 'fillflags'
def fill_colorpattern(context, values): ''' fillflags.fill_colorpattern ''' return values['fillflags'].colorpattern
def fill_image(context, values): ''' fillflags.fill_image ''' return values['fillflags'].image
def fill_gradation(context, values): ''' fillflags.fill_gradation ''' return values['fillflags'].gradation
yield dict(type=FillColorPattern, name='fill_colorpattern', condition=fill_colorpattern) yield dict(type=FillGradation, name='fill_gradation', condition=fill_gradation) yield dict(type=FillImage, name='fill_image', condition=fill_image) yield dict(type=UINT32, name='shape', condition=fill_gradation) yield dict(type=BYTE, name='blur_center', condition=fill_gradation) # 스펙 1.2의 표28 설명과는 달리, # 적어도 5.0.1.7에서, 있는 경우가 있고 없는 경우가 있음 # yield N_ARRAY(UINT32, BYTE), 'extended' # SPEC attributes = classmethod(attributes)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_CHAR_SHAPEfrom hwp5.dataio import StructTypefrom hwp5.dataio import Structfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT32from hwp5.dataio import INT32from hwp5.dataio import INT8from hwp5.dataio import UINT8from hwp5.dataio import WORDfrom hwp5.binmodel._shared import COLORREF
def LanguageStruct(name, basetype): ''' 표 29 글꼴에 대한 언어 ''' def attributes(): for lang in ('ko', 'en', 'cn', 'jp', 'other', 'symbol', 'user'): yield basetype, lang attributes = staticmethod(attributes) return StructType(name, (Struct,), dict(basetype=basetype, attributes=attributes))
class ShadowSpace(Struct): def attributes(): yield INT8, 'x' yield INT8, 'y' attributes = staticmethod(attributes)
class CharShape(RecordModel): ''' 4.1.6. 글자 모양 '''
tagid = HWPTAG_CHAR_SHAPE
# 표 30 글자 모양 속성 Underline = Enum(NONE=0, UNDERLINE=1, LINE_THROUGH=2, OVERLINE=3) UnderlineStyle = Enum(SOLID=0, DASHED=1, DOTTED=2, DASH_DOT=3, DASH_DOT_DOT=4, LONG_DASHED=5, LARGE_DOTTED=6, DOUBLE=7, LOWER_WEIGHTED=8, UPPER_WEIGHTED=9, MIDDLE_WEIGHTED=10) Flags = Flags(UINT32, 0, 'italic', 1, 'bold', 2, 3, Underline, 'underline', 4, 7, UnderlineStyle, 'underline_style', 8, 10, 'outline', 11, 13, 'shadow')
def attributes(cls): ''' 표 28 글자 모양 ''' yield LanguageStruct('FontFace', WORD), 'font_face', yield (LanguageStruct('LetterWidthExpansion', UINT8), 'letter_width_expansion') yield LanguageStruct('LetterSpacing', INT8), 'letter_spacing' yield LanguageStruct('RelativeSize', INT8), 'relative_size' yield LanguageStruct('Position', INT8), 'position' yield INT32, 'basesize', yield cls.Flags, 'charshapeflags', yield ShadowSpace, 'shadow_space' yield COLORREF, 'text_color', yield COLORREF, 'underline_color', yield COLORREF, 'shade_color', yield COLORREF, 'shadow_color', # yield UINT16, 'borderfill_id', # DIFFSPEC # yield COLORREF, 'strikeoutColor', # DIFFSPEC attributes = classmethod(attributes)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_TAB_DEFfrom hwp5.dataio import HWPUNITfrom hwp5.dataio import UINT32from hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import Structfrom hwp5.dataio import N_ARRAY
class Tab(Struct):
Kind = Enum(LEFT=0, RIGHT=1, CENTER=2, FLOAT=3)
Flags = Flags(UINT32, 0, 7, Kind, 'kind', 8, 15, 'fill_type')
@classmethod def attributes(cls): yield HWPUNIT, 'pos', yield cls.Flags, 'flags'
class TabDef(RecordModel): ''' 4.1.7. 탭 정의 '''
tagid = HWPTAG_TAB_DEF
''' 표 32 탭 정의 속성 ''' Flags = Flags(UINT32, 0, 'autotab_left', 1, 'autotab_right')
@classmethod def attributes(cls): yield dict(type=cls.Flags, name='flags') yield dict(type=N_ARRAY(UINT32, Tab), name='tabs')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_NUMBERINGfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT32from hwp5.dataio import UINT16from hwp5.dataio import INT32from hwp5.dataio import BSTRfrom hwp5.dataio import HWPUNIT16from hwp5.dataio import Structfrom hwp5.dataio import ARRAY
class NumberingLevel(Struct):
# 표 35 문단 머리 정보 속성 Align = Enum(LEFT=0, CENTER=1, RIGHT=2, UNKNOWN=3) DistanceType = Enum(RATIO=0, VALUE=1) Flags = Flags(UINT32, 0, 1, Align, 'align', 2, 'auto_width', 3, 'auto_indent', 4, DistanceType, 'space_type')
@classmethod def attributes(cls): ''' 표 34 문단 머리 정보 ''' yield cls.Flags, 'flags' yield HWPUNIT16, 'width_correction' yield UINT16, 'space' yield INT32, 'charshape_id' yield BSTR, 'numbering_format' # see 표 36 문단 번호 형식
class Numbering(RecordModel): ''' 4.1.8. 문단 번호 ''' tagid = HWPTAG_NUMBERING
Align = NumberingLevel.Align DistanceType = NumberingLevel.DistanceType Flags = NumberingLevel.Flags
def attributes(cls): ''' 표 33 문단 번호 ''' yield ARRAY(NumberingLevel, 7), 'levels' yield UINT16, 'starting_number' yield dict(type=ARRAY(UINT32, 7), name='unknown', version=(5, 0, 3, 0)) attributes = classmethod(attributes)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_BULLETfrom hwp5.dataio import INT32from hwp5.dataio import UINT32from hwp5.dataio import UINT16from hwp5.dataio import HWPUNIT16from hwp5.dataio import WCHARfrom hwp5.dataio import Enumfrom hwp5.dataio import Flags
BulletAlignEnum = Enum(LEFT=0, CENTER=1, RIGHT=2)BulletFlags = Flags(UINT32, 0, 1, BulletAlignEnum, 'align', 3, 'auto_indent')
class Bullet(RecordModel): ''' 4.1.9. 글머리표 '''
tagid = HWPTAG_BULLET
@staticmethod def attributes(): # TODO: Spec 1.2 is insufficient and incorrect yield BulletFlags, 'flags', yield HWPUNIT16, 'width', # 너비, 단위: HWPUNIT yield UINT16, 'space', # 본문과의 간격, 단위: % yield INT32, 'charshape_id', yield WCHAR, 'char'12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_PARA_SHAPEfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import INT32from hwp5.dataio import UINT32from hwp5.dataio import UINT16from hwp5.dataio import SHWPUNITfrom hwp5.dataio import HWPUNIT16
class ParaShape(RecordModel): ''' 4.1.10. 문단 모양 ''' tagid = HWPTAG_PARA_SHAPE
# 표 39 문단 모양 속성1 LineSpacingType = Enum(RATIO=0, FIXED=1, SPACEONLY=2, MINIMUM=3) Align = Enum(BOTH=0, LEFT=1, RIGHT=2, CENTER=3, DISTRIBUTE=4, DISTRIBUTE_SPACE=5) VAlign = Enum(FONT=0, TOP=1, CENTER=2, BOTTOM=3) LineBreakAlphabet = Enum(WORD=0, HYPHEN=1, CHAR=2) LineBreakHangul = Enum(WORD=0, CHAR=1) HeadShape = Enum(NONE=0, OUTLINE=1, NUMBER=2, BULLET=3) Flags1 = Flags(UINT32, 0, 1, LineSpacingType, 'linespacing_type', 2, 4, Align, 'align', 5, 6, LineBreakAlphabet, 'linebreak_alphabet', 7, LineBreakHangul, 'linebreak_hangul', 8, 'use_paper_grid', 9, 15, 'minimum_space', # 공백 최소값 16, 'protect_single_line', # 외톨이줄 보호 17, 'with_next_paragraph', # 다음 문단과 함께 18, 'protect', # 문단 보호 19, 'start_new_page', # 문단 앞에서 항상 쪽 나눔 20, 21, VAlign, 'valign', 22, 'lineheight_along_fontsize', # 글꼴에 어울리는 줄 높이 23, 24, HeadShape, 'head_shape', # 문단 머리 모양 25, 27, 'level', # 문단 수준 28, 'linked_border', # 문단 테두리 연결 여부 29, 'ignore_margin', # 문단 여백 무시 30, 'tail_shape') # 문단 꼬리 모양
# 표 40 문단 모양 속성2 Flags2 = Flags(UINT32, 0, 1, 'in_single_line', 2, 3, 'reserved', 4, 'autospace_alphabet', 5, 'autospace_number')
# 표 41 줄 간격 종류 Flags3 = Flags(UINT32, 0, 4, LineSpacingType, 'linespacing_type3')
Flags = Flags1
def attributes(cls): ''' 표 38 문단 모양 ''' yield cls.Flags, 'parashapeflags', yield INT32, 'doubled_margin_left', # 1/7200 * 2 # DIFFSPEC yield INT32, 'doubled_margin_right', # 1/7200 * 2 yield SHWPUNIT, 'indent', yield INT32, 'doubled_margin_top', # 1/7200 * 2 yield INT32, 'doubled_margin_bottom', # 1/7200 * 2 yield SHWPUNIT, 'linespacing', yield UINT16, 'tabdef_id', yield UINT16, 'numbering_bullet_id', yield UINT16, 'borderfill_id', yield HWPUNIT16, 'border_left', yield HWPUNIT16, 'border_right', yield HWPUNIT16, 'border_top', yield HWPUNIT16, 'border_bottom', yield dict(type=cls.Flags2, name='flags2', version=(5, 0, 1, 7)) # yield cls.Flags3, 'flags3', # DIFFSPEC # yield UINT32, 'lineSpacing', # DIFFSPEC attributes = classmethod(attributes)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_STYLEfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import BYTEfrom hwp5.dataio import BSTRfrom hwp5.dataio import INT16from hwp5.dataio import UINT16
class Style(RecordModel): ''' 4.1.11. 스타일 ''' tagid = HWPTAG_STYLE
# 표 43 스타일 종류 Kind = Enum(PARAGRAPH=0, CHAR=1) Flags = Flags(BYTE, 0, 1, Kind, 'kind')
def attributes(cls): ''' 표 42 스타일 ''' yield BSTR, 'local_name', yield BSTR, 'name', yield cls.Flags, 'flags', yield BYTE, 'next_style_id', yield INT16, 'lang_id', yield UINT16, 'parashape_id', yield UINT16, 'charshape_id',
# unknown fields # following fields are found from 5.0.0.0 yield UINT16, 'unknown' attributes = classmethod(attributes)12345678910111213141516171819202122232425262728293031# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_DOC_DATA
class DocData(RecordModel): ''' 4.1.12. 문서 임의의 데이터 ''' tagid = HWPTAG_DOC_DATA
# TODO1234567891011121314151617181920212223242526272829# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_DISTRIBUTE_DOC_DATA
class DistributeDocData(RecordModel): ''' 4.1.13. 배포용 문서 데이터 ''' tagid = HWPTAG_DISTRIBUTE_DOC_DATA123456789101112131415161718192021222324252627282930313233343536373839404142# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_COMPATIBLE_DOCUMENTfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT32
class CompatibleDocument(RecordModel): ''' 4.1.14. 호환 문서 ''' tagid = HWPTAG_COMPATIBLE_DOCUMENT
# 표 50 대상 프로그램 Target = Enum(DEFAULT=0, HWP2007=1, MSWORD=2) Flags = Flags(UINT32, 0, 1, 'target')
def attributes(cls): ''' 표 49 호환 문서 ''' yield cls.Flags, 'flags' attributes = classmethod(attributes)123456789101112131415161718192021222324252627282930313233343536373839# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_LAYOUT_COMPATIBILITYfrom hwp5.dataio import UINT32
class LayoutCompatibility(RecordModel): ''' 4.1.15. 레이아웃 호환성 ''' tagid = HWPTAG_LAYOUT_COMPATIBILITY
def attributes(): ''' 표 51 레이아웃 호환성 ''' yield UINT32, 'char', yield UINT32, 'paragraph', yield UINT32, 'section', yield UINT32, 'object', yield UINT32, 'field', attributes = staticmethod(attributes)1234567891011121314151617181920212223242526272829# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_BEGIN_PLUS_16
class TagModel32(RecordModel): tagid = HWPTAG_BEGIN_PLUS_16 # TODO12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_PARA_HEADERfrom hwp5.dataio import Flagsfrom hwp5.dataio import BYTEfrom hwp5.dataio import UINT32from hwp5.dataio import UINT16
class Paragraph(RecordModel): ''' 4.2.1. 문단 헤더 '''
tagid = HWPTAG_PARA_HEADER
# 표 54 단 나누기 종류 SplitFlags = Flags(BYTE, 0, 'new_section', 1, 'new_columnsdef', 2, 'new_page', 3, 'new_column') ControlMask = Flags(UINT32, 2, 'unknown1', 11, 'control', 21, 'new_number') Flags = Flags(UINT32, 31, 'unknown', 0, 30, 'chars')
def attributes(cls): ''' 표 53 문단 헤더 ''' yield cls.Flags, 'text', yield cls.ControlMask, 'controlmask', yield UINT16, 'parashape_id', yield BYTE, 'style_id', yield cls.SplitFlags, 'split', yield UINT16, 'charshapes', yield UINT16, 'rangetags', yield UINT16, 'linesegs', yield UINT32, 'instance_id', attributes = classmethod(attributes)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literalsfrom __future__ import division
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_PARA_TEXTfrom hwp5.dataio import ArrayTypefrom hwp5.binmodel.controlchar import ControlChar
class ParaTextChunks(list, metaclass=ArrayType):
def read(cls, f): bytes = f.read() return [x for x in cls.parse_chunks(bytes)] read = classmethod(read)
def parse_chunks(bytes): from hwp5.dataio import decode_utf16le_with_hypua size = len(bytes) idx = 0 while idx < size: ctrlpos, ctrlpos_end = ControlChar.find(bytes, idx) if idx < ctrlpos: text = decode_utf16le_with_hypua(bytes[idx:ctrlpos]) yield (idx // 2, ctrlpos // 2), text if ctrlpos < ctrlpos_end: cch = ControlChar.decode(bytes[ctrlpos:ctrlpos_end]) yield (ctrlpos // 2, ctrlpos_end // 2), cch idx = ctrlpos_end parse_chunks = staticmethod(parse_chunks)
class ParaText(RecordModel): ''' 4.2.2. 문단의 텍스트 ''' tagid = HWPTAG_PARA_TEXT
def attributes(): yield ParaTextChunks, 'chunks' attributes = staticmethod(attributes)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_PARA_CHAR_SHAPEfrom hwp5.dataio import ArrayTypefrom hwp5.dataio import X_ARRAYfrom hwp5.dataio import ARRAYfrom hwp5.dataio import UINT32from hwp5.dataio import UINT16from hwp5.binmodel._shared import ref_parent_member
class ParaCharShape(RecordModel): ''' 4.2.3. 문단의 글자 모양 ''' tagid = HWPTAG_PARA_CHAR_SHAPE
def attributes(): ''' 표 56 문단의 글자 모양 ''' yield dict(name='charshapes', type=X_ARRAY(ARRAY(UINT32, 2), ref_parent_member('charshapes'))) attributes = staticmethod(attributes)
class ParaCharShapeList(list, metaclass=ArrayType):
itemtype = ARRAY(UINT16, 2)
def read(cls, f, context): bytes = f.read() return cls.decode(bytes, context) read = classmethod(read)
def decode(payload, context=None): import struct fmt = 'II' unitsize = struct.calcsize('<' + fmt) unitcount = len(payload) / unitsize values = struct.unpack('<' + (fmt * unitcount), payload) return list(tuple(values[i * 2:i * 2 + 2]) for i in range(0, unitcount)) decode = staticmethod(decode)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_PARA_LINE_SEGfrom hwp5.binmodel._shared import ref_parent_memberfrom hwp5.dataio import ArrayTypefrom hwp5.dataio import Structfrom hwp5.dataio import UINT32from hwp5.dataio import Flagsfrom hwp5.dataio import SHWPUNITfrom hwp5.dataio import INT32from hwp5.dataio import X_ARRAY
class LineSeg(Struct): Flags = Flags(UINT32, # 0, 'first_in_page', # 1, 'first_in_column', # 16, 'empty', 17, 'line_head', 18, 'line_tail', # 19, 'auto_hyphen', 20, 'indented', 21, 'bullet')
def attributes(cls): yield INT32, 'chpos', yield SHWPUNIT, 'y', yield SHWPUNIT, 'height', yield SHWPUNIT, 'height_text', yield SHWPUNIT, 'height_baseline', yield SHWPUNIT, 'space_below', yield SHWPUNIT, 'x', yield SHWPUNIT, 'width' yield cls.Flags, 'lineseg_flags' attributes = classmethod(attributes)
class ParaLineSeg(RecordModel): ''' 4.2.4. 문단의 레이아웃 '''
tagid = HWPTAG_PARA_LINE_SEG
def attributes(cls): ''' 표 57 문단의 레이아웃 ''' yield dict(name='linesegs', type=X_ARRAY(LineSeg, ref_parent_member('linesegs'))) attributes = classmethod(attributes)
class ParaLineSegList(list, metaclass=ArrayType):
itemtype = LineSeg
def read(cls, f, context): payload = context['stream'].read() return cls.decode(context, payload) read = classmethod(read)
def decode(cls, context, payload): import struct unitfmt = 'iiiiiiiiHH' unitsize = struct.calcsize('<' + unitfmt) unitcount = len(payload) // unitsize values = struct.unpack('<' + unitfmt * unitcount, payload) names = ['chpos', 'y', 'height', 'height2', 'height85', 'space_below', 'x', 'width', 'a8', 'flags'] x = list(dict(zip(names, tuple(values[i * 10:i * 10 + 10]))) for i in range(0, unitcount)) for d in x: d['flags'] = LineSeg.Flags(d['flags']) return x decode = classmethod(decode)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_PARA_RANGE_TAGfrom hwp5.dataio import UINT32from hwp5.dataio import Flagsfrom hwp5.dataio import Structfrom hwp5.dataio import X_ARRAYfrom hwp5.binmodel._shared import ref_parent_member
class RangeTag(Struct): ''' 표 58 문단의 영역 태그 '''
Tag = Flags(UINT32, 0, 23, 'data', 24, 31, 'kind')
@classmethod def attributes(cls): yield UINT32, 'start' yield UINT32, 'end' yield cls.Tag, 'tag'
class ParaRangeTag(RecordModel): ''' 4.2.5. 문단의 영역 태그 '''
tagid = HWPTAG_PARA_RANGE_TAG
@staticmethod def attributes(): yield dict(name='range_tags', type=X_ARRAY(RangeTag, ref_parent_member('rangetags')))1234567891011121314151617181920212223242526272829303132333435363738394041424344# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel.controls._shared import Control
import hwp5.binmodel.controls.bookmark_controlimport hwp5.binmodel.controls.columns_defimport hwp5.binmodel.controls.common_controlsimport hwp5.binmodel.controls.dutmalimport hwp5.binmodel.controls.fieldimport hwp5.binmodel.controls.gshape_object_controlimport hwp5.binmodel.controls.header_footerimport hwp5.binmodel.controls.hidden_commentimport hwp5.binmodel.controls.index_markerimport hwp5.binmodel.controls.noteimport hwp5.binmodel.controls.numberingimport hwp5.binmodel.controls.page_hideimport hwp5.binmodel.controls.page_number_positionimport hwp5.binmodel.controls.page_odd_evenimport hwp5.binmodel.controls.section_defimport hwp5.binmodel.controls.table_controlimport hwp5.binmodel.controls.tcps_control
hwp5Control123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157# -*- coding: utf-8 -*-## pyhwp : hwp file format parser in python# Copyright (C) 2010-2023 mete0r <https://github.com/mete0r>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU Affero 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 Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.#from __future__ import absolute_importfrom __future__ import print_functionfrom __future__ import unicode_literals
from hwp5.binmodel._shared import RecordModelTypefrom hwp5.binmodel._shared import RecordModelfrom hwp5.tagids import HWPTAG_LIST_HEADERfrom hwp5.dataio import Enumfrom hwp5.dataio import Flagsfrom hwp5.dataio import UINT32from hwp5.dataio import UINT16from hwp5.dataio import SHWPUNITfrom hwp5.dataio import HWPUNITfrom hwp5.dataio import HWPUNIT16from hwp5.dataio import BYTEfrom hwp5.binmodel._shared import Marginfrom hwp5.binmodel.controls.table_control import TableControlfrom hwp5.binmodel.controls.gshape_object_control import GShapeObjectControlfrom hwp5.binmodel.controls.header_footer import Headerfrom hwp5.binmodel.controls.header_footer import Footerfrom hwp5.binmodel.tagid60_shape_component import ShapeComponent
list_header_models = dict()
class ListHeaderType(RecordModelType):
def __new__(mcs, name, bases, attrs): cls = RecordModelType.__new__(mcs, name, bases, attrs) if 'parent_model_type' in attrs: parent_model_type = attrs['parent_model_type'] before_tablebody = attrs.get('before_tablebody', False) list_type_key = parent_model_type, before_tablebody assert list_type_key not in list_header_models list_header_models[list_type_key] = cls return cls
class ListHeader(RecordModel, metaclass=ListHeaderType): ''' 4.2.7. 문단 리스트 헤더 '''
tagid = HWPTAG_LIST_HEADER
VAlign = Enum(TOP=0, MIDDLE=1, BOTTOM=2) Flags = Flags(UINT32, 0, 2, 'textdirection', 3, 4, 'linebreak', 5, 6, VAlign, 'valign')
def attributes(cls): ''' 표 60 문단 리스트 헤더 ''' yield UINT16, 'paragraphs', yield UINT16, 'unknown1', yield cls.Flags, 'listflags', attributes = classmethod(attributes)
extension_types = list_header_models
def get_extension_key(context, model): ''' (parent model type, after TableBody) ''' if 'parent' in context: context, model = context['parent'] seen_table_body = context.get('seen_table_body', False) return model['type'], seen_table_body get_extension_key = staticmethod(get_extension_key)
class TableCaption(ListHeader): ''' 표 66 캡션 리스트 ''' parent_model_type = TableControl before_tablebody = False
# 표 68 캡션 속성 Position = Enum(LEFT=0, RIGHT=1, TOP=2, BOTTOM=3) Flags = Flags(UINT32, 0, 1, Position, 'position', # 캡션이 긴 경우 테이블 여백 영역까지 확장 2, 'expand_to_margin')
def attributes(cls): ''' 표 67 캡션 ''' yield cls.Flags, 'flags', yield HWPUNIT, 'width', yield HWPUNIT16, 'separation', # 캡션과 틀 사이 간격 yield HWPUNIT, 'max_width', # expand_to_margin 고려한 최대 너비 attributes = classmethod(attributes)
class TableCell(ListHeader): ''' 표 75 셀 속성 ''' parent_model_type = TableControl before_tablebody = True
def attributes(): yield UINT16, 'col', yield UINT16, 'row', yield UINT16, 'colspan', yield UINT16, 'rowspan', yield SHWPUNIT, 'width', yield SHWPUNIT, 'height', yield Margin, 'padding', yield UINT16, 'borderfill_id', yield SHWPUNIT, 'unknown_width', attributes = staticmethod(attributes)
class GShapeObjectCaption(TableCaption): parent_model_type = GShapeObjectControl
class TextboxParagraphList(ListHeader): ''' 표 85 그리기 개체 글상자용 텍스트 속성 ''' parent_model_type = ShapeComponent
def attributes(): yield Margin, 'padding' yield HWPUNIT, 'maxwidth' attributes = staticmethod(attributes)
class HeaderFooterParagraphList(ListHeader): ''' 표 129 머리말/꼬리말 ''' def attributes(): yield HWPUNIT, 'width' yield HWPUNIT, 'height' yield BYTE, 'textrefsbitmap' yield BYTE, 'numberrefsbitmap' attributes = staticmethod(attributes)
class HeaderParagraphList(HeaderFooterParagraphList): parent_model_type = Header
class FooterParagraphList(HeaderFooterParagraphList): parent_model_type = Footersrc/README.rstAdded+6
src/hwp5/COPYINGAdded+661
src/hwp5/READMEAdded+73
src/hwp5/VERSION.txtAdded+1
src/hwp5/__init__.pyAdded+26
src/hwp5/binmodel/__init__.pyAdded+549
src/hwp5/binmodel/_shared.pyAdded+265
src/hwp5/binmodel/controlchar.pyAdded+215
src/hwp5/binmodel/controls/__init__.pyAdded+94
src/hwp5/binmodel/controls/_shared.pyAdded+59
src/hwp5/binmodel/controls/bookmark_control.pyAdded+50
src/hwp5/binmodel/controls/columns_def.pyAdded+84
src/hwp5/binmodel/controls/common_controls.pyAdded+81
src/hwp5/binmodel/controls/dutmal.pyAdded+48
src/hwp5/binmodel/controls/field.pyAdded+185
src/hwp5/binmodel/controls/gshape_object_control.pyAdded+28
src/hwp5/binmodel/controls/header_footer.pyAdded+48
src/hwp5/binmodel/controls/hidden_comment.pyAdded+34
src/hwp5/binmodel/controls/index_marker.pyAdded+37
src/hwp5/binmodel/controls/note.pyAdded+47
src/hwp5/binmodel/controls/numbering.pyAdded+69
src/hwp5/binmodel/controls/page_hide.pyAdded+42
src/hwp5/binmodel/controls/page_number_position.pyAdded+49
src/hwp5/binmodel/controls/page_odd_even.pyAdded+39
src/hwp5/binmodel/controls/section_def.pyAdded+73
src/hwp5/binmodel/controls/table_control.pyAdded+36
src/hwp5/binmodel/controls/tcps_control.pyAdded+38
src/hwp5/binmodel/tagid16_document_properties.pyAdded+47
src/hwp5/binmodel/tagid17_id_mappings.pyAdded+60
src/hwp5/binmodel/tagid18_bin_data.pyAdded+77
src/hwp5/binmodel/tagid19_face_name.pyAdded+136
src/hwp5/binmodel/tagid20_border_fill.pyAdded+89
src/hwp5/binmodel/tagid21_char_shape.pyAdded+90
src/hwp5/binmodel/tagid22_tab_def.pyAdded+60
src/hwp5/binmodel/tagid23_numbering.pyAdded+72
src/hwp5/binmodel/tagid24_bullet.pyAdded+52
src/hwp5/binmodel/tagid25_para_shape.pyAdded+97
src/hwp5/binmodel/tagid26_style.pyAdded+55
src/hwp5/binmodel/tagid27_doc_data.pyAdded+31
src/hwp5/binmodel/tagid28_distribute_doc_data.pyAdded+29
src/hwp5/binmodel/tagid30_compatible_document.pyAdded+42
src/hwp5/binmodel/tagid31_layout_compatibility.pyAdded+39
src/hwp5/binmodel/tagid32_unknown.pyAdded+29
src/hwp5/binmodel/tagid50_para_header.pyAdded+61
src/hwp5/binmodel/tagid51_para_text.pyAdded+61
src/hwp5/binmodel/tagid52_para_char_shape.pyAdded+64
src/hwp5/binmodel/tagid53_para_line_seg.pyAdded+95
src/hwp5/binmodel/tagid54_para_range_tag.pyAdded+54
src/hwp5/binmodel/tagid55_ctrl_header.pyAdded+44
src/hwp5/binmodel/tagid56_list_header.pyAdded+157